"""
***If you find this notebook useful then please upvote.***

"""
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load

import numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All" 
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session
#Importing required packages.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
#from sklearn.svm import SVC
from sklearn.linear_model import SGDClassifier
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score
%matplotlib inline
#Loading dataset
rwine = pd.read_csv('../input/red-wine-quality-cortez-et-al-2009/winequality-red.csv')
"""
## Data Preprocessing and Visualization
"""
#Let's check how the data is distributed
rwine.head()
#knowing number of features and data size
row,col=rwine.shape
print(row,",",col)
#Data Information 
rwine.info()
# There is no null values, and no categorical data
#knowing the number of red wine quality classes
rwine['quality'].value_counts()
#Making binary classificaion for the target by dividing wine as g for good and b for bad.
#Dividing wine as good and bad by giving the limit for the quality
bins = (2, 5.5, 8)
groups = ['b', 'g']
rwine['quality'] = pd.cut(rwine['quality'], bins = bins, labels = groups)
L_quality = LabelEncoder()
rwine['quality'] = L_quality.fit_transform(rwine['quality'])

rwine['quality'].value_counts()
#fig, axs = plt.subplots(5,2,figsize=(15,15))
#axs[0, 0].hist(rwine['fixed acidity'],bins=10) #original data
#axs[0, 0].set_title('fixed acidity')
#axs[0, 1].hist(rwine['volatile acidity'],bins=10) 
#axs[0, 1].set_title('volatile acidity')

df_train = rwine.sample(frac=0.7, random_state=0)
df_test = rwine.drop(df_train.index)

# Split features and target
X_train = df_train.drop('quality', axis=1)
X_test = df_test.drop('quality', axis=1)
y_train = df_train['quality']
y_test = df_test['quality']
from tensorflow import keras
from tensorflow.keras import layers

model = keras.Sequential([
    layers.Dense(1024, activation='relu', input_shape=[11]),
    layers.Dropout(0.3),
    layers.BatchNormalization(),
    layers.Dense(1024, activation='relu'),
    layers.Dropout(0.3),
    layers.BatchNormalization(),
    layers.Dense(1024, activation='relu'),
    layers.Dropout(0.3),
    layers.BatchNormalization(),
    layers.Dense(1, activation='sigmoid'),])
model.compile(
    optimizer='adam',
    loss='binary_crossentropy',
    metrics=['binary_accuracy'],
)

history = model.fit(
    X_train, y_train,
    validation_data=(X_test, y_test),
    batch_size=250,
    epochs=100,
    verbose=0
)


# Show the learning curves
history_df = pd.DataFrame(history.history)
history_df.loc[:, ['loss', 'val_loss']].plot();
history_df.loc[:, ['binary_accuracy', 'val_binary_accuracy']].plot()

print(("Best Validation Loss: {:0.4f}" +\
      "\nBest Validation Accuracy: {:0.4f}")\
      .format(history_df['val_loss'].min(), 
              history_df['val_binary_accuracy'].max()))