{"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":"!pip install livelossplot","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:26:22.796089Z","iopub.execute_input":"2022-06-16T16:26:22.796531Z","iopub.status.idle":"2022-06-16T16:26:34.699316Z","shell.execute_reply.started":"2022-06-16T16:26:22.796495Z","shell.execute_reply":"2022-06-16T16:26:34.698373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport matplotlib.pyplot as plt\n%matplotlib inline\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 Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau, CSVLogger\nfrom tensorflow.keras.optimizers import RMSprop\nfrom livelossplot import PlotLossesKeras\nfrom livelossplot.keras import PlotLossesCallback","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:26:36.057202Z","iopub.execute_input":"2022-06-16T16:26:36.057885Z","iopub.status.idle":"2022-06-16T16:26:36.071188Z","shell.execute_reply.started":"2022-06-16T16:26:36.057844Z","shell.execute_reply":"2022-06-16T16:26:36.070220Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAINING_LOGS_FILE = \"training_logs.csv\"\nMODEL_SUMMARY_FILE = \"model_summary.txt\"\nMODEL_FILE = \"model.h5\"\nTRAINING_PLOT_FILE = \"training.png\"\nVALIDATION_PLOT_FILE = \"validation.png\"\nKAGGLE_SUBMISSION_FILE = \"submission.csv\"","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:26:38.821334Z","iopub.execute_input":"2022-06-16T16:26:38.821904Z","iopub.status.idle":"2022-06-16T16:26:38.827102Z","shell.execute_reply.started":"2022-06-16T16:26:38.821868Z","shell.execute_reply":"2022-06-16T16:26:38.826285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"../input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"../input/digit-recognizer/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:26:40.714220Z","iopub.execute_input":"2022-06-16T16:26:40.714668Z","iopub.status.idle":"2022-06-16T16:26:46.179688Z","shell.execute_reply.started":"2022-06-16T16:26:40.714635Z","shell.execute_reply":"2022-06-16T16:26:46.178399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = train[\"label\"]\nx = train.drop(labels = [\"label\"], axis = 1) ","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:26:54.238007Z","iopub.execute_input":"2022-06-16T16:26:54.238626Z","iopub.status.idle":"2022-06-16T16:26:54.341867Z","shell.execute_reply.started":"2022-06-16T16:26:54.238584Z","shell.execute_reply":"2022-06-16T16:26:54.340892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"VERBOSITY = 1\nEPOCHS = 2\nBATCH_SIZE = 512\nCLASSES = 10\nCHANNELS = 1\nIMAGE_SIZE = 28\nIMAGE_WIDTH, IMAGE_HEIGHT = IMAGE_SIZE, IMAGE_SIZE\nVALIDATION_RATIO = 0.1","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:26:56.341696Z","iopub.execute_input":"2022-06-16T16:26:56.342496Z","iopub.status.idle":"2022-06-16T16:26:56.348063Z","shell.execute_reply.started":"2022-06-16T16:26:56.342459Z","shell.execute_reply":"2022-06-16T16:26:56.347026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = x.values.reshape(-1, IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)\ntest = test.values.reshape(-1, IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:05.760980Z","iopub.execute_input":"2022-06-16T16:27:05.761451Z","iopub.status.idle":"2022-06-16T16:27:05.766879Z","shell.execute_reply.started":"2022-06-16T16:27:05.761417Z","shell.execute_reply":"2022-06-16T16:27:05.766092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = to_categorical(y, num_classes=CLASSES)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:07.603171Z","iopub.execute_input":"2022-06-16T16:27:07.603870Z","iopub.status.idle":"2022-06-16T16:27:07.610290Z","shell.execute_reply.started":"2022-06-16T16:27:07.603833Z","shell.execute_reply":"2022-06-16T16:27:07.609155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_training, x_validation, y_training, y_validation = train_test_split(x,y,test_size=VALIDATION_RATIO,shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:09.544414Z","iopub.execute_input":"2022-06-16T16:27:09.545002Z","iopub.status.idle":"2022-06-16T16:27:10.075058Z","shell.execute_reply.started":"2022-06-16T16:27:09.544968Z","shell.execute_reply":"2022-06-16T16:27:10.073888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_generator = ImageDataGenerator(rescale=1./255,rotation_range=10,zoom_range=0.15, width_shift_range=0.1,height_shift_range=0.1)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:14.194980Z","iopub.execute_input":"2022-06-16T16:27:14.195464Z","iopub.status.idle":"2022-06-16T16:27:14.202073Z","shell.execute_reply.started":"2022-06-16T16:27:14.195414Z","shell.execute_reply":"2022-06-16T16:27:14.201123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_generator.fit(x_training)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:15.995600Z","iopub.execute_input":"2022-06-16T16:27:15.996035Z","iopub.status.idle":"2022-06-16T16:27:16.125500Z","shell.execute_reply.started":"2022-06-16T16:27:15.996001Z","shell.execute_reply":"2022-06-16T16:27:16.124345Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(filters=32,\n                 kernel_size=(5,5),\n                 padding='Same', \n                 activation='relu',\n                 input_shape=(IMAGE_WIDTH, IMAGE_HEIGHT, CHANNELS)))\nmodel.add(Conv2D(filters=32,\n                 kernel_size=(5,5),\n                 padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(Conv2D(filters=64, kernel_size=(3,3),padding='Same', \n                 activation='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))\nmodel.add(Dropout(0.5))\n\nmodel.add(Flatten())\nmodel.add(Dense(8192, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(2048, activation='relu'))\nmodel.add(Dropout(0.5))\n\nmodel.add(Dense(CLASSES, activation=\"softmax\"))\n","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:19.851592Z","iopub.execute_input":"2022-06-16T16:27:19.851985Z","iopub.status.idle":"2022-06-16T16:27:20.177653Z","shell.execute_reply.started":"2022-06-16T16:27:19.851952Z","shell.execute_reply":"2022-06-16T16:27:20.176691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(optimizer=RMSprop(lr=0.0001,rho=0.9,epsilon=1e-08,decay=0.00001),loss=\"categorical_crossentropy\",metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:24.582226Z","iopub.execute_input":"2022-06-16T16:27:24.582678Z","iopub.status.idle":"2022-06-16T16:27:24.593139Z","shell.execute_reply.started":"2022-06-16T16:27:24.582645Z","shell.execute_reply":"2022-06-16T16:27:24.592482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(MODEL_SUMMARY_FILE,\"w\") as fh:\n    model.summary(print_fn=lambda line: fh.write(line + \"\\n\"))","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:28.952283Z","iopub.execute_input":"2022-06-16T16:27:28.952722Z","iopub.status.idle":"2022-06-16T16:27:28.962207Z","shell.execute_reply.started":"2022-06-16T16:27:28.952688Z","shell.execute_reply":"2022-06-16T16:27:28.961421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit_generator(data_generator.flow(x_training,y_training,batch_size=BATCH_SIZE),epochs=EPOCHS,validation_data=(x_validation, y_validation),verbose=VERBOSITY,steps_per_epoch=x_training.shape[0] // BATCH_SIZE,callbacks=[PlotLossesKeras(),CSVLogger(TRAINING_LOGS_FILE,append=False,separator=\";\")])","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:27:37.141276Z","iopub.execute_input":"2022-06-16T16:27:37.142788Z","iopub.status.idle":"2022-06-16T16:33:09.098237Z","shell.execute_reply.started":"2022-06-16T16:27:37.142735Z","shell.execute_reply":"2022-06-16T16:33:09.096991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights(MODEL_FILE)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:33:53.015432Z","iopub.execute_input":"2022-06-16T16:33:53.015939Z","iopub.status.idle":"2022-06-16T16:33:53.450843Z","shell.execute_reply.started":"2022-06-16T16:33:53.015905Z","shell.execute_reply":"2022-06-16T16:33:53.449551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(test, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:33:56.242704Z","iopub.execute_input":"2022-06-16T16:33:56.243106Z","iopub.status.idle":"2022-06-16T16:34:56.685853Z","shell.execute_reply.started":"2022-06-16T16:33:56.243073Z","shell.execute_reply":"2022-06-16T16:34:56.684810Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = predictions.flatten()\npd.DataFrame({\"ImageId\":list(range(1,len(predictions)+1)),\n              \"Label\":predictions}).to_csv(KAGGLE_SUBMISSION_FILE,\n                                           index=False,\n                                           header=True)","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:35:22.579758Z","iopub.execute_input":"2022-06-16T16:35:22.580186Z","iopub.status.idle":"2022-06-16T16:35:23.285811Z","shell.execute_reply.started":"2022-06-16T16:35:22.580153Z","shell.execute_reply":"2022-06-16T16:35:23.284502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_pred = pd.DataFrame(model.predict(x_validation, batch_size=200))\ntest_pred = pd.DataFrame(test_pred.idxmax(axis = 1))\ntest_pred.index.name = 'ImageId'\ntest_pred = test_pred.rename(columns = {0: 'Label'}).reset_index()\ntest_pred['ImageId'] = test_pred['ImageId'] + 1\n\ntest_pred.head()","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:35:25.317657Z","iopub.execute_input":"2022-06-16T16:35:25.318273Z","iopub.status.idle":"2022-06-16T16:35:32.470921Z","shell.execute_reply.started":"2022-06-16T16:35:25.318225Z","shell.execute_reply":"2022-06-16T16:35:32.469846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(x_validation[0])","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:35:35.144719Z","iopub.execute_input":"2022-06-16T16:35:35.145147Z","iopub.status.idle":"2022-06-16T16:35:35.301176Z","shell.execute_reply.started":"2022-06-16T16:35:35.145113Z","shell.execute_reply":"2022-06-16T16:35:35.300072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.imshow(x_validation[1])","metadata":{"execution":{"iopub.status.busy":"2022-06-16T16:35:38.316126Z","iopub.execute_input":"2022-06-16T16:35:38.316585Z","iopub.status.idle":"2022-06-16T16:35:38.495444Z","shell.execute_reply.started":"2022-06-16T16:35:38.316549Z","shell.execute_reply":"2022-06-16T16:35:38.494077Z"},"trusted":true},"execution_count":null,"outputs":[]}]}