{"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\nimport os\n\n# Python ≥3.5 is required\nimport sys\nassert sys.version_info >= (3, 5)\n\n# Scikit-Learn ≥0.20 is required\nimport sklearn\nassert sklearn.__version__ >= \"0.20\"\n\n# TensorFlow ≥2.0 is required\nimport tensorflow as tf\nfrom tensorflow import keras\nassert tf.__version__ >= \"2.0\"\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten,Conv2D, MaxPooling2D, BatchNormalization\n\n# to make this notebook's output stable across runs\nnp.random.seed(42)\ntf.random.set_seed(42)\n\n# To plot pretty figures\n%matplotlib inline\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nmpl.rc('axes', labelsize=14)\nmpl.rc('xtick', labelsize=12)\nmpl.rc('ytick', labelsize=12)\n\n# Where to save the figures\nPROJECT_ROOT_DIR = \".\"\nCHAPTER_ID = \"cnn\"\nIMAGES_PATH = os.path.join(PROJECT_ROOT_DIR, \"images\", CHAPTER_ID)\nos.makedirs(IMAGES_PATH, exist_ok=True)\n\ndef save_fig(fig_id, tight_layout=True, fig_extension=\"png\", resolution=300):\n    path = os.path.join(IMAGES_PATH, fig_id + \".\" + fig_extension)\n    print(\"Saving figure\", fig_id)\n    if tight_layout:\n        plt.tight_layout()\n    plt.savefig(path, format=fig_extension, dpi=resolution)\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 all files under the input directory\n\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#read train and test files in pandas DataFrame\ntrain_df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_df.head())\nprint(train_df.shape)\nprint(test_df.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train_full = train_df['label'].astype('int32')\nX_train_full = train_df.drop(labels = ['label'], axis=1).astype('float32')\nX_test = test_df.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# delete for extra space\ndel train_df\ndel test_df\n\nprint(Y_train_full.shape)\nprint(X_train_full.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# show the distribution of each class\nprint(Y_train_full.value_counts())\nsns.countplot(Y_train_full)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# normalization, reshaping, and splitting \nX_train_full = X_train_full / 255.0\nX_test = X_test / 255.0\n\nX_train_full = X_train_full.values.reshape(X_train_full.shape[0], 28, 28, 1)\nX_test = X_test.values.reshape(X_test.shape[0], 28, 28, 1)\n\nX_train, x_val, Y_train, y_val = train_test_split(X_train_full, Y_train_full,\n                                                  test_size=0.1, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(X_train.shape)\nprint(x_val.shape)\nprint(Y_train.shape)\nprint(y_val.shape)\nprint(X_test.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.imshow(X_train[0][:,:,0], cmap='gray')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# CNN model architecture (all these parameters might be tuned to achieve better results)\nfrom functools import partial\n\nDefaultConv2D = partial(Conv2D, kernel_size=3, activation='relu', padding='SAME')\n\nmodel = Sequential([\n    DefaultConv2D(filters=64, kernel_size=7, input_shape=[28,28,1]),\n    BatchNormalization(),\n    MaxPooling2D(pool_size=2),\n    DefaultConv2D(filters=128),\n    BatchNormalization(),\n    DefaultConv2D(filters=128),\n    BatchNormalization(),\n    MaxPooling2D(pool_size=2),\n    DefaultConv2D(filters=256),\n    BatchNormalization(),\n    DefaultConv2D(filters=256),\n    BatchNormalization(),\n    MaxPooling2D(pool_size=2),\n    Flatten(),\n    Dense(units=128, activation='relu'),\n    Dropout(0.5),\n    Dense(units=64, activation='relu'),\n    Dropout(0.5),\n    Dense(units=10, activation='softmax'),\n])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# show model architecture\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#optimizer = keras.optimizers.Adam(beta_1=0.9, beta_2=0.999, amsgrad=False)\n# sparse loss is used when there are multi-class \n# (note: use one-hot encoding for Y values if you didn't use sparse)\nmodel.compile(loss='sparse_categorical_crossentropy', optimizer='nadam',\n              metrics=['accuracy'])             ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"K = keras.callbacks\nreduce_lr = K.ReduceLROnPlateau(monitor='val_accuracy', patience=10,\n                                             verbose=1, factor=0.1, min_lr=0.00001)\n# another method is to use LearningRateScheduler, reduce the learning rate by 10% every epoch\n# annealer = LearningRateScheduler(lambda x: 1e-3 * 0.9 ** x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# With data augmentation to prevent overfitting (accuracy 0.99286)\n\ndata_augmentation = keras.preprocessing.image.ImageDataGenerator(\n        rotation_range=10,  # randomly rotate images in the range (degrees, 0 to 180)\n        zoom_range = 0.1, # Randomly zoom image \n        width_shift_range=0.1,  # randomly shift images horizontally (fraction of total width)\n        height_shift_range=0.1)  # randomly shift images vertically (fraction of total height)\n\ndata_augmentation.fit(X_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 40\nbatch_size = 64\nhistory = model.fit_generator(data_augmentation.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs=epochs, validation_data=(x_val,y_val),\n                              steps_per_epoch=X_train.shape[0] // batch_size,\n                              verbose=1, callbacks=[reduce_lr])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"final_loss, final_acc = model.evaluate(x_val, y_val, verbose=0)\nprint(\"Final loss: {0:.4f}, final accuracy: {1:.4f}\".format(final_loss, final_acc))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Plot the loss and accuracy curves for training and validation \nfig, ax = plt.subplots(2,1)\nax[0].plot(history.history['loss'], color='b', label=\"Training loss\")\nax[0].plot(history.history['val_loss'], color='r', label=\"validation loss\",axes =ax[0])\nlegend = ax[0].legend(loc='best', shadow=True)\n\nax[1].plot(history.history['accuracy'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\n\n# Predict the values from the validation dataset\nY_pred = model.predict(x_val)\n# Convert predictions classes to one hot vectors \nY_pred_classes = np.argmax(Y_pred,axis = 1) \n# compute the confusion matrix\nY_true = y_val\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nsns.heatmap(confusion_mtx, annot=True, fmt='d')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# predict results\nresults = model.predict(X_test)\n\n# select the index with the maximum probability\nresults = np.argmax(results,axis = 1)\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.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}