{"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,"isSourceIdPinned":false,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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","trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:36.597463Z","iopub.execute_input":"2025-09-01T08:27:36.597799Z","iopub.status.idle":"2025-09-01T08:27:36.626775Z","shell.execute_reply.started":"2025-09-01T08:27:36.597775Z","shell.execute_reply":"2025-09-01T08:27:36.625952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\nprint(train.shape)\ntrain.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:36.655714Z","iopub.execute_input":"2025-09-01T08:27:36.656062Z","iopub.status.idle":"2025-09-01T08:27:38.945471Z","shell.execute_reply.started":"2025-09-01T08:27:36.656025Z","shell.execute_reply":"2025-09-01T08:27:38.944295Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nprint(test.shape)\ntest.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:38.946873Z","iopub.execute_input":"2025-09-01T08:27:38.947594Z","iopub.status.idle":"2025-09-01T08:27:40.363658Z","shell.execute_reply.started":"2025-09-01T08:27:38.947560Z","shell.execute_reply":"2025-09-01T08:27:40.362881Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Y_train = train[\"label\"]\nX_train = train.drop(labels=[\"label\"], axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:40.364420Z","iopub.execute_input":"2025-09-01T08:27:40.364682Z","iopub.status.idle":"2025-09-01T08:27:40.496997Z","shell.execute_reply.started":"2025-09-01T08:27:40.364653Z","shell.execute_reply":"2025-09-01T08:27:40.495967Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n#visualize number of digits in classes\nplt.figure(figsize=(15,7))\ng = sns.countplot(Y_train, palette=\"icefire\")\nplt.title(\"Number of digit classes\")\nY_train.value_counts()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:40.498703Z","iopub.execute_input":"2025-09-01T08:27:40.498959Z","iopub.status.idle":"2025-09-01T08:27:40.690760Z","shell.execute_reply.started":"2025-09-01T08:27:40.498938Z","shell.execute_reply":"2025-09-01T08:27:40.689731Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot some samples\nimg = X_train.iloc[0].values.reshape(28,28)\nplt.imshow(img,cmap='gray')\nplt.title(train.iloc[0,0])\nplt.axis(\"off\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:40.691815Z","iopub.execute_input":"2025-09-01T08:27:40.692168Z","iopub.status.idle":"2025-09-01T08:27:40.779889Z","shell.execute_reply.started":"2025-09-01T08:27:40.692139Z","shell.execute_reply":"2025-09-01T08:27:40.779046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot some samples\nimg = X_train.iloc[3].values.reshape(28,28)\nplt.imshow(img,cmap='gray')\nplt.title(train.iloc[0,0])\nplt.axis(\"off\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:40.780849Z","iopub.execute_input":"2025-09-01T08:27:40.781164Z","iopub.status.idle":"2025-09-01T08:27:40.869552Z","shell.execute_reply.started":"2025-09-01T08:27:40.781140Z","shell.execute_reply":"2025-09-01T08:27:40.868596Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# plot some samples\nimg = X_train.iloc[4].values.reshape(28,28)\nplt.imshow(img,cmap='gray')\nplt.title(train.iloc[0,0])\nplt.axis(\"off\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:40.870516Z","iopub.execute_input":"2025-09-01T08:27:40.870788Z","iopub.status.idle":"2025-09-01T08:27:40.960747Z","shell.execute_reply.started":"2025-09-01T08:27:40.870762Z","shell.execute_reply":"2025-09-01T08:27:40.959787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#normalizing the data\nX_train = X_train / 255\ntest = test / 255\nprint(\"X train shape:\", X_train.shape)\nprint(\"Y train shape:\", test.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:40.961894Z","iopub.execute_input":"2025-09-01T08:27:40.962162Z","iopub.status.idle":"2025-09-01T08:27:41.082144Z","shell.execute_reply.started":"2025-09-01T08:27:40.962141Z","shell.execute_reply":"2025-09-01T08:27:41.081204Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#reshape\nX_train.values.reshape(-1,28,28,1)\ntest.values.reshape(-1,28,28,1)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.082974Z","iopub.execute_input":"2025-09-01T08:27:41.083661Z","iopub.status.idle":"2025-09-01T08:27:41.091883Z","shell.execute_reply.started":"2025-09-01T08:27:41.083629Z","shell.execute_reply":"2025-09-01T08:27:41.091049Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#label encoding\nfrom keras.utils import to_categorical\nY_train = to_categorical(Y_train, num_classes=10)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.094432Z","iopub.execute_input":"2025-09-01T08:27:41.094698Z","iopub.status.idle":"2025-09-01T08:27:41.108509Z","shell.execute_reply.started":"2025-09-01T08:27:41.094677Z","shell.execute_reply":"2025-09-01T08:27:41.107529Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#train test splittingf\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size=0.1, random_state=2)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.109478Z","iopub.execute_input":"2025-09-01T08:27:41.109713Z","iopub.status.idle":"2025-09-01T08:27:41.355766Z","shell.execute_reply.started":"2025-09-01T08:27:41.109694Z","shell.execute_reply":"2025-09-01T08:27:41.354947Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\nimport itertools\n\nfrom keras.utils import to_categorical\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()\nmodel.add(Conv2D(filters=8, kernel_size=(5,5), padding='Same', activation = 'relu', input_shape = (28,28,1)))\nmodel.add(MaxPool2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\n#\nmodel.add(Conv2D(filters=16, kernel_size=(3,3), padding='Same', activation='relu', input_shape=(28,28,1)))\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\"))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.356626Z","iopub.execute_input":"2025-09-01T08:27:41.357553Z","iopub.status.idle":"2025-09-01T08:27:41.444122Z","shell.execute_reply.started":"2025-09-01T08:27:41.357520Z","shell.execute_reply":"2025-09-01T08:27:41.443185Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# define optimizer (ADAM)\n#adjusting learning rate\noptimizer = Adam(learning_rate=0.001, beta_1=0.9, beta_2=0.999)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.445157Z","iopub.execute_input":"2025-09-01T08:27:41.445747Z","iopub.status.idle":"2025-09-01T08:27:41.452904Z","shell.execute_reply.started":"2025-09-01T08:27:41.445715Z","shell.execute_reply":"2025-09-01T08:27:41.451951Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#compile mode\n#categorical cross entropy\n\nmodel.compile(optimizer = optimizer, loss=\"categorical_crossentropy\", metrics = [\"accuracy\"])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.453827Z","iopub.execute_input":"2025-09-01T08:27:41.454362Z","iopub.status.idle":"2025-09-01T08:27:41.470048Z","shell.execute_reply.started":"2025-09-01T08:27:41.454330Z","shell.execute_reply":"2025-09-01T08:27:41.469267Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#initializing epoch and bach size\n\nepochs = 10\nbatch_size = 250\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:27:41.471357Z","iopub.execute_input":"2025-09-01T08:27:41.471672Z","iopub.status.idle":"2025-09-01T08:27:41.485580Z","shell.execute_reply.started":"2025-09-01T08:27:41.471644Z","shell.execute_reply":"2025-09-01T08:27:41.484565Z"}},"outputs":[],"execution_count":null},{"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\nX_train = X_train.values.reshape(-1, 28, 28, 1).astype('float32')\nX_val   = X_val.values.reshape(-1, 28, 28, 1).astype('float32')\n\ndatagen.fit(X_train)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:29:35.353965Z","iopub.execute_input":"2025-09-01T08:29:35.354840Z","iopub.status.idle":"2025-09-01T08:29:35.461436Z","shell.execute_reply.started":"2025-09-01T08:29:35.354811Z","shell.execute_reply":"2025-09-01T08:29:35.460524Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# fitting the model\n\nepochs = 10\nhistory = model.fit(datagen.flow(X_train, Y_train, batch_size = batch_size), epochs = epochs, validation_data = (X_val, Y_val), steps_per_epoch = X_train.shape[0] // batch_size)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:29:38.735887Z","iopub.execute_input":"2025-09-01T08:29:38.736232Z","iopub.status.idle":"2025-09-01T08:31:04.562825Z","shell.execute_reply.started":"2025-09-01T08:29:38.736209Z","shell.execute_reply":"2025-09-01T08:31:04.561958Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Evaluate the model\n    # test(validation) loss visualization\n    # confisuon matrix\n\nplt.plot(history.history['val_loss'], color = 'b')\nplt.title(\"Test Loss\")\nplt.xlabel(\"Number of epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-09-01T08:32:17.313998Z","iopub.execute_input":"2025-09-01T08:32:17.314341Z","iopub.status.idle":"2025-09-01T08:32:17.489968Z","shell.execute_reply.started":"2025-09-01T08:32:17.314319Z","shell.execute_reply":"2025-09-01T08:32:17.489073Z"}},"outputs":[],"execution_count":null}]}