{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","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":30786,"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-10-21T19:39:21.545004Z","iopub.execute_input":"2024-10-21T19:39:21.54543Z","iopub.status.idle":"2024-10-21T19:39:21.934081Z","shell.execute_reply.started":"2024-10-21T19:39:21.545388Z","shell.execute_reply":"2024-10-21T19:39:21.933031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport keras\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:21.936113Z","iopub.execute_input":"2024-10-21T19:39:21.936657Z","iopub.status.idle":"2024-10-21T19:39:34.118725Z","shell.execute_reply.started":"2024-10-21T19:39:21.93661Z","shell.execute_reply":"2024-10-21T19:39:34.117664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nsample_submission = pd.read_csv(\"/kaggle/input/digit-recognizer/sample_submission.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:34.120153Z","iopub.execute_input":"2024-10-21T19:39:34.12088Z","iopub.status.idle":"2024-10-21T19:39:39.765207Z","shell.execute_reply.started":"2024-10-21T19:39:34.120821Z","shell.execute_reply":"2024-10-21T19:39:39.764343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:39.767733Z","iopub.execute_input":"2024-10-21T19:39:39.768068Z","iopub.status.idle":"2024-10-21T19:39:39.794391Z","shell.execute_reply.started":"2024-10-21T19:39:39.768032Z","shell.execute_reply":"2024-10-21T19:39:39.793465Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.datasets import mnist \nimport 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\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\n\n\nsns.set(style='white', context='notebook', palette='deep')","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:39.795597Z","iopub.execute_input":"2024-10-21T19:39:39.796331Z","iopub.status.idle":"2024-10-21T19:39:40.792301Z","shell.execute_reply.started":"2024-10-21T19:39:39.79626Z","shell.execute_reply":"2024-10-21T19:39:40.791313Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.subplot(422)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:40.793562Z","iopub.execute_input":"2024-10-21T19:39:40.794036Z","iopub.status.idle":"2024-10-21T19:39:41.117066Z","shell.execute_reply.started":"2024-10-21T19:39:40.794002Z","shell.execute_reply":"2024-10-21T19:39:41.116094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ytrain = train[\"label\"]\n\n# Drop 'label' column\nxtrain = train.drop(labels = [\"label\"],axis = 1)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.118209Z","iopub.execute_input":"2024-10-21T19:39:41.118561Z","iopub.status.idle":"2024-10-21T19:39:41.204228Z","shell.execute_reply.started":"2024-10-21T19:39:41.118525Z","shell.execute_reply":"2024-10-21T19:39:41.20324Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.205427Z","iopub.execute_input":"2024-10-21T19:39:41.205794Z","iopub.status.idle":"2024-10-21T19:39:41.225297Z","shell.execute_reply.started":"2024-10-21T19:39:41.205757Z","shell.execute_reply":"2024-10-21T19:39:41.224264Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ytrain.head()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.226474Z","iopub.execute_input":"2024-10-21T19:39:41.22681Z","iopub.status.idle":"2024-10-21T19:39:41.234985Z","shell.execute_reply.started":"2024-10-21T19:39:41.226777Z","shell.execute_reply":"2024-10-21T19:39:41.233968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"s = sns.countplot(ytrain)\nytrain.value_counts()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.238569Z","iopub.execute_input":"2024-10-21T19:39:41.23891Z","iopub.status.idle":"2024-10-21T19:39:41.491914Z","shell.execute_reply.started":"2024-10-21T19:39:41.238874Z","shell.execute_reply":"2024-10-21T19:39:41.491039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain.isnull().any().describe()","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.493315Z","iopub.execute_input":"2024-10-21T19:39:41.49371Z","iopub.status.idle":"2024-10-21T19:39:41.514587Z","shell.execute_reply.started":"2024-10-21T19:39:41.493665Z","shell.execute_reply":"2024-10-21T19:39:41.513493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain = xtrain / 255.0\ntest = test / 255.0","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.515777Z","iopub.execute_input":"2024-10-21T19:39:41.516131Z","iopub.status.idle":"2024-10-21T19:39:41.608842Z","shell.execute_reply.started":"2024-10-21T19:39:41.516081Z","shell.execute_reply":"2024-10-21T19:39:41.607986Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain = xtrain.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.6102Z","iopub.execute_input":"2024-10-21T19:39:41.610937Z","iopub.status.idle":"2024-10-21T19:39:41.616581Z","shell.execute_reply.started":"2024-10-21T19:39:41.610887Z","shell.execute_reply":"2024-10-21T19:39:41.615338Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ytrain = to_categorical(ytrain, num_classes = 10)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.617924Z","iopub.execute_input":"2024-10-21T19:39:41.618255Z","iopub.status.idle":"2024-10-21T19:39:41.626871Z","shell.execute_reply.started":"2024-10-21T19:39:41.618219Z","shell.execute_reply":"2024-10-21T19:39:41.625802Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"random_seed = 2","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.627934Z","iopub.execute_input":"2024-10-21T19:39:41.628809Z","iopub.status.idle":"2024-10-21T19:39:41.633902Z","shell.execute_reply.started":"2024-10-21T19:39:41.628772Z","shell.execute_reply":"2024-10-21T19:39:41.632984Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain, xval, ytrain, yval = train_test_split(xtrain, ytrain, test_size = 0.1, random_state=random_seed)\ng = plt.imshow(xtrain[0][:,:,0])","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:41.63564Z","iopub.execute_input":"2024-10-21T19:39:41.636239Z","iopub.status.idle":"2024-10-21T19:39:42.382161Z","shell.execute_reply.started":"2024-10-21T19:39:41.636173Z","shell.execute_reply":"2024-10-21T19:39:42.38129Z"},"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-10-21T19:39:42.383512Z","iopub.execute_input":"2024-10-21T19:39:42.384278Z","iopub.status.idle":"2024-10-21T19:39:43.294355Z","shell.execute_reply.started":"2024-10-21T19:39:42.384232Z","shell.execute_reply":"2024-10-21T19:39:43.293557Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer = RMSprop(rho=0.9, epsilon=1e-08, decay=0.0)\nmodel.compile(optimizer = optimizer , loss = \"categorical_crossentropy\", metrics=[\"accuracy\"])","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:43.295411Z","iopub.execute_input":"2024-10-21T19:39:43.295711Z","iopub.status.idle":"2024-10-21T19:39:43.311602Z","shell.execute_reply.started":"2024-10-21T19:39:43.295679Z","shell.execute_reply":"2024-10-21T19:39:43.310735Z"},"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)\n","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:43.31288Z","iopub.execute_input":"2024-10-21T19:39:43.313565Z","iopub.status.idle":"2024-10-21T19:39:43.318149Z","shell.execute_reply.started":"2024-10-21T19:39:43.313522Z","shell.execute_reply":"2024-10-21T19:39:43.317128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 30 # Turn epochs to 30 to get 0.9967 accuracy\nbatch_size = 86","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:43.319241Z","iopub.execute_input":"2024-10-21T19:39:43.319561Z","iopub.status.idle":"2024-10-21T19:39:43.326317Z","shell.execute_reply.started":"2024-10-21T19:39:43.319529Z","shell.execute_reply":"2024-10-21T19:39:43.325209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(xtrain, ytrain, batch_size = batch_size, epochs = epochs, \n                    validation_data = (xval, yval), verbose = 2)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:39:43.32751Z","iopub.execute_input":"2024-10-21T19:39:43.327839Z","iopub.status.idle":"2024-10-21T19:41:10.489205Z","shell.execute_reply.started":"2024-10-21T19:39:43.327795Z","shell.execute_reply":"2024-10-21T19:41:10.488242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"datagen = 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(xtrain)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:45:00.33188Z","iopub.execute_input":"2024-10-21T19:45:00.332965Z","iopub.status.idle":"2024-10-21T19:45:00.426179Z","shell.execute_reply.started":"2024-10-21T19:45:00.332919Z","shell.execute_reply":"2024-10-21T19:45:00.425155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(datagen.flow(xtrain, ytrain, batch_size=batch_size),\n                    epochs=epochs, \n                    validation_data=(xval, yval),\n                    verbose=2, \n                    steps_per_epoch=xtrain.shape[0] // batch_size,\n                    callbacks=[learning_rate_reduction])\n","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:50:09.157208Z","iopub.execute_input":"2024-10-21T19:50:09.158006Z","iopub.status.idle":"2024-10-21T19:53:54.268974Z","shell.execute_reply.started":"2024-10-21T19:50:09.157962Z","shell.execute_reply":"2024-10-21T19:53:54.268143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, 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['acc'], color='b', label=\"Training accuracy\")\nax[1].plot(history.history['val_acc'], color='r',label=\"Validation accuracy\")\nlegend = ax[1].legend(loc='best', shadow=True)","metadata":{"execution":{"iopub.status.busy":"2024-10-21T19:54:54.060575Z","iopub.execute_input":"2024-10-21T19:54:54.061476Z","iopub.status.idle":"2024-10-21T19:54:54.723529Z","shell.execute_reply.started":"2024-10-21T19:54:54.061434Z","shell.execute_reply":"2024-10-21T19:54:54.722208Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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(xval)\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(yval,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":{"execution":{"iopub.status.busy":"2024-10-21T19:56:14.294353Z","iopub.execute_input":"2024-10-21T19:56:14.295306Z","iopub.status.idle":"2024-10-21T19:56:16.051147Z","shell.execute_reply.started":"2024-10-21T19:56:14.295224Z","shell.execute_reply":"2024-10-21T19:56:16.050182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 = xval[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":{"execution":{"iopub.status.busy":"2024-10-21T19:57:02.169449Z","iopub.execute_input":"2024-10-21T19:57:02.170103Z","iopub.status.idle":"2024-10-21T19:57:03.439429Z","shell.execute_reply.started":"2024-10-21T19:57:02.170061Z","shell.execute_reply":"2024-10-21T19:57:03.438438Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results = 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-10-21T19:57:19.821445Z","iopub.execute_input":"2024-10-21T19:57:19.822016Z","iopub.status.idle":"2024-10-21T19:57:21.83543Z","shell.execute_reply.started":"2024-10-21T19:57:19.821952Z","shell.execute_reply":"2024-10-21T19:57:21.834558Z"},"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('digitrecogsubmission.csv')","metadata":{"execution":{"iopub.status.busy":"2024-10-21T20:00:00.953065Z","iopub.execute_input":"2024-10-21T20:00:00.953687Z","iopub.status.idle":"2024-10-21T20:00:01.004558Z","shell.execute_reply.started":"2024-10-21T20:00:00.953649Z","shell.execute_reply":"2024-10-21T20:00:01.003776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}