{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.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":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Overview\n##### This notebook implements a Convolutional Neural Network (CNN) using Keras to recognize handwritten digits from the MNIST dataset, achieving top-tier accuracy (99.7%).","metadata":{}},{"cell_type":"markdown","source":"# Key Components","metadata":{}},{"cell_type":"markdown","source":"## 1. Import my libraries","metadata":{}},{"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\nnp.random.seed(2)\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 tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:00:54.358703Z","iopub.execute_input":"2025-10-04T23:00:54.359500Z","iopub.status.idle":"2025-10-04T23:00:54.366997Z","shell.execute_reply.started":"2025-10-04T23:00:54.359466Z","shell.execute_reply":"2025-10-04T23:00:54.365874Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sns.set(style='white', context='notebook', palette='deep')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:00:59.282344Z","iopub.execute_input":"2025-10-04T23:00:59.282791Z","iopub.status.idle":"2025-10-04T23:00:59.288783Z","shell.execute_reply.started":"2025-10-04T23:00:59.282757Z","shell.execute_reply":"2025-10-04T23:00:59.287693Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2.   Data Preparation","metadata":{}},{"cell_type":"markdown","source":"### 2.1 get Data","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:01:04.774198Z","iopub.execute_input":"2025-10-04T23:01:04.774561Z","iopub.status.idle":"2025-10-04T23:01:09.025037Z","shell.execute_reply.started":"2025-10-04T23:01:04.774534Z","shell.execute_reply":"2025-10-04T23:01:09.023759Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2.2 Data visualization","metadata":{}},{"cell_type":"code","source":"# Separate features and labels\nY_train = train[\"label\"]\nX_train = train.drop(labels=[\"label\"], axis=1)\n\ndel train\n\n# If Y_train is one-hot encoded:\nif len(Y_train.shape) > 1 and Y_train.shape[1] > 1:\n    Y_train_labels = np.argmax(Y_train, axis=1)\nelse:\n    Y_train_labels = Y_train\n\n# Create countplot\nplt.figure(figsize=(12, 6))\nax = sns.countplot(x=Y_train_labels)\nplt.title('MNIST Digit Distribution', fontsize=16)\nplt.xlabel('Digit', fontsize=12)\nplt.ylabel('Count', fontsize=12)\n\n# Add count labels on bars\nfor p in ax.patches:\n    ax.annotate(f'{p.get_height():.0f}', \n                (p.get_x() + p.get_width() / 2., p.get_height()), \n                ha='center', va='center', \n                xytext=(0, 5), \n                textcoords='offset points')\nplt.show()\n\n# Value counts\nvalue_counts = pd.Series(Y_train_labels).value_counts().sort_index()\nprint(\"\\nDigit Distribution:\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:11:25.728970Z","iopub.execute_input":"2025-10-04T23:11:25.729307Z","iopub.status.idle":"2025-10-04T23:11:26.555674Z","shell.execute_reply.started":"2025-10-04T23:11:25.729285Z","shell.execute_reply":"2025-10-04T23:11:26.554298Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2.3 Normalization","metadata":{}},{"cell_type":"code","source":"# Normmalization the data\nX_train = X_train / 255.0\ntest = test / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:14:35.598611Z","iopub.execute_input":"2025-10-04T23:14:35.599011Z","iopub.status.idle":"2025-10-04T23:14:35.952402Z","shell.execute_reply.started":"2025-10-04T23:14:35.598982Z","shell.execute_reply":"2025-10-04T23:14:35.951245Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2.4 Reshape","metadata":{}},{"cell_type":"code","source":"# Reshape image in 3 dimensions (height = 28px, width = 28px , canal = 1)\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:18:47.825125Z","iopub.execute_input":"2025-10-04T23:18:47.825621Z","iopub.status.idle":"2025-10-04T23:18:47.833339Z","shell.execute_reply.started":"2025-10-04T23:18:47.825597Z","shell.execute_reply":"2025-10-04T23:18:47.831972Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2.5 Label encoding","metadata":{}},{"cell_type":"code","source":"# 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:20:29.154983Z","iopub.execute_input":"2025-10-04T23:20:29.155395Z","iopub.status.idle":"2025-10-04T23:20:29.163622Z","shell.execute_reply.started":"2025-10-04T23:20:29.155360Z","shell.execute_reply":"2025-10-04T23:20:29.161826Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 2.6 Split training and valdiation set ","metadata":{}},{"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, \n                                                  Y_train, \n                                                  test_size = 0.1, \n                                                  random_state=random_seed)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:22:01.013563Z","iopub.execute_input":"2025-10-04T23:22:01.014823Z","iopub.status.idle":"2025-10-04T23:22:01.600554Z","shell.execute_reply.started":"2025-10-04T23:22:01.014786Z","shell.execute_reply":"2025-10-04T23:22:01.599391Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Some examples\ng = plt.imshow(X_train[0][:,:,0])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:22:41.944796Z","iopub.execute_input":"2025-10-04T23:22:41.945130Z","iopub.status.idle":"2025-10-04T23:22:42.295355Z","shell.execute_reply.started":"2025-10-04T23:22:41.945103Z","shell.execute_reply":"2025-10-04T23:22:42.293974Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3. CNN\n## 3.1 Define the model","metadata":{}},{"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', 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.25))\n\nmodel.add(Conv2D(filters = 64, kernel_size = (3,3),padding = 'Same', activation ='relu'))\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.25))\n\nmodel.add(Flatten())\nmodel.add(Dense(256, activation = \"relu\"))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, activation = \"softmax\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:26:57.960965Z","iopub.execute_input":"2025-10-04T23:26:57.961417Z","iopub.status.idle":"2025-10-04T23:26:58.138963Z","shell.execute_reply.started":"2025-10-04T23:26:57.961379Z","shell.execute_reply":"2025-10-04T23:26:58.137402Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3.2 Set the optimizer and annealer","metadata":{}},{"cell_type":"code","source":"# Define the optimizer\noptimizer = RMSprop(learning_rate=0.001, rho=0.9, epsilon=1e-08, decay=0.0)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:29:05.108886Z","iopub.execute_input":"2025-10-04T23:29:05.109310Z","iopub.status.idle":"2025-10-04T23:29:05.128493Z","shell.execute_reply.started":"2025-10-04T23:29:05.109285Z","shell.execute_reply":"2025-10-04T23:29:05.126854Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:29:42.753780Z","iopub.execute_input":"2025-10-04T23:29:42.755336Z","iopub.status.idle":"2025-10-04T23:29:42.766851Z","shell.execute_reply.started":"2025-10-04T23:29:42.755281Z","shell.execute_reply":"2025-10-04T23:29:42.765449Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:30:12.584305Z","iopub.execute_input":"2025-10-04T23:30:12.584645Z","iopub.status.idle":"2025-10-04T23:30:12.591497Z","shell.execute_reply.started":"2025-10-04T23:30:12.584622Z","shell.execute_reply":"2025-10-04T23:30:12.589826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"epochs = 1 # Turn epochs to 30 to get 0.9967 accuracy\nbatch_size = 86","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:30:28.844166Z","iopub.execute_input":"2025-10-04T23:30:28.844549Z","iopub.status.idle":"2025-10-04T23:30:28.850539Z","shell.execute_reply.started":"2025-10-04T23:30:28.844525Z","shell.execute_reply":"2025-10-04T23:30:28.849030Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 3.3 Data augmentation ","metadata":{}},{"cell_type":"code","source":"# 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:32:08.638866Z","iopub.execute_input":"2025-10-04T23:32:08.639241Z","iopub.status.idle":"2025-10-04T23:32:08.771435Z","shell.execute_reply.started":"2025-10-04T23:32:08.639215Z","shell.execute_reply":"2025-10-04T23:32:08.769782Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Fit the model\n\n# First, let's make sure we train the model properly\nprint(\"Starting model training...\")\n\n# Train the model (simplified version without data augmentation for testing)\nhistory = model.fit(\n    X_train, Y_train,\n    batch_size=32,  # Smaller batch for testing\n    epochs=epochs,       # Fewer epochs for testing\n    validation_data=(X_val, Y_val),\n    verbose=1,\n    shuffle=True\n)\n\nprint(\"Training completed!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:47:51.089614Z","iopub.execute_input":"2025-10-04T23:47:51.090025Z","iopub.status.idle":"2025-10-04T23:50:16.153250Z","shell.execute_reply.started":"2025-10-04T23:47:51.089999Z","shell.execute_reply":"2025-10-04T23:50:16.151742Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4. Evaluate the model\n## 4.1 Training and validation curves","metadata":{}},{"cell_type":"code","source":"# Now plot the results\nfig, axes = plt.subplots(1, 2, figsize=(15, 5))\n\n# Plot Loss\naxes[0].plot(history.history['loss'], label='Training Loss', color='blue', linewidth=2)\naxes[0].plot(history.history['val_loss'], label='Validation Loss', color='red', linewidth=2)\naxes[0].set_title('Training and Validation Loss', fontsize=14, fontweight='bold')\naxes[0].set_xlabel('Epochs')\naxes[0].set_ylabel('Loss')\naxes[0].legend()\naxes[0].grid(True, alpha=0.3)\n\n# Plot Accuracy - handle different metric names\naccuracy_key = 'accuracy' if 'accuracy' in history.history else 'acc'\nval_accuracy_key = 'val_accuracy' if 'val_accuracy' in history.history else 'val_acc'\n\naxes[1].plot(history.history[accuracy_key], label='Training Accuracy', color='blue', linewidth=2)\naxes[1].plot(history.history[val_accuracy_key], label='Validation Accuracy', color='red', linewidth=2)\naxes[1].set_title('Training and Validation Accuracy', fontsize=14, fontweight='bold')\naxes[1].set_xlabel('Epochs')\naxes[1].set_ylabel('Accuracy')\naxes[1].legend()\naxes[1].grid(True, alpha=0.3)\n\nplt.tight_layout()\nplt.show()\n\n# Print final metrics\nprint(f\"\\nFinal Training Accuracy: {history.history[accuracy_key][-1]:.4f}\")\nprint(f\"Final Validation Accuracy: {history.history[val_accuracy_key][-1]:.4f}\")\nprint(f\"Final Training Loss: {history.history['loss'][-1]:.4f}\")\nprint(f\"Final Validation Loss: {history.history['val_loss'][-1]:.4f}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:50:33.223530Z","iopub.execute_input":"2025-10-04T23:50:33.223890Z","iopub.status.idle":"2025-10-04T23:50:33.847275Z","shell.execute_reply.started":"2025-10-04T23:50:33.223869Z","shell.execute_reply":"2025-10-04T23:50:33.846115Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## 4.2 Confusion matrix","metadata":{}},{"cell_type":"code","source":"# Look at confusion matrix \n\ndef plot_confusion_matrix(cm, classes,\n                          normalize=False,\n                          title='Confusion matrix',\n                          cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\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\nplot_confusion_matrix(confusion_mtx, classes = range(10)) ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:51:40.483498Z","iopub.execute_input":"2025-10-04T23:51:40.483886Z","iopub.status.idle":"2025-10-04T23:51:45.983489Z","shell.execute_reply.started":"2025-10-04T23:51:40.483862Z","shell.execute_reply":"2025-10-04T23:51:45.982389Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Display some error results \n\n# Errors are difference between predicted labels and true labels\nerrors = (Y_pred_classes - Y_true != 0)\n\nY_pred_classes_errors = Y_pred_classes[errors]\nY_pred_errors = Y_pred[errors]\nY_true_errors = Y_true[errors]\nX_val_errors = X_val[errors]\n\ndef display_errors(errors_index,img_errors,pred_errors, obs_errors):\n    \"\"\" This function shows 6 images with their predicted and real labels\"\"\"\n    n = 0\n    nrows = 2\n    ncols = 3\n    fig, ax = plt.subplots(nrows,ncols,sharex=True,sharey=True)\n    for row in range(nrows):\n        for col in range(ncols):\n            error = errors_index[n]\n            ax[row,col].imshow((img_errors[error]).reshape((28,28)))\n            ax[row,col].set_title(\"Predicted label :{}\\nTrue label :{}\".format(pred_errors[error],obs_errors[error]))\n            n += 1\n\n# Probabilities of the wrong predicted numbers\nY_pred_errors_prob = np.max(Y_pred_errors,axis = 1)\n\n# Predicted probabilities of the true values in the error set\ntrue_prob_errors = np.diagonal(np.take(Y_pred_errors, Y_true_errors, axis=1))\n\n# Difference between the probability of the predicted label and the true label\ndelta_pred_true_errors = Y_pred_errors_prob - true_prob_errors\n\n# Sorted list of the delta prob errors\nsorted_dela_errors = np.argsort(delta_pred_true_errors)\n\n# Top 6 errors \nmost_important_errors = sorted_dela_errors[-6:]\n\n# Show the top 6 errors\ndisplay_errors(most_important_errors, X_val_errors, Y_pred_classes_errors, Y_true_errors)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:52:20.839414Z","iopub.execute_input":"2025-10-04T23:52:20.839847Z","iopub.status.idle":"2025-10-04T23:52:22.000880Z","shell.execute_reply.started":"2025-10-04T23:52:20.839822Z","shell.execute_reply":"2025-10-04T23:52:21.999644Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:53:35.318917Z","iopub.execute_input":"2025-10-04T23:53:35.319290Z","iopub.status.idle":"2025-10-04T23:54:03.749067Z","shell.execute_reply.started":"2025-10-04T23:53:35.319267Z","shell.execute_reply":"2025-10-04T23:54:03.747826Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-10-04T23:54:20.624800Z","iopub.execute_input":"2025-10-04T23:54:20.625537Z","iopub.status.idle":"2025-10-04T23:54:20.665519Z","shell.execute_reply.started":"2025-10-04T23:54:20.625504Z","shell.execute_reply":"2025-10-04T23:54:20.664267Z"}},"outputs":[],"execution_count":null}]}