# 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 in 

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

from keras.utils.np_utils import to_categorical
import seaborn as sns

from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix

from keras.models import Sequential
from keras.layers import Conv2D,Dense,Flatten,MaxPool2D,Dropout,BatchNormalization
from keras.optimizers import Adam
from keras.preprocessing.image import ImageDataGenerator
from keras.callbacks import ReduceLROnPlateau
# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

        
train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')
test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')

#print(train)
#print(train.columns)
Y_train = train['label']
X_train = train.drop(columns=['label'],axis=1)
#print(y_train.describe())
#print(x_train.describe())

del train

#g = sns.countplot(y_train)


#To count the values of digits
#print(y_train.value_counts())


#Normalizing the pixels
X_train = X_train/255

#Reshaping the train values
X_train = X_train.values.reshape(-1,28,28,1)

#label encoding the hot vectors
Y_train = to_categorical(Y_train , num_classes=10)


#Splitting the data
x_train , x_test , y_train , y_test = train_test_split(X_train, Y_train, test_size=0.2 , random_state=101)

x_train = x_train.reshape(x_train.shape[0], 28, 28, 1)

#Sequential Model
model = Sequential()

#1st Layer
model.add(Conv2D(filters=32,kernel_size=(3,3),padding='same',input_shape=(28,28,1),activation='relu'))


model.add(Conv2D(filters=32,kernel_size=(3,3),padding='same',activation='relu'))


model.add(MaxPool2D(pool_size=(2,2)))


model.add(Dropout(0.25))

#2nd Layer
model.add(Conv2D(filters=64,kernel_size=(3,3),padding='same',activation='relu'))

model.add(Conv2D(filters=64,kernel_size=(3,3),padding='same',activation='relu'))


model.add(MaxPool2D(pool_size=(2,2),strides=(2,2)))


model.add(Dropout(0.25))

#3rd Layer

model.add(Flatten())
model.add(Dense(256,activation='relu'))

model.add(Dropout(0.5))
model.add(Dense(10,activation='softmax'))
# Any results you write to the current directory are saved as output.

# Define the optimizer
adam = Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)
model.compile(optimizer = adam , loss = "categorical_crossentropy", metrics=["accuracy"])


learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', 
                                            patience=3, 
                                            verbose=1, 
                                            factor=0.5, 
                                            min_lr=0.00001)


datagen = ImageDataGenerator(
        featurewise_center=False,  # set input mean to 0 over the dataset
        samplewise_center=False,  # set each sample mean to 0
        featurewise_std_normalization=False,  # divide inputs by std of the dataset
        samplewise_std_normalization=False,  # divide each input by its std
        zca_whitening=False,  # apply ZCA whitening
        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)
        zoom_range = 0.1, # Randomly zoom image 
        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)
        height_shift_range=0.1,  # randomly shift images vertically (fraction of total height)
        horizontal_flip=False,  # randomly flip images
        vertical_flip=False)  # randomly flip images


datagen.fit(X_train)

history = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=64),
                              epochs = 15, validation_data = (x_test,y_test),
                              verbose = 2, steps_per_epoch=X_train.shape[0] // 64
                              , callbacks=[learning_rate_reduction])


test = test.values.reshape(-1, 28, 28,1)

results = model.predict(test)
results = np.argmax(results,axis = 1)
results = pd.Series(results,name="Label")
submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1)
submission.to_csv("../working/ashish_cnn_mnist_datagen.csv",index=False)
#model.fit(x_train , y_train ,epochs=10 , batch_size = 50)


# Any results you write to the current directory are saved as output.