{"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 tensorflow as tf\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.layers.experimental import preprocessing\nfrom sklearn.preprocessing import OneHotEncoder\n#from sklearn.model_selection import train_test_split\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-06-19T15:29:35.922656Z","iopub.execute_input":"2022-06-19T15:29:35.923187Z","iopub.status.idle":"2022-06-19T15:29:41.765608Z","shell.execute_reply.started":"2022-06-19T15:29:35.923101Z","shell.execute_reply":"2022-06-19T15:29:41.764076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntr_y = train_data.pop(\"label\")\n#tr_y = y.values.reshape(-1, 1)\ntr_X = train_data/255.0\nX = tr_X.values.reshape(42000, 28, 28, 1)\ntrain_X = X[0:37000, :, :, :]\nval_X = X[37000:42000, :, :, :]\nprint(\"Training data shape: \", train_X.shape)\nprint(\"Validating data shape: \", val_X.shape)\ntest_data = pd.read_csv(\"../input/digit-recognizer/test.csv\")\ninput_shape = [train_X.shape[1]]","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:29:41.767393Z","iopub.execute_input":"2022-06-19T15:29:41.768045Z","iopub.status.idle":"2022-06-19T15:29:47.200031Z","shell.execute_reply.started":"2022-06-19T15:29:41.768007Z","shell.execute_reply":"2022-06-19T15:29:47.199193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#OH_Enc = OneHotEncoder()\n#trn_y = OH_Enc.fit_transform(tr_y)\ntrain_y = tr_y[0:37000]\nval_y_ = tr_y[37000:42000].reset_index()\nval_y_.pop(\"index\")\nval_y = val_y_.squeeze()\nprint(\"Training label shape: \", train_y.shape)\nprint(\"Validating label shape: \", val_y.shape)","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:29:47.201457Z","iopub.execute_input":"2022-06-19T15:29:47.201827Z","iopub.status.idle":"2022-06-19T15:29:47.212163Z","shell.execute_reply.started":"2022-06-19T15:29:47.201791Z","shell.execute_reply":"2022-06-19T15:29:47.211427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data1_ = val_X[3633, :, :, :]\nprint(val_y[3633])\nplt.imshow(data1_, cmap=\"Greys_r\")","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:29:47.213980Z","iopub.execute_input":"2022-06-19T15:29:47.215122Z","iopub.status.idle":"2022-06-19T15:29:47.401420Z","shell.execute_reply.started":"2022-06-19T15:29:47.215080Z","shell.execute_reply":"2022-06-19T15:29:47.400678Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = keras.Sequential([\n    \n    preprocessing.RandomRotation(factor=0.05, fill_mode='constant'),     # 18 degrees\n    preprocessing.RandomZoom(height_factor=(-0.2,0.2), width_factor=(-0.2,0.2), fill_mode='constant'),  # 20%\n    \n    layers.Conv2D(filters=16, kernel_size=(5,5), activation=\"relu\", padding=\"same\"),\n    layers.MaxPool2D(pool_size=(2,2), padding=(\"same\")),\n    \n    layers.Conv2D(filters=32, kernel_size=(5,5), activation=\"relu\", padding=\"same\"),\n    layers.MaxPool2D(pool_size=(2,2), padding=(\"same\")),\n    \n    layers.Conv2D(filters=32, kernel_size=(5,5), activation=\"relu\", padding=\"same\"),\n    layers.MaxPool2D(pool_size=(2,2), padding=(\"same\")),\n    \n    layers.Flatten(),\n    \n    layers.Dense(units=512, activation=\"relu\"),\n    layers.BatchNormalization(),\n    layers.Dense(units=1024, activation=\"relu\"),\n    layers.BatchNormalization(),\n    layers.Dropout(0.5),\n    layers.Dense(units=512, activation=\"relu\"),\n    layers.BatchNormalization(),\n    layers.Dense(units=10, activation=\"softmax\"),\n])\nmodel.build([None, 28, 28, 1]) # `input_shape` is the shape of the input data\n                         # e.g. input_shape = (None, 32, 32, 3)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:29:47.402674Z","iopub.execute_input":"2022-06-19T15:29:47.402992Z","iopub.status.idle":"2022-06-19T15:29:50.222345Z","shell.execute_reply.started":"2022-06-19T15:29:47.402959Z","shell.execute_reply":"2022-06-19T15:29:50.221499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lr_schedule = keras.optimizers.schedules.ExponentialDecay(\n    initial_learning_rate=0.01,\n    decay_steps=1000,\n    decay_rate=0.9\n)\nmodel.compile(    \n    optimizer=tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n    loss=tf.keras.losses.SparseCategoricalCrossentropy(),\n    metrics=tf.keras.metrics.SparseCategoricalAccuracy()\n)","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:30:52.746514Z","iopub.execute_input":"2022-06-19T15:30:52.747287Z","iopub.status.idle":"2022-06-19T15:30:52.766633Z","shell.execute_reply.started":"2022-06-19T15:30:52.747248Z","shell.execute_reply":"2022-06-19T15:30:52.765920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"early_stopping = keras.callbacks.EarlyStopping(\n    patience=30,\n    min_delta=0.001,\n    restore_best_weights=True,\n)\n\nhistory = model.fit(\n    train_X, train_y,\n    validation_data=(val_X, val_y),\n    shuffle = True,\n    batch_size=512,\n    callbacks=[early_stopping],\n    epochs=100,\n    verbose=True\n)","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:34:06.467914Z","iopub.execute_input":"2022-06-19T15:34:06.468270Z","iopub.status.idle":"2022-06-19T15:34:11.600572Z","shell.execute_reply.started":"2022-06-19T15:34:06.468242Z","shell.execute_reply":"2022-06-19T15:34:11.599395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot(title=\"Cross-entropy\")\nhistory_df.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot(title=\"Accuracy\")","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:32:30.109524Z","iopub.execute_input":"2022-06-19T15:32:30.110048Z","iopub.status.idle":"2022-06-19T15:32:30.487316Z","shell.execute_reply.started":"2022-06-19T15:32:30.109999Z","shell.execute_reply":"2022-06-19T15:32:30.486585Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test = pd.read_csv(\"../input/digit-recognizer/test.csv\")/255\ntest_index = test.index\ntest_data = test.values.reshape(-1, 28, 28, 1)\n\ntest_preds = np.zeros((1, 1))\ntest_preds = test_preds + model.predict(test_data)\ntest_preds = np.argmax(test_preds, axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:32:38.893508Z","iopub.execute_input":"2022-06-19T15:32:38.894277Z","iopub.status.idle":"2022-06-19T15:32:41.872581Z","shell.execute_reply.started":"2022-06-19T15:32:38.894237Z","shell.execute_reply":"2022-06-19T15:32:41.871734Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plot some model predictions\nplt.figure(figsize=(15,20))\nplt.suptitle('Model predictions', fontsize=20, y=1.05)\n\n# Subplot\nfor i in range(100):\n    img = test_data[i];\n    ax=plt.subplot(10, 10, i+1)\n    ax.grid(False)\n    ax.get_xaxis().set_visible(False)\n    ax.get_yaxis().set_visible(False)\n    ax.title.set_text(f'Pred:{test_preds[i]}')\n    plt.imshow(img, cmap='gray')\n    \nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:32:44.762051Z","iopub.execute_input":"2022-06-19T15:32:44.762398Z","iopub.status.idle":"2022-06-19T15:32:48.915656Z","shell.execute_reply.started":"2022-06-19T15:32:44.762368Z","shell.execute_reply":"2022-06-19T15:32:48.914873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Save predictions to file\noutput = pd.DataFrame({'ImageId': test_index+1,\n                       'Label': test_preds})\n\n# Check format\noutput.head()","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:29:50.240851Z","iopub.status.idle":"2022-06-19T15:29:50.241290Z","shell.execute_reply.started":"2022-06-19T15:29:50.241072Z","shell.execute_reply":"2022-06-19T15:29:50.241094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"output.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-06-19T15:29:50.243231Z","iopub.status.idle":"2022-06-19T15:29:50.244145Z","shell.execute_reply.started":"2022-06-19T15:29:50.243895Z","shell.execute_reply":"2022-06-19T15:29:50.243920Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}