{"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":"code","source":"import numpy as np\nimport pandas as pd\n\nimport tensorflow as tf\nimport tensorflow.keras as keras\nfrom tensorflow.keras import layers\n\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import confusion_matrix","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:13.692955Z","iopub.execute_input":"2025-08-22T07:27:13.693327Z","iopub.status.idle":"2025-08-22T07:27:13.967267Z","shell.execute_reply.started":"2025-08-22T07:27:13.693300Z","shell.execute_reply":"2025-08-22T07:27:13.966495Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:13.968899Z","iopub.execute_input":"2025-08-22T07:27:13.969163Z","iopub.status.idle":"2025-08-22T07:27:13.978220Z","shell.execute_reply.started":"2025-08-22T07:27:13.969142Z","shell.execute_reply":"2025-08-22T07:27:13.977387Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"mnist_train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\nmnist_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')\n\ndisplay(\" train data\",mnist_train )\ndisplay(\" test data\",mnist_test )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:13.979118Z","iopub.execute_input":"2025-08-22T07:27:13.979400Z","iopub.status.idle":"2025-08-22T07:27:19.283842Z","shell.execute_reply.started":"2025-08-22T07:27:13.979379Z","shell.execute_reply":"2025-08-22T07:27:19.282965Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_size=28*28\nimage_size","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:19.285940Z","iopub.execute_input":"2025-08-22T07:27:19.286252Z","iopub.status.idle":"2025-08-22T07:27:19.291941Z","shell.execute_reply.started":"2025-08-22T07:27:19.286228Z","shell.execute_reply":"2025-08-22T07:27:19.291091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = mnist_train.drop('label', axis=1).copy()\nX_test = mnist_test.copy()\nY_train = mnist_train['label'].copy()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:19.292737Z","iopub.execute_input":"2025-08-22T07:27:19.293026Z","iopub.status.idle":"2025-08-22T07:27:19.651879Z","shell.execute_reply.started":"2025-08-22T07:27:19.293006Z","shell.execute_reply":"2025-08-22T07:27:19.650942Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train.describe()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:19.652898Z","iopub.execute_input":"2025-08-22T07:27:19.653202Z","iopub.status.idle":"2025-08-22T07:27:21.751172Z","shell.execute_reply.started":"2025-08-22T07:27:19.653176Z","shell.execute_reply":"2025-08-22T07:27:21.749966Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = X_train / 255.0\nX_test = X_test / 255.0","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:21.752044Z","iopub.execute_input":"2025-08-22T07:27:21.752268Z","iopub.status.idle":"2025-08-22T07:27:21.855162Z","shell.execute_reply.started":"2025-08-22T07:27:21.752253Z","shell.execute_reply":"2025-08-22T07:27:21.854583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"X_train = X_train.values.reshape(-1, 28, 28, 1)\nX_test = X_test.values.reshape(-1, 28, 28, 1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:21.855911Z","iopub.execute_input":"2025-08-22T07:27:21.856475Z","iopub.status.idle":"2025-08-22T07:27:21.861449Z","shell.execute_reply.started":"2025-08-22T07:27:21.856444Z","shell.execute_reply":"2025-08-22T07:27:21.860517Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\nno_images=len(X_train)\n\nfig, ax = plt.subplots(figsize=(10, 10))\n\nplt.imshow(X_train[random.randint(0,no_images), :, :, 0], cmap='Greys', interpolation='nearest') \n\nplt.title(\"Sample Image\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:21.863020Z","iopub.execute_input":"2025-08-22T07:27:21.863249Z","iopub.status.idle":"2025-08-22T07:27:22.238894Z","shell.execute_reply.started":"2025-08-22T07:27:21.863232Z","shell.execute_reply":"2025-08-22T07:27:22.238014Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"\nfig, ax = plt.subplots(figsize=(2,2)) \n\nplt.imshow(X_train[random.randint(0,no_images), :, :, 0], cmap='Greys', interpolation='nearest')\nplt.title(\"Sample Image\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.241714Z","iopub.execute_input":"2025-08-22T07:27:22.241961Z","iopub.status.idle":"2025-08-22T07:27:22.364671Z","shell.execute_reply.started":"2025-08-22T07:27:22.241943Z","shell.execute_reply":"2025-08-22T07:27:22.363856Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"validation_size= 0.2\n\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size= validation_size)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.365239Z","iopub.execute_input":"2025-08-22T07:27:22.365462Z","iopub.status.idle":"2025-08-22T07:27:22.765266Z","shell.execute_reply.started":"2025-08-22T07:27:22.365438Z","shell.execute_reply":"2025-08-22T07:27:22.764504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"Y_train = keras.utils.to_categorical(Y_train, num_classes=10)\nY_val = keras.utils.to_categorical(Y_val, num_classes=10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.766212Z","iopub.execute_input":"2025-08-22T07:27:22.766526Z","iopub.status.idle":"2025-08-22T07:27:22.773222Z","shell.execute_reply.started":"2025-08-22T07:27:22.766504Z","shell.execute_reply":"2025-08-22T07:27:22.772368Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def CNN():\n    model = keras.Sequential()\n    model.add(layers.Conv2D(32, (3, 3), (1, 1), padding='valid', input_shape=(28, 28, 1), name='conv2d_1_1'))\n    model.add(layers.Conv2D(32, (3, 3), (1, 1), padding='same', name='conv2d_1_2'))\n    model.add(layers.BatchNormalization(name='bn_1'))\n    model.add(layers.Activation('relu', name='relu_1'))\n    model.add(layers.MaxPooling2D((2, 2), (2, 2), padding='valid', name='mp2d_1'))\n    model.add(layers.Dropout(0.2, name='drop_1'))\n    model.add(layers.Conv2D(64, (3, 3), (1, 1), padding='valid', name='conv2d_2_1'))\n    model.add(layers.Conv2D(64, (3, 3), (1, 1), padding='same', name='conv2d_2_2'))\n    model.add(layers.BatchNormalization(name='bn_2'))\n    model.add(layers.Activation('relu', name='relu_2'))\n    model.add(layers.MaxPooling2D((2, 2), (2, 2), padding='valid', name='mp2d_2'))\n    model.add(layers.Dropout(0.2, name='drop_2'))\n    model.add(layers.Flatten())\n    model.add(layers.Dense(100, activation='relu'))\n    model.add(layers.Dense(10, activation='softmax'))\n    \n    return model","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.774861Z","iopub.execute_input":"2025-08-22T07:27:22.775615Z","iopub.status.idle":"2025-08-22T07:27:22.792570Z","shell.execute_reply.started":"2025-08-22T07:27:22.775584Z","shell.execute_reply":"2025-08-22T07:27:22.791610Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = CNN()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.793619Z","iopub.execute_input":"2025-08-22T07:27:22.793930Z","iopub.status.idle":"2025-08-22T07:27:22.966778Z","shell.execute_reply.started":"2025-08-22T07:27:22.793895Z","shell.execute_reply":"2025-08-22T07:27:22.965835Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.compile(optimizer='adam', loss='CategoricalCrossentropy', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.967818Z","iopub.execute_input":"2025-08-22T07:27:22.968155Z","iopub.status.idle":"2025-08-22T07:27:22.979370Z","shell.execute_reply.started":"2025-08-22T07:27:22.968128Z","shell.execute_reply":"2025-08-22T07:27:22.978532Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:22.980381Z","iopub.execute_input":"2025-08-22T07:27:22.980700Z","iopub.status.idle":"2025-08-22T07:27:23.012676Z","shell.execute_reply.started":"2025-08-22T07:27:22.980675Z","shell.execute_reply":"2025-08-22T07:27:23.011613Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history = model.fit(X_train, Y_train, validation_data=(X_val, Y_val), batch_size=64, epochs=50, verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T07:27:23.013732Z","iopub.execute_input":"2025-08-22T07:27:23.013975Z","iopub.status.idle":"2025-08-22T08:13:12.628355Z","shell.execute_reply.started":"2025-08-22T07:27:23.013955Z","shell.execute_reply":"2025-08-22T08:13:12.627501Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='accuracy')\nplt.plot(history.history['val_accuracy'], label='val_accuracy')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend(loc='lower right')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='loss')\nplt.plot(history.history['val_loss'], label='val_loss')\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend(loc='lower right')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T08:13:12.630055Z","iopub.execute_input":"2025-08-22T08:13:12.630317Z","iopub.status.idle":"2025-08-22T08:13:13.296300Z","shell.execute_reply.started":"2025-08-22T08:13:12.630297Z","shell.execute_reply":"2025-08-22T08:13:13.295122Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def predict(model, X, imgs):\n    s = int(np.sqrt(imgs))\n    fig, ax = plt.subplots(s, s, sharex=True, sharey=True, figsize=(15, 15))\n    ax = ax.flatten()\n    preds = model.predict(X[:imgs])\n    for i in range(imgs):\n        y_pred = np.argmax(preds[i])\n        img = X[i].reshape(28, 28)\n        ax[i].imshow(img, cmap='Greys', interpolation='nearest')\n        ax[i].set_title(f'p: {y_pred}')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T08:13:13.297417Z","iopub.execute_input":"2025-08-22T08:13:13.297797Z","iopub.status.idle":"2025-08-22T08:13:13.304640Z","shell.execute_reply.started":"2025-08-22T08:13:13.297766Z","shell.execute_reply":"2025-08-22T08:13:13.303457Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predict(model, X_test, 25)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-22T08:13:13.305806Z","iopub.execute_input":"2025-08-22T08:13:13.306109Z","iopub.status.idle":"2025-08-22T08:13:17.576358Z","shell.execute_reply.started":"2025-08-22T08:13:13.306087Z","shell.execute_reply":"2025-08-22T08:13:17.575528Z"}},"outputs":[],"execution_count":null}]}