{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"![](http://i.morioh.com/ceb686e62b.png)","metadata":{}},{"cell_type":"code","source":"import cv2\nimport numpy as np\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, Dense, Dropout, Flatten, MaxPool2D\nfrom keras.layers import BatchNormalization\nfrom keras.utils import to_categorical\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import LearningRateScheduler","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = np.loadtxt('/kaggle/input/digit-recognizer/train.csv', delimiter=',', skiprows=1)\ntest = np.loadtxt('/kaggle/input/digit-recognizer/test.csv', delimiter=',', skiprows=1)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:01:57.030455Z","iopub.execute_input":"2023-02-21T19:01:57.031153Z","iopub.status.idle":"2023-02-21T19:02:30.658011Z","shell.execute_reply.started":"2023-02-21T19:01:57.031116Z","shell.execute_reply":"2023-02-21T19:02:30.656918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# save label\ntrain_label = train[:, 0]\n\n# bring the dimension to a form convenient for processing\ntrain = np.resize(train[:, 1:], (train.shape[0], 28, 28, 1))\ntest = np.resize(test, (test.shape[0], 28, 28, 1))","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:30.670666Z","iopub.execute_input":"2023-02-21T19:02:30.671118Z","iopub.status.idle":"2023-02-21T19:02:30.987997Z","shell.execute_reply.started":"2023-02-21T19:02:30.671083Z","shell.execute_reply":"2023-02-21T19:02:30.986843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# One-hot encoding of label value\ny = to_categorical(train_label,10)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:30.990546Z","iopub.execute_input":"2023-02-21T19:02:30.991201Z","iopub.status.idle":"2023-02-21T19:02:30.996709Z","shell.execute_reply.started":"2023-02-21T19:02:30.991164Z","shell.execute_reply":"2023-02-21T19:02:30.995638Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('train:', train.shape)\nprint('y:', y.shape)\nprint('test:', test.shape)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:30.999178Z","iopub.execute_input":"2023-02-21T19:02:30.999612Z","iopub.status.idle":"2023-02-21T19:02:31.012713Z","shell.execute_reply.started":"2023-02-21T19:02:30.999581Z","shell.execute_reply":"2023-02-21T19:02:31.011447Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Visualize the raw data","metadata":{}},{"cell_type":"code","source":"%matplotlib inline\nimport matplotlib.pyplot as plt\n\nfig = plt.figure(figsize=(20, 10))\nfor i, img in enumerate(train[0:5, :], 1):\n    subplot = fig.add_subplot(1, 5, i)\n    plt.imshow(img[:,:,0], cmap='gray');\n    subplot.set_title('%s' % train_label[i - 1]);","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:31.014308Z","iopub.execute_input":"2023-02-21T19:02:31.014859Z","iopub.status.idle":"2023-02-21T19:02:31.745075Z","shell.execute_reply.started":"2023-02-21T19:02:31.014816Z","shell.execute_reply":"2023-02-21T19:02:31.743833Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Split the sample into training and validation","metadata":{}},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\ny_train, y_val, x_train, x_val = train_test_split(\n    y, train, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:31.746365Z","iopub.execute_input":"2023-02-21T19:02:31.746692Z","iopub.status.idle":"2023-02-21T19:02:31.840994Z","shell.execute_reply.started":"2023-02-21T19:02:31.746662Z","shell.execute_reply":"2023-02-21T19:02:31.839977Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Building a convolutional network for training","metadata":{}},{"cell_type":"code","source":"model = Sequential([\n    Conv2D(filters=32,\n           kernel_size=(3, 3),\n           padding='same',\n           activation='relu',\n           input_shape=x_train.shape[1:]), \n    Conv2D(filters=32,\n           kernel_size=(3, 3),\n           padding='same',\n           activation='relu',\n           input_shape=x_train.shape[1:]),                      \n    MaxPool2D(pool_size=(2, 2), padding='valid'),                     \n    BatchNormalization(),\n\n    Conv2D(filters=64, \n           kernel_size=(3, 3),\n           padding='same',\n           activation='relu'),\n    Conv2D(filters=64, \n           kernel_size=(3, 3),\n           padding='same',\n           activation='relu'),                                             \n    MaxPool2D(pool_size=(2, 2), padding='valid'),\n    BatchNormalization(),\n    \n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.4),\n    Dense(10, activation='softmax')])\n\nmodel.compile(optimizer='Adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:31.842596Z","iopub.execute_input":"2023-02-21T19:02:31.843047Z","iopub.status.idle":"2023-02-21T19:02:31.962749Z","shell.execute_reply.started":"2023-02-21T19:02:31.843003Z","shell.execute_reply":"2023-02-21T19:02:31.961673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:31.964788Z","iopub.execute_input":"2023-02-21T19:02:31.965549Z","iopub.status.idle":"2023-02-21T19:02:32.007251Z","shell.execute_reply.started":"2023-02-21T19:02:31.965496Z","shell.execute_reply":"2023-02-21T19:02:32.006085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ImageDataGenerator for image augmentation\nimg_dg = ImageDataGenerator(\n    rotation_range=10,\n    zoom_range=0.1,\n    width_shift_range=0.1,\n    height_shift_range=0.1)\n\n\nlr = LearningRateScheduler(lambda epoch: 1e-3 * (0.95**epoch))","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:02:32.009268Z","iopub.execute_input":"2023-02-21T19:02:32.009639Z","iopub.status.idle":"2023-02-21T19:02:32.015482Z","shell.execute_reply.started":"2023-02-21T19:02:32.009608Z","shell.execute_reply":"2023-02-21T19:02:32.014279Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Launching training","metadata":{}},{"cell_type":"code","source":"# fitting\nhistory = model.fit(img_dg.flow(x_train, y_train, batch_size=64), \n                    epochs=20,  \n                    validation_data = (x_val, y_val),\n                    steps_per_epoch=x_train.shape[0]//64,\n                    callbacks=[lr])","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label = 'val_accuracy')\nplt.xlabel('Epoch')\nplt.ylabel('Accuracy')\nplt.ylim([0, 1])\nplt.legend(loc='lower right')","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:29:48.851207Z","iopub.execute_input":"2023-02-21T19:29:48.851701Z","iopub.status.idle":"2023-02-21T19:29:49.056090Z","shell.execute_reply.started":"2023-02-21T19:29:48.851659Z","shell.execute_reply":"2023-02-21T19:29:49.055221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Predicting the class of an object","metadata":{}},{"cell_type":"code","source":"y_pred = model.predict(x_val)\ny_pred_labels = np.argmax(y_pred, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:30:13.069752Z","iopub.execute_input":"2023-02-21T19:30:13.070512Z","iopub.status.idle":"2023-02-21T19:30:18.081593Z","shell.execute_reply.started":"2023-02-21T19:30:13.070470Z","shell.execute_reply":"2023-02-21T19:30:18.080310Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Evaluate the quality of the solution on the validation set","metadata":{}},{"cell_type":"code","source":"y_val = np.argmax(y_val, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:30:24.395437Z","iopub.execute_input":"2023-02-21T19:30:24.396968Z","iopub.status.idle":"2023-02-21T19:30:24.403700Z","shell.execute_reply.started":"2023-02-21T19:30:24.396899Z","shell.execute_reply":"2023-02-21T19:30:24.402426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score\nprint('Accuracy: %s' % accuracy_score(y_val, y_pred_labels))","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:30:27.620458Z","iopub.execute_input":"2023-02-21T19:30:27.620906Z","iopub.status.idle":"2023-02-21T19:30:27.628282Z","shell.execute_reply.started":"2023-02-21T19:30:27.620869Z","shell.execute_reply":"2023-02-21T19:30:27.626934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report\nprint(classification_report(y_val, y_pred_labels))","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:30:35.008205Z","iopub.execute_input":"2023-02-21T19:30:35.008937Z","iopub.status.idle":"2023-02-21T19:30:35.037919Z","shell.execute_reply.started":"2023-02-21T19:30:35.008896Z","shell.execute_reply":"2023-02-21T19:30:35.036465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\ncm = confusion_matrix(y_val, y_pred_labels)\n\nplt.figure(figsize=(10, 8))\nplt.imshow(cm, cmap=plt.cm.Blues)\nplt.xlabel(\"Predicted labels\")\nplt.ylabel(\"True labels\")\nplt.xticks([], [])\nplt.yticks([], [])\nplt.title('Confusion matrix ')\nplt.colorbar()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:43:52.683581Z","iopub.execute_input":"2023-02-21T19:43:52.684632Z","iopub.status.idle":"2023-02-21T19:43:52.885438Z","shell.execute_reply.started":"2023-02-21T19:43:52.684588Z","shell.execute_reply":"2023-02-21T19:43:52.883875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> ## Visualize predictions for the test set","metadata":{}},{"cell_type":"code","source":"y_pred_test = model.predict(test)\ny_pred_test_labels = np.argmax(y_pred_test, axis=1)","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:30:43.460578Z","iopub.execute_input":"2023-02-21T19:30:43.461071Z","iopub.status.idle":"2023-02-21T19:30:59.723329Z","shell.execute_reply.started":"2023-02-21T19:30:43.461032Z","shell.execute_reply":"2023-02-21T19:30:59.722212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig = plt.figure(figsize=(20, 10))\nindices = np.random.choice(range(len(test)), 5)\nimg_prediction = zip(test[indices], y_pred_test_labels[indices])\nfor i, (img, pred) in enumerate(img_prediction, 1):\n    subplot = fig.add_subplot(1, 5, i)\n    plt.imshow(img[...,0], cmap='gray');\n    subplot.set_title('%d' % pred);","metadata":{"execution":{"iopub.status.busy":"2023-02-21T19:30:59.725977Z","iopub.execute_input":"2023-02-21T19:30:59.726480Z","iopub.status.idle":"2023-02-21T19:31:00.727295Z","shell.execute_reply.started":"2023-02-21T19:30:59.726433Z","shell.execute_reply":"2023-02-21T19:31:00.726119Z"},"trusted":true},"execution_count":null,"outputs":[]}]}