{"cells":[{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n\n%matplotlib inline\n\nnp.random.seed(7)\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout,Flatten, Conv2D, MaxPool2D,BatchNormalization \nfrom keras.optimizers import RMSprop, Adam\nfrom keras.preprocessing.image import ImageDataGenerator \nfrom keras.callbacks import ReduceLROnPlateau\n\nsns.set(style='white', context='notebook', palette='deep')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")\n\nY_train=train[\"label\"]\nX_train = train.drop(labels = [\"label\"],axis = 1) \n\ndel train\n# print(train)\ng = sns.countplot(Y_train)\nY_train.value_counts()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test.isnull().any().describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#Normalize the data\nX_train = X_train / 255.0\ntest = test / 255.0\nprint(X_train.shape)\nprint(type(test))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_train = X_train.to_numpy()\nX_train=X_train.reshape(-1,28,28,1)\ntest = test.to_numpy()\ntest=test.reshape(-1,28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"random_seed=3\n# Split the train and the validation set for the fitting\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"g = plt.imshow(X_train[0][:,:,0])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"datagen = ImageDataGenerator(zoom_range = 0.1, width_shift_range = 0.1, height_shift_range = 0.1, rotation_range = 10) ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=Sequential()\nmodel.add(Conv2D(filters=32,kernel_size=(3,3), padding='Same', activation='relu', input_shape=(28,28,1),name='first'))\nmodel.add(BatchNormalization())\n\nmodel.add(Conv2D(filters=64,kernel_size=(3,3), activation='relu', name='second'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPool2D(pool_size=(2,2)))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu',name='third'))\nmodel.add(BatchNormalization())\n\nmodel.add(MaxPool2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(128, activation = \"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.15))\n\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(10, activation = \"softmax\"))\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"opt=Adam(learning_rate=0.001)\nmodel.compile(optimizer = opt , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_accuracy', patience=3, verbose=1, factor=0.5, min_lr=0.00001)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history=model.fit(X_train,Y_train,batch_size=32,epochs=30,validation_data=(X_val, Y_val),verbose=1)\nhistory = model.fit_generator(datagen.flow(X_train, Y_train, batch_size = 32), epochs = 40, \n                              validation_data = (X_val, Y_val), callbacks = [learning_rate_reduction])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_loss, final_acc = model.evaluate(X_val, Y_val, verbose=1)\n\nprint(\"Final loss: {0:.4f}, final accuracy: {1:.4f}\".format(final_loss, final_acc))\n\n# list all data in history\nprint(history.history.keys())\n\n# summarize history for accuracy\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# summarize history for loss\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":"predictions = model.predict_classes(test, verbose=1)\ntest = test.reshape(-1, 28, 28, 1) / 255\ny_pred = model.predict(test, batch_size = 64)\n\ny_pred = np.argmax(y_pred,axis = 1)\ny_pred = pd.Series(y_pred,name=\"Label\")\ny_pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\nsubmissions.to_csv(\"aksr.csv\", index=False, header=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model.save_weights(filepath='final_weight.h5')\nmodel.save(\"model.h5\")","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":4}