{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30673,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"!pip install tensorflow","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-03-27T23:50:34.925517Z","iopub.execute_input":"2024-03-27T23:50:34.926435Z","iopub.status.idle":"2024-03-27T23:50:50.548047Z","shell.execute_reply.started":"2024-03-27T23:50:34.926386Z","shell.execute_reply":"2024-03-27T23:50:50.547113Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install keras","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:50:50.550373Z","iopub.execute_input":"2024-03-27T23:50:50.550719Z","iopub.status.idle":"2024-03-27T23:51:00.697923Z","shell.execute_reply.started":"2024-03-27T23:50:50.550690Z","shell.execute_reply":"2024-03-27T23:51:00.696937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\n%matplotlib inline\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils import to_categorical # convert to one-hot-encoding\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D\nfrom keras.optimizers import RMSprop\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\n\nsns.set(style='white', context='notebook', palette='deep')","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:51:35.563418Z","iopub.execute_input":"2024-03-27T23:51:35.563744Z","iopub.status.idle":"2024-03-27T23:51:50.736348Z","shell.execute_reply.started":"2024-03-27T23:51:35.563719Z","shell.execute_reply":"2024-03-27T23:51:50.735630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the data\ntrain = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\nY_train = train[\"label\"]\n\n# Drop 'label' column\nX_train = train.drop(labels = [\"label\"],axis = 1) \n\n# free some space\ndel train \n\n# Normalize the data\nX_train = X_train / 255.0\ntest = test / 255.0\n\n#Reshape\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\n\n# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0])\nY_train = to_categorical(Y_train, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:53:50.859948Z","iopub.execute_input":"2024-03-27T23:53:50.860993Z","iopub.status.idle":"2024-03-27T23:53:55.255186Z","shell.execute_reply.started":"2024-03-27T23:53:50.860958Z","shell.execute_reply":"2024-03-27T23:53:55.254437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set the random seed\nrandom_seed = 2\n\n# Split the train and the validation set for the fitting\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)\n\n# Some examples\ng = plt.imshow(X_train[0][:,:,0])","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:54:41.426899Z","iopub.execute_input":"2024-03-27T23:54:41.427455Z","iopub.status.idle":"2024-03-27T23:54:41.731264Z","shell.execute_reply.started":"2024-03-27T23:54:41.427384Z","shell.execute_reply":"2024-03-27T23:54:41.730273Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set the CNN model \n# my CNN architechture is In -> [[Conv2D->relu]*2 -> MaxPool2D -> Dropout]*2 -> Flatten -> Dense -> Dropout -> Out\n\nmodel = Sequential()\n\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(Conv2D(filters = 32, kernel_size = (5,5),padding = 'Same', \n                 activation ='relu'))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n\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.25))\n\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:55:02.096528Z","iopub.execute_input":"2024-03-27T23:55:02.097207Z","iopub.status.idle":"2024-03-27T23:55:02.288513Z","shell.execute_reply.started":"2024-03-27T23:55:02.097174Z","shell.execute_reply":"2024-03-27T23:55:02.287087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the optimizer\noptimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08)\n# Compile the model\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:55:17.498851Z","iopub.execute_input":"2024-03-27T23:55:17.499230Z","iopub.status.idle":"2024-03-27T23:55:17.519748Z","shell.execute_reply.started":"2024-03-27T23:55:17.499198Z","shell.execute_reply":"2024-03-27T23:55:17.518846Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', \n                                            patience=3, \n                                            verbose=1, \n                                            factor=0.5, \n                                            min_lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:55:38.833808Z","iopub.execute_input":"2024-03-27T23:55:38.834925Z","iopub.status.idle":"2024-03-27T23:55:38.841281Z","shell.execute_reply.started":"2024-03-27T23:55:38.834868Z","shell.execute_reply":"2024-03-27T23:55:38.840426Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 30 # Turn epochs to 30 to get 0.9967 accuracy\nbatch_size = 86\n\n# With data augmentation to prevent overfitting (accuracy 0.99286)\n\ndatagen = 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":"2024-03-27T23:56:04.421735Z","iopub.execute_input":"2024-03-27T23:56:04.423109Z","iopub.status.idle":"2024-03-27T23:56:04.458089Z","shell.execute_reply.started":"2024-03-27T23:56:04.423046Z","shell.execute_reply":"2024-03-27T23:56:04.456991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fit the model\nhistory = model.fit_generator(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                              epochs = epochs, validation_data = (X_val,Y_val),\n                              verbose = 2, steps_per_epoch=X_train.shape[0] // batch_size\n                              , callbacks=[learning_rate_reduction])","metadata":{"execution":{"iopub.status.busy":"2024-03-27T23:56:21.051707Z","iopub.execute_input":"2024-03-27T23:56:21.052092Z","iopub.status.idle":"2024-03-28T00:33:25.104816Z","shell.execute_reply.started":"2024-03-27T23:56:21.052059Z","shell.execute_reply":"2024-03-28T00:33:25.104031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"execution":{"iopub.status.busy":"2024-03-28T00:35:32.906699Z","iopub.execute_input":"2024-03-28T00:35:32.907117Z","iopub.status.idle":"2024-03-28T00:35:33.860672Z","shell.execute_reply.started":"2024-03-28T00:35:32.907087Z","shell.execute_reply":"2024-03-28T00:35:33.859770Z"},"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":"2024-03-28T00:35:37.789019Z","iopub.execute_input":"2024-03-28T00:35:37.789427Z","iopub.status.idle":"2024-03-28T00:35:58.764017Z","shell.execute_reply.started":"2024-03-28T00:35:37.789377Z","shell.execute_reply":"2024-03-28T00:35:58.762940Z"},"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(\"mnist_image_result.csv\",index=False)","metadata":{"execution":{"iopub.status.busy":"2024-03-28T00:36:16.509737Z","iopub.execute_input":"2024-03-28T00:36:16.510295Z","iopub.status.idle":"2024-03-28T00:36:16.535594Z","shell.execute_reply.started":"2024-03-28T00:36:16.510268Z","shell.execute_reply":"2024-03-28T00:36:16.534463Z"},"trusted":true},"execution_count":null,"outputs":[]}]}