{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# importing the required libraries\nimport csv\nimport numpy as np\nimport keras\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Dense,Dropout,Activation,BatchNormalization\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom keras import layers,regularizers\nimport seaborn as sns\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom keras.optimizers import Adam,RMSprop","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"decay=1e-4\nxtrain = []\nytrain = []\nxtest  = []\n#rough  = []\nxval   = []\nyval   = []","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data extraction","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \ntrain =pd.read_csv(os.path.join(dirname,'train.csv'))\nprint(\"train\",np.shape(train))\ntest =pd.read_csv(os.path.join(dirname,'test.csv'))\nprint(\"test\",np.shape(test))\nsample_submission =pd.read_csv(os.path.join(dirname,'sample_submission.csv')) \nDig_MNIST=pd.read_csv(os.path.join(dirname,'Dig-MNIST.csv'))\n\nxtrain=train.drop('label',axis=1)\nytrain=train.label\nxtest = test.drop('id', axis = 1)\nxval=Dig_MNIST.drop('label',axis=1)\nyval=Dig_MNIST.label\n\n\nxtrain=xtrain.values\nxtest=xtest.values\nxval=xval.values\nytrain=ytrain.values\nyval=yval.values\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Mean normalization \nxtrain=xtrain.reshape(-1,28,28,1).astype('float32')\nxtest=xtest.reshape(-1,28,28,1).astype('float32')\nxval=xval.reshape(-1,28,28,1).astype('float32')\n\n\nxtrain=(xtrain-np.mean(xtrain))/255\nxtest=(xtest-np.mean(xtest))/255\nxval=(xval-np.mean(xval))/255","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(xtrain[0][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# analysing data distribution over all 10 classes\ny=train.label.value_counts()\nsns.barplot(y.index,y)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# now lets create our CNN model with >0.99 public score\nmodel=Sequential()\nmodel.add(layers.Conv2D(64, (3,3), padding='same', input_shape=(28, 28, 1)))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\nmodel.add(layers.Conv2D(64,  (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\nmodel.add(layers.Conv2D(64,  (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\n\nmodel.add(layers.MaxPooling2D(2, 2))\nmodel.add(layers.Dropout(0.2))\n\nmodel.add(layers.Conv2D(128, (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\nmodel.add(layers.Conv2D(128, (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\nmodel.add(layers.Conv2D(128, (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\n\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Dropout(0.2)) \n\nmodel.add(layers.Conv2D(256, (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\nmodel.add(layers.Conv2D(256, (3,3), padding='same'))\nmodel.add(layers.BatchNormalization(momentum=0.9, epsilon=1e-5, gamma_initializer=\"uniform\"))\nmodel.add(layers.LeakyReLU(alpha=0.1))\n\nmodel.add(layers.MaxPooling2D(2,2))\nmodel.add(layers.Dropout(0.4))\n\n\nmodel.add(layers.Flatten())\nmodel.add(layers.Dense(256))\nmodel.add(layers.LeakyReLU(alpha=0.1))\n\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dense(256))\nmodel.add(layers.LeakyReLU(alpha=0.1))\n\nmodel.add(layers.BatchNormalization())\nmodel.add(layers.Dense(10, activation='softmax'))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\noptimizer = RMSprop(learning_rate=0.002,rho=0.9)#,momentum=0.1,epsilon=1e-07,centered=True,name='RMSprop')\nmodel.compile(optimizer=optimizer,loss='sparse_categorical_crossentropy',metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# DATA AUGMENTATION","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(\n    rotation_range=11, \n    zoom_range=0.4, \n    width_shift_range=0.3, \n    height_shift_range=0.3,\n#     rescale=1./255\n)\ndatagen.fit(xtrain)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# REDUCING LEARNING RATE __ EARLY STOPPING\nlearning_rate_reduction = tf.keras.callbacks.ReduceLROnPlateau( \n    monitor='loss',    # Quantity to be monitored.\n    factor=0.2,       # Factor by which the learning rate will be reduced. new_lr = lr * factor\n    patience=2,        # The number of epochs with no improvement after which learning rate will be reduced.\n    verbose=1,         # 0: quiet - 1: update messages.\n    mode=\"auto\",       # {auto, min, max}. In min mode, lr will be reduced when the quantity monitored has stopped decreasing; \n                       # in the max mode it will be reduced when the quantity monitored has stopped increasing; \n                       # in auto mode, the direction is automatically inferred from the name of the monitored quantity.\n    min_delta=0.0001,  # threshold for measuring the new optimum, to only focus on significant changes.\n    cooldown=0,        # number of epochs to wait before resuming normal operation after learning rate (lr) has been reduced.\n    min_lr=0.00001     # lower bound on the learning rate.\n    )\n\nes = EarlyStopping(monitor='val_loss', mode='min', verbose=1, patience=300, restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# FITTING OUR MODEL\nhistory=model.fit_generator(datagen.flow(xtrain, ytrain, batch_size=1024),\n                              steps_per_epoch=len(xtrain)//1024,\n                              epochs=50,\n                              validation_data=(np.array(xval),np.array(yval)),\n                              validation_steps=50,\n                              callbacks=[learning_rate_reduction, es])\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plotting Graphs\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\n\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ytest = model.predict_classes(xtest)\nid_col = np.arange(ytest.shape[0])\nsubmission = pd.DataFrame({'id': id_col, 'label': ytest})\nsubmission.to_csv('submission.csv', index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":1}