{"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":"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\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-09-30T14:32:10.065893Z","iopub.execute_input":"2022-09-30T14:32:10.066296Z","iopub.status.idle":"2022-09-30T14:32:10.075809Z","shell.execute_reply.started":"2022-09-30T14:32:10.066263Z","shell.execute_reply":"2022-09-30T14:32:10.074627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\nfrom keras.utils.np_utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import MaxPool2D, Conv2D, Dense, Flatten, Dropout\nfrom tensorflow.keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:10.078169Z","iopub.execute_input":"2022-09-30T14:32:10.078874Z","iopub.status.idle":"2022-09-30T14:32:10.085910Z","shell.execute_reply.started":"2022-09-30T14:32:10.078838Z","shell.execute_reply":"2022-09-30T14:32:10.084815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:10.087699Z","iopub.execute_input":"2022-09-30T14:32:10.087989Z","iopub.status.idle":"2022-09-30T14:32:13.996708Z","shell.execute_reply.started":"2022-09-30T14:32:10.087961Z","shell.execute_reply":"2022-09-30T14:32:13.995721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = train.drop('label', axis=1)\ny_train = train['label']","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:13.999369Z","iopub.execute_input":"2022-09-30T14:32:14.000258Z","iopub.status.idle":"2022-09-30T14:32:14.081326Z","shell.execute_reply.started":"2022-09-30T14:32:14.000217Z","shell.execute_reply":"2022-09-30T14:32:14.080131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train.value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.083128Z","iopub.execute_input":"2022-09-30T14:32:14.083531Z","iopub.status.idle":"2022-09-30T14:32:14.094587Z","shell.execute_reply.started":"2022-09-30T14:32:14.083496Z","shell.execute_reply":"2022-09-30T14:32:14.093587Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.isnull().sum().any()","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.096034Z","iopub.execute_input":"2022-09-30T14:32:14.096440Z","iopub.status.idle":"2022-09-30T14:32:14.142725Z","shell.execute_reply.started":"2022-09-30T14:32:14.096401Z","shell.execute_reply":"2022-09-30T14:32:14.141692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train.isnull().sum().any()","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.144395Z","iopub.execute_input":"2022-09-30T14:32:14.144771Z","iopub.status.idle":"2022-09-30T14:32:14.151872Z","shell.execute_reply.started":"2022-09-30T14:32:14.144737Z","shell.execute_reply":"2022-09-30T14:32:14.150987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train/255.0\ntest = test/255.0","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.153447Z","iopub.execute_input":"2022-09-30T14:32:14.154106Z","iopub.status.idle":"2022-09-30T14:32:14.325257Z","shell.execute_reply.started":"2022-09-30T14:32:14.154067Z","shell.execute_reply":"2022-09-30T14:32:14.324171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train = x_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.327243Z","iopub.execute_input":"2022-09-30T14:32:14.327596Z","iopub.status.idle":"2022-09-30T14:32:14.332732Z","shell.execute_reply.started":"2022-09-30T14:32:14.327560Z","shell.execute_reply":"2022-09-30T14:32:14.331751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train = to_categorical(y_train, num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.337440Z","iopub.execute_input":"2022-09-30T14:32:14.337813Z","iopub.status.idle":"2022-09-30T14:32:14.346397Z","shell.execute_reply.started":"2022-09-30T14:32:14.337778Z","shell.execute_reply":"2022-09-30T14:32:14.345476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train,x_val,y_train,y_val = train_test_split(x_train,y_train, test_size=0.1, random_state=3)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.347732Z","iopub.execute_input":"2022-09-30T14:32:14.348106Z","iopub.status.idle":"2022-09-30T14:32:14.720503Z","shell.execute_reply.started":"2022-09-30T14:32:14.348072Z","shell.execute_reply":"2022-09-30T14:32:14.719506Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(x_train[0])","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.721732Z","iopub.execute_input":"2022-09-30T14:32:14.722103Z","iopub.status.idle":"2022-09-30T14:32:14.917815Z","shell.execute_reply.started":"2022-09-30T14:32:14.722069Z","shell.execute_reply":"2022-09-30T14:32:14.916855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), padding='same', activation='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters=32, kernel_size=(5,5), padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.22))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), padding='same', activation='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters=64, kernel_size=(3,3), padding='same', activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.22))\n\nmodel.add(Flatten())\nmodel.add(Dense(200, activation = \"relu\"))\nmodel.add(Dropout(0.45))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.919091Z","iopub.execute_input":"2022-09-30T14:32:14.919524Z","iopub.status.idle":"2022-09-30T14:32:14.988897Z","shell.execute_reply.started":"2022-09-30T14:32:14.919488Z","shell.execute_reply":"2022-09-30T14:32:14.988061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = RMSprop(learning_rate=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.990102Z","iopub.execute_input":"2022-09-30T14:32:14.990540Z","iopub.status.idle":"2022-09-30T14:32:14.995750Z","shell.execute_reply.started":"2022-09-30T14:32:14.990501Z","shell.execute_reply":"2022-09-30T14:32:14.994656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=optimizer, loss='categorical_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:14.997115Z","iopub.execute_input":"2022-09-30T14:32:14.997749Z","iopub.status.idle":"2022-09-30T14:32:15.009847Z","shell.execute_reply.started":"2022-09-30T14:32:14.997712Z","shell.execute_reply":"2022-09-30T14:32:15.008981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc',patience=3,verbose=1,factor=0.5,min_lr=0.00001)                                          ","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:15.011582Z","iopub.execute_input":"2022-09-30T14:32:15.011880Z","iopub.status.idle":"2022-09-30T14:32:15.019021Z","shell.execute_reply.started":"2022-09-30T14:32:15.011856Z","shell.execute_reply":"2022-09-30T14:32:15.018118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = ImageDataGenerator(\n        featurewise_center=False,  # set input mean to 0 over the dataset\n        samplewise_center=False,  # set each sample mean to 0\n        featurewise_std_normalization=False,  # divide inputs by std of the dataset\n        samplewise_std_normalization=False,  # divide each input by its std\n        zca_whitening=False,  # apply ZCA whitening\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        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\n\ndatagen.fit(x_train)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:15.020447Z","iopub.execute_input":"2022-09-30T14:32:15.020787Z","iopub.status.idle":"2022-09-30T14:32:15.119417Z","shell.execute_reply.started":"2022-09-30T14:32:15.020753Z","shell.execute_reply":"2022-09-30T14:32:15.118408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(datagen.flow(x_train,y_train, batch_size=86),\n                              epochs = 1, validation_data = (x_val,y_val),\n                              verbose = 2, steps_per_epoch=x_train.shape[0], callbacks=[learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:15.121044Z","iopub.execute_input":"2022-09-30T14:32:15.121414Z","iopub.status.idle":"2022-09-30T14:32:25.861910Z","shell.execute_reply.started":"2022-09-30T14:32:15.121378Z","shell.execute_reply":"2022-09-30T14:32:25.860982Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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# Convert validation observations to one hot vectors\ny_true = np.argmax(y_val,axis = 1)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:25.863688Z","iopub.execute_input":"2022-09-30T14:32:25.864066Z","iopub.status.idle":"2022-09-30T14:32:26.179900Z","shell.execute_reply.started":"2022-09-30T14:32:25.864029Z","shell.execute_reply":"2022-09-30T14:32:26.178736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_classes","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:26.181600Z","iopub.execute_input":"2022-09-30T14:32:26.181983Z","iopub.status.idle":"2022-09-30T14:32:26.189373Z","shell.execute_reply.started":"2022-09-30T14:32:26.181945Z","shell.execute_reply":"2022-09-30T14:32:26.188404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# evaluate test accuracy\nscore = model.evaluate(x_val, y_val, verbose=0)\naccuracy = 100*score[1]\n\n# print test accuracy\nprint('Test accuracy: %.4f%%' % accuracy)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:26.190984Z","iopub.execute_input":"2022-09-30T14:32:26.191564Z","iopub.status.idle":"2022-09-30T14:32:26.563821Z","shell.execute_reply.started":"2022-09-30T14:32:26.191527Z","shell.execute_reply":"2022-09-30T14:32:26.562890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = ['0','1','2','3','4','5','6','7','8','9']","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:26.565161Z","iopub.execute_input":"2022-09-30T14:32:26.565534Z","iopub.status.idle":"2022-09-30T14:32:26.573219Z","shell.execute_reply.started":"2022-09-30T14:32:26.565499Z","shell.execute_reply":"2022-09-30T14:32:26.572059Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot a random sample of test images, their predicted labels, and ground truth\nfig = plt.figure(figsize=(20, 8))\nfor i, idx in enumerate(np.random.choice(x_val.shape[0], size=40, replace=False)):\n    ax = fig.add_subplot(5, 8, i + 1, xticks=[], yticks=[])\n    ax.imshow(np.squeeze(x_val[idx]))\n    pred_idx = np.argmax(y_pred[idx])\n    true_idx = np.argmax(y_val[idx])\n    ax.set_title(\"{} ({})\".format(labels[pred_idx], labels[true_idx]),\n                 color=(\"blue\" if pred_idx == true_idx else \"red\"))","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:32:26.575030Z","iopub.execute_input":"2022-09-30T14:32:26.575486Z","iopub.status.idle":"2022-09-30T14:32:28.250450Z","shell.execute_reply.started":"2022-09-30T14:32:26.575450Z","shell.execute_reply":"2022-09-30T14:32:28.249492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predict results\nresults = model.predict(test)\n\n# select the indix with the maximum probability\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:38:53.570458Z","iopub.execute_input":"2022-09-30T14:38:53.570839Z","iopub.status.idle":"2022-09-30T14:38:56.435828Z","shell.execute_reply.started":"2022-09-30T14:38:53.570808Z","shell.execute_reply":"2022-09-30T14:38:56.434404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"submission.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2022-09-30T14:39:05.516963Z","iopub.execute_input":"2022-09-30T14:39:05.517319Z","iopub.status.idle":"2022-09-30T14:39:05.550388Z","shell.execute_reply.started":"2022-09-30T14:39:05.517289Z","shell.execute_reply":"2022-09-30T14:39:05.549489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}