{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\n#import the necessary libraries\nimport pandas as pd\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nfrom keras.optimizers import Adam,RMSprop\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.utils import np_utils,plot_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom IPython.display import Image\nfrom keras.layers import Conv2D, MaxPooling2D\nfrom keras.callbacks import ReduceLROnPlateau,ModelCheckpoint,EarlyStopping\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix,accuracy_score\nfrom keras.datasets import mnist\n\n#set the backgroung style sheet\nsns.set_style(\"whitegrid\")\nimport os\nprint(os.listdir(\"../input\"))\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"#load the csv file in a dataframe using read_csv function\ndf = pd.read_csv('../input/digit-recognizer/train.csv')\ntest_df = pd.read_csv('../input/digit-recognizer/test.csv') \ndf.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df1_train = pd.read_csv('../input/mnist-in-csv/mnist_train.csv')\ndf1_train.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f912ae019c4c8688826e24f6c84f5b5f4af9eddc"},"cell_type":"code","source":"X = df.drop(\"label\",axis=1)\ny = df['label']\nX_1 = df1_train.drop(\"label\",axis=1)\ny_1 = df1_train['label']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3b7699d19e1b9896ef80f7ca49125daf5b2ea788"},"cell_type":"code","source":"X = X / 255.0\nX_1 = X_1 / 255.0\ntest_df = test_df / 255.0","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = np.concatenate((X, X_1), axis=0)\ny = np.concatenate((y, y_1), axis=0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = pd.DataFrame(X)\ny = pd.DataFrame(y)\n\nx_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.15,random_state=0)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"fc1f874c3bc004cbb49ec9403dfc7b1b8e4f66a8"},"cell_type":"code","source":"x_train = x_train.values.reshape(-1,28,28,1)\nx_test = x_test.values.reshape(-1,28,28,1)\ntest_df = test_df.values.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"13dc72b12c43a5bf3f45866258c03847e5f57ff6"},"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(64, (3, 3), input_shape=(28,28,1),padding=\"SAME\"))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(64, (3, 3),padding=\"SAME\"))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(Activation('relu'))\n\nmodel.add(Conv2D(128,(3, 3),padding=\"SAME\"))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(128, (3, 3),padding=\"SAME\"))\nmodel.add(BatchNormalization(axis=-1))\nmodel.add(Activation('relu'))\n\nmodel.add(Conv2D(192,(3, 3),padding=\"SAME\"))\nmodel.add(Activation('relu'))\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Conv2D(192,(5, 5),strides=2,padding=\"SAME\"))\nmodel.add(Activation('relu'))\n\nmodel.add(Flatten())\n\n# Fully connected layer\nmodel.add(Dense(256))\n# model.add(Dense(256))\nmodel.add(BatchNormalization())\nmodel.add(Activation('relu'))\nmodel.add(Dropout(0.3))\nmodel.add(Dense(10))\n\nmodel.add(Activation('softmax'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',patience=3, verbose=1,factor=0.5,min_lr=0.00001)\nbest_model = ModelCheckpoint('mnist_weights.h5', monitor='val_acc', verbose=1, save_best_only=True, mode='max')\n\nearly_stopping = EarlyStopping(monitor='val_loss', min_delta=1e-10, patience=10,restore_best_weights=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4abb4a1fdc4fe5ac881a96194eed718a7de34379"},"cell_type":"code","source":"model.compile(optimizer='adam',\n              loss='sparse_categorical_crossentropy',\n              metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"aug = ImageDataGenerator(\n    featurewise_center=False,  \n        samplewise_center=False,  \n        featurewise_std_normalization=False,  \n        samplewise_std_normalization=False, \n        rotation_range=10, \n        zoom_range = 0.,\n        width_shift_range=0.1,  \n        height_shift_range=0.1,  \n        horizontal_flip=False,\n        vertical_flip=False)\n\naug.fit(x_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d9edf9703631fb6a84ca50efe1b3ee7ec33a3e5c"},"cell_type":"code","source":"h = model.fit_generator(\n    aug.flow(x_train, y_train, batch_size=64),\n    validation_data=(x_test, y_test),\n    steps_per_epoch=len(x_train) // 64,\n    epochs=50, verbose=1,\n    callbacks=[learning_rate_reduction,best_model,early_stopping]\n    )\n\n# h = model.fit(x_train,y_train,validation_data = (x_test,y_test),epochs=50,batch_size=100,\n#                  callbacks=[learning_rate_reduction,best_model,early_stopping],shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(h.history).plot()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(x_test)\ny_pred = np.argmax(y_pred,axis = 1)\naccuracy_score(y_test,y_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cm = confusion_matrix(y_test,y_pred)\nf,ax = plt.subplots(figsize=(7, 7))\nsns.heatmap(cm, cmap='Blues',annot=True, linewidths=.5, fmt= '.1f',ax=ax)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(16,10))\ncount = 1\ny_true = list(y_test.values)\nfor i in range(len(y_pred)):\n    if count==11:\n        break\n    if y_true[i][0]!=y_pred[i]:\n        plt.subplot(2,5,count)\n        plt.imshow(x_test[i].reshape(28,28),cmap=plt.cm.binary)\n        plt.xlabel(\"Predicted label :{}\\nTrue label :{}\".format(y_pred[i],y_true[i][0]))\n        count+=1","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"13869dbb97734424c47ac92486548c1ed8708928"},"cell_type":"code","source":"result = model.predict(test_df)\nresults = np.argmax(result,axis = 1)\nresults","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2a6b1f0935d5a2c6c5b409acf3ed64788634b30a"},"cell_type":"code","source":"Label = pd.Series(results,name = 'Label')\nImageId = pd.Series(range(1,28001),name = 'ImageId')\nsubmission = pd.concat([ImageId,Label],axis = 1)\nsubmission.to_csv('submission.csv',index = False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_json = model.to_json()\nwith open(\"model.json\", \"w\") as json_file:\n    json_file.write(model_json)\n# serialize weights to HDF5\nmodel.save_weights(\"model.h5\")\nprint(\"Saved model to disk\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}