{"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":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":"2024-05-03T12:54:02.021724Z","iopub.execute_input":"2024-05-03T12:54:02.021995Z","iopub.status.idle":"2024-05-03T12:54:02.726536Z","shell.execute_reply.started":"2024-05-03T12:54:02.021971Z","shell.execute_reply":"2024-05-03T12:54:02.725591Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# import warnings\nimport warnings\n# filter warnings\nwarnings.filterwarnings('ignore')","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:02.727992Z","iopub.execute_input":"2024-05-03T12:54:02.728365Z","iopub.status.idle":"2024-05-03T12:54:03.680413Z","shell.execute_reply.started":"2024-05-03T12:54:02.728340Z","shell.execute_reply":"2024-05-03T12:54:03.679448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv(\"../input/digit-recognizer/train.csv\")\nprint(train_data.shape)\ntrain_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:03.681612Z","iopub.execute_input":"2024-05-03T12:54:03.681900Z","iopub.status.idle":"2024-05-03T12:54:07.534641Z","shell.execute_reply.started":"2024-05-03T12:54:03.681875Z","shell.execute_reply":"2024-05-03T12:54:07.533692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data= pd.read_csv(\"../input/digit-recognizer/test.csv\")\nprint(test_data.shape)\ntest_data.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:07.537583Z","iopub.execute_input":"2024-05-03T12:54:07.538184Z","iopub.status.idle":"2024-05-03T12:54:09.555214Z","shell.execute_reply.started":"2024-05-03T12:54:07.538156Z","shell.execute_reply":"2024-05-03T12:54:09.554359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Drop 'label' column from train dataset and put it to Y_train variable below\ntrain_images = train_data.drop(labels = [\"label\"],axis = 1) \n\n# put labels into labels variable\nlabels = train_data[\"label\"]","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:09.556258Z","iopub.execute_input":"2024-05-03T12:54:09.556536Z","iopub.status.idle":"2024-05-03T12:54:09.640065Z","shell.execute_reply.started":"2024-05-03T12:54:09.556514Z","shell.execute_reply":"2024-05-03T12:54:09.638991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# visualize number of digits classes\nlabels.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:09.641406Z","iopub.execute_input":"2024-05-03T12:54:09.641719Z","iopub.status.idle":"2024-05-03T12:54:09.656201Z","shell.execute_reply.started":"2024-05-03T12:54:09.641693Z","shell.execute_reply":"2024-05-03T12:54:09.655077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualization\n10 digits have been plotted starting from 1 to 10","metadata":{}},{"cell_type":"code","source":"# plot some samples\nfor i in range(10):\n    img = train_images.iloc[i].values\n    img = img.reshape((28,28))\n    plt.imshow(img,cmap='gray')\n    plt.title(labels.iloc[i])\n    plt.axis(\"off\")\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:09.657437Z","iopub.execute_input":"2024-05-03T12:54:09.657718Z","iopub.status.idle":"2024-05-03T12:54:10.686070Z","shell.execute_reply.started":"2024-05-03T12:54:09.657695Z","shell.execute_reply":"2024-05-03T12:54:10.685253Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Randomly 9 digits have been plotted ina grid show","metadata":{}},{"cell_type":"code","source":"random_indices = np.random.choice(len(train_images), size=18, replace=False)\n\nfig, axes = plt.subplots(3, 6, figsize=(9, 9))\naxes = axes.flatten()\n\nfor i, idx in enumerate(random_indices):\n    image = train_images.iloc[idx].values\n    image = image.reshape((28, 28))\n    ax = axes[i]\n    ax.imshow(image, cmap='gray')\n    ax.axis('off')\n    ax.set_title(f\"Label: {labels[idx]}\", fontsize=10, pad=5)\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:10.687476Z","iopub.execute_input":"2024-05-03T12:54:10.688060Z","iopub.status.idle":"2024-05-03T12:54:11.804453Z","shell.execute_reply.started":"2024-05-03T12:54:10.688011Z","shell.execute_reply":"2024-05-03T12:54:11.803543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Normalize the data","metadata":{}},{"cell_type":"code","source":"train_images = train_images / 255.0\ntest_data = test_data / 255.0\nprint(\"train_images shape: \",train_images.shape)\nprint(\"test shape: \",test_data.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:11.805798Z","iopub.execute_input":"2024-05-03T12:54:11.806473Z","iopub.status.idle":"2024-05-03T12:54:11.896535Z","shell.execute_reply.started":"2024-05-03T12:54:11.806438Z","shell.execute_reply":"2024-05-03T12:54:11.895550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reshape\ntrain_images = train_images.values.reshape(-1,28,28,1)\ntest_data = test_data.values.reshape(-1,28,28,1)\nprint(\"train shape: \",train_images.shape)\nprint(\"test shape: \",test_data.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:11.900822Z","iopub.execute_input":"2024-05-03T12:54:11.901110Z","iopub.status.idle":"2024-05-03T12:54:11.906661Z","shell.execute_reply.started":"2024-05-03T12:54:11.901085Z","shell.execute_reply":"2024-05-03T12:54:11.905723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Label Encoding \n\nfrom keras.utils import to_categorical # convert to one-hot-encoding\n\nlabels = to_categorical(labels, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:11.907907Z","iopub.execute_input":"2024-05-03T12:54:11.908489Z","iopub.status.idle":"2024-05-03T12:54:22.166536Z","shell.execute_reply.started":"2024-05-03T12:54:11.908455Z","shell.execute_reply":"2024-05-03T12:54:22.165493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Split the train and the validation set for the fitting\nfrom sklearn.model_selection import train_test_split\n\nX_train, X_val, Y_train, Y_val = train_test_split(train_images, labels, test_size = 0.1, random_state=2)\n\nprint(\"x_train shape\",X_train.shape)\nprint(\"x_test shape\",X_val.shape)\nprint(\"y_train shape\",Y_train.shape)\nprint(\"y_test shape\",Y_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:22.168031Z","iopub.execute_input":"2024-05-03T12:54:22.168752Z","iopub.status.idle":"2024-05-03T12:54:22.684190Z","shell.execute_reply.started":"2024-05-03T12:54:22.168715Z","shell.execute_reply":"2024-05-03T12:54:22.683243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# CNN model design","metadata":{}},{"cell_type":"code","source":"from 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,Adam\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau\n\nmodel = Sequential()\n#\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', \n                 activation ='relu', input_shape = (28,28,1)))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n#\nmodel.add(Conv2D(filters = 32, 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# fully connected\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-05-03T12:54:22.685502Z","iopub.execute_input":"2024-05-03T12:54:22.685785Z","iopub.status.idle":"2024-05-03T12:54:23.464598Z","shell.execute_reply.started":"2024-05-03T12:54:22.685760Z","shell.execute_reply":"2024-05-03T12:54:23.463656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define the optimizer\noptimizer = Adam(learning_rate=0.0005, beta_1=0.9, beta_2=0.999)\n\n# Compile the model\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:23.465708Z","iopub.execute_input":"2024-05-03T12:54:23.465960Z","iopub.status.idle":"2024-05-03T12:54:23.479199Z","shell.execute_reply.started":"2024-05-03T12:54:23.465938Z","shell.execute_reply":"2024-05-03T12:54:23.478494Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 100  # for better result increase the epochs\nbatch_size = 250","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:23.480201Z","iopub.execute_input":"2024-05-03T12:54:23.480460Z","iopub.status.idle":"2024-05-03T12:54:23.484605Z","shell.execute_reply.started":"2024-05-03T12:54:23.480438Z","shell.execute_reply":"2024-05-03T12:54:23.483583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data augmentation\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,  # dimesion reduction\n        rotation_range=5,  # randomly rotate images in the range 5 degrees\n        zoom_range = 0.1, # Randomly zoom image 10%\n        width_shift_range=0.1,  # randomly shift images horizontally 10%\n        height_shift_range=0.1,  # randomly shift images vertically 10%\n        horizontal_flip=False,  # randomly flip images\n        vertical_flip=False)  # randomly flip images\n\ndatagen.fit(X_train)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:23.485723Z","iopub.execute_input":"2024-05-03T12:54:23.485997Z","iopub.status.idle":"2024-05-03T12:54:23.579253Z","shell.execute_reply.started":"2024-05-03T12:54:23.485974Z","shell.execute_reply":"2024-05-03T12:54:23.578422Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training","metadata":{}},{"cell_type":"code","source":"# Fit the model\nhistory = model.fit(datagen.flow(X_train,Y_train, batch_size=batch_size),\n                    epochs = epochs, validation_data = (X_val,Y_val), \n                    steps_per_epoch=X_train.shape[0] // batch_size)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T12:54:23.580379Z","iopub.execute_input":"2024-05-03T12:54:23.580670Z","iopub.status.idle":"2024-05-03T13:03:30.416503Z","shell.execute_reply.started":"2024-05-03T12:54:23.580646Z","shell.execute_reply":"2024-05-03T13:03:30.415706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"accuracy = history.history['accuracy']\nvalidation_accuracy = history.history['val_accuracy']\nepochs = range(len(accuracy))\nfig = plt.figure(figsize=(14,7))\nplt.plot(epochs,accuracy,'r',label=\"Training Accuracy\")\nplt.plot(epochs,validation_accuracy,'b',label=\"Validation Accuracy\")\nplt.legend(loc='upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:30.419142Z","iopub.execute_input":"2024-05-03T13:03:30.419857Z","iopub.status.idle":"2024-05-03T13:03:30.713176Z","shell.execute_reply.started":"2024-05-03T13:03:30.419830Z","shell.execute_reply":"2024-05-03T13:03:30.712289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss = history.history['loss']\nvalidation_loss = history.history['val_loss']\nepochs = range(len(loss))\nfig = plt.figure(figsize=(14,7))\nplt.plot(epochs,loss,'r',label=\"Training loss\")\nplt.plot(epochs,validation_loss,'b',label=\"Validation loss\")\nplt.legend(loc='upper left')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:30.714487Z","iopub.execute_input":"2024-05-03T13:03:30.714845Z","iopub.status.idle":"2024-05-03T13:03:30.997373Z","shell.execute_reply.started":"2024-05-03T13:03:30.714811Z","shell.execute_reply":"2024-05-03T13:03:30.996500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# confusion matrix\nfrom sklearn.metrics import confusion_matrix\nimport seaborn as sns\n\n# 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) \n# compute the confusion matrix\nconfusion_mtx = confusion_matrix(Y_true, Y_pred_classes) \n# plot the confusion matrix\nf,ax = plt.subplots(figsize=(8, 8))\nsns.heatmap(confusion_mtx, annot=True, linewidths=0.01,cmap=\"Greens\",linecolor=\"gray\", fmt= '.1f',ax=ax)\nplt.xlabel(\"Predicted Label\")\nplt.ylabel(\"True Label\")\nplt.title(\"Confusion Matrix\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:30.998542Z","iopub.execute_input":"2024-05-03T13:03:30.998869Z","iopub.status.idle":"2024-05-03T13:03:32.383423Z","shell.execute_reply.started":"2024-05-03T13:03:30.998838Z","shell.execute_reply":"2024-05-03T13:03:32.382477Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def calculate_metrics(confusion_matrix, categories):\n    \"\"\"\n    Function to calculate important metrics for multi-classification problems.\n    \"\"\"\n    # Calculating 4 different metrics\n    precision = np.diag(confusion_matrix) / np.sum(confusion_matrix, axis=0)\n    recall = np.diag(confusion_matrix) / np.sum(confusion_matrix, axis=1)\n    f1_score = 2 * (precision * recall) / (precision + recall)\n    accuracy = np.sum(np.diag(confusion_matrix)) / np.sum(confusion_matrix)\n\n    # Printing the results based on each category\n    for i, category in enumerate(categories):\n        print(f\"Class: {category.title()}\")\n        print(f\"Precision: {precision[i]:.3f}\")\n        print(f\"Recall: {recall[i]:.3f}\")\n        print(f\"F1-Score: {f1_score[i]:.3f}\\n\")\n        \n    # Showing the total accuracy of the model\n    print(f\"\\nAccuracy: {accuracy:.3f}\")","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:32.384711Z","iopub.execute_input":"2024-05-03T13:03:32.385506Z","iopub.status.idle":"2024-05-03T13:03:32.392515Z","shell.execute_reply.started":"2024-05-03T13:03:32.385468Z","shell.execute_reply":"2024-05-03T13:03:32.391538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']\nconfusion_matrix = confusion_mtx\ncalculate_metrics(confusion_matrix, categories=labels)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:32.393720Z","iopub.execute_input":"2024-05-03T13:03:32.393996Z","iopub.status.idle":"2024-05-03T13:03:32.406081Z","shell.execute_reply.started":"2024-05-03T13:03:32.393971Z","shell.execute_reply":"2024-05-03T13:03:32.405266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(test_data)\ny_pred_classes = np.argmax(y_pred,axis = 1) \ny_pred_classes.shape","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:32.407021Z","iopub.execute_input":"2024-05-03T13:03:32.407342Z","iopub.status.idle":"2024-05-03T13:03:34.309989Z","shell.execute_reply.started":"2024-05-03T13:03:32.407317Z","shell.execute_reply":"2024-05-03T13:03:34.309087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df1= pd.DataFrame(y_pred_classes, columns=['Label'])\ndf2=pd.DataFrame(range(1,y_pred.shape[0]+1),columns=['ImageId'])\nresults = pd.concat([df2, df1],axis = 1)\nresults.to_csv(\"digit-recognizer.csv\", index = False)","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:03:34.311375Z","iopub.execute_input":"2024-05-03T13:03:34.311741Z","iopub.status.idle":"2024-05-03T13:03:34.354341Z","shell.execute_reply.started":"2024-05-03T13:03:34.311708Z","shell.execute_reply":"2024-05-03T13:03:34.353467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result_csv = pd.read_csv(\"/kaggle/working/digit-recognizer.csv\")\nprint(result_csv.shape)\nresult_csv.head()","metadata":{"execution":{"iopub.status.busy":"2024-05-03T13:05:35.909598Z","iopub.execute_input":"2024-05-03T13:05:35.910269Z","iopub.status.idle":"2024-05-03T13:05:35.928122Z","shell.execute_reply.started":"2024-05-03T13:05:35.910235Z","shell.execute_reply":"2024-05-03T13:05:35.927076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}