{"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":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30732,"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","execution":{"iopub.status.busy":"2024-06-14T19:33:10.046527Z","iopub.execute_input":"2024-06-14T19:33:10.047008Z","iopub.status.idle":"2024-06-14T19:33:10.060450Z","shell.execute_reply.started":"2024-06-14T19:33:10.046973Z","shell.execute_reply":"2024-06-14T19:33:10.058378Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:10.409261Z","iopub.execute_input":"2024-06-14T19:33:10.410297Z","iopub.status.idle":"2024-06-14T19:33:14.695196Z","shell.execute_reply.started":"2024-06-14T19:33:10.410231Z","shell.execute_reply":"2024-06-14T19:33:14.693910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.info()","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:14.698235Z","iopub.execute_input":"2024-06-14T19:33:14.698751Z","iopub.status.idle":"2024-06-14T19:33:14.749485Z","shell.execute_reply.started":"2024-06-14T19:33:14.698705Z","shell.execute_reply":"2024-06-14T19:33:14.748293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torchvision\nimport torchvision.transforms as transforms\nimport matplotlib.pyplot as plt\nimport torch.nn.functional as F\n","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:14.751079Z","iopub.execute_input":"2024-06-14T19:33:14.751542Z","iopub.status.idle":"2024-06-14T19:33:14.763470Z","shell.execute_reply.started":"2024-06-14T19:33:14.751501Z","shell.execute_reply":"2024-06-14T19:33:14.762045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = train_data.drop('label',axis=1)\ny = train_data['label']\n","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:14.764970Z","iopub.execute_input":"2024-06-14T19:33:14.765386Z","iopub.status.idle":"2024-06-14T19:33:15.484084Z","shell.execute_reply.started":"2024-06-14T19:33:14.765354Z","shell.execute_reply":"2024-06-14T19:33:15.482664Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"classes = y.unique()\nnum_classes = len(y.unique())\n\nprint (classes)\nprint (num_classes)","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:15.487898Z","iopub.execute_input":"2024-06-14T19:33:15.488497Z","iopub.status.idle":"2024-06-14T19:33:15.498724Z","shell.execute_reply.started":"2024-06-14T19:33:15.488453Z","shell.execute_reply":"2024-06-14T19:33:15.497217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3, random_state = 0)\ny_train = y_train.to_numpy()\nX_train = X_train.to_numpy()\nX_test = X_test.to_numpy()\ny_test = y_test.to_numpy()","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:15.500293Z","iopub.execute_input":"2024-06-14T19:33:15.500795Z","iopub.status.idle":"2024-06-14T19:33:16.357215Z","shell.execute_reply.started":"2024-06-14T19:33:15.500750Z","shell.execute_reply":"2024-06-14T19:33:16.356050Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Net(nn.Module):\n    def __init__(self, num_classes):\n        super(Net, self).__init__()\n        self.conv1 = nn.Conv2d(1,32, kernel_size = 3, stride = 1, padding =1)\n        self.conv2 = nn.Conv2d(32, 64, kernel_size = 3, stride = 1, padding=1)\n        self.fc1 = nn.Linear(64*7*7, num_classes)\n#        self.fc2 = nn.Linear(128, num_classes)\n        \n    def forward(self,x):\n        x = F.relu(self.conv1(x))\n        x = F.max_pool2d(x,2)\n        x = F.relu(self.conv2(x))\n        x = F.max_pool2d(x,2)\n        x = x.view(x.size(0), -1) #Flatten the tensor\n        x = self.fc1(x)\n   #     x = self.fc2(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:16.358647Z","iopub.execute_input":"2024-06-14T19:33:16.359096Z","iopub.status.idle":"2024-06-14T19:33:16.370475Z","shell.execute_reply.started":"2024-06-14T19:33:16.359056Z","shell.execute_reply":"2024-06-14T19:33:16.369140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import DataLoader, TensorDataset\n\nX_train_tensor = torch.tensor(X_train, dtype=torch.float32)\ny_train_tensor = torch.tensor(y_train, dtype=torch.long)\nX_train_reshaped = X_train_tensor.view(X_train_tensor.shape[0], 1, 28, 28)\n#Create the TensorData and DataLoader\ntrain_dataset = TensorDataset(X_train_reshaped, y_train_tensor)\ntrain_loader = DataLoader(train_dataset, batch_size = 1, shuffle = True)","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:16.372094Z","iopub.execute_input":"2024-06-14T19:33:16.372655Z","iopub.status.idle":"2024-06-14T19:33:16.442077Z","shell.execute_reply.started":"2024-06-14T19:33:16.372599Z","shell.execute_reply":"2024-06-14T19:33:16.440902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nX_test_tensor = torch.tensor(X_test, dtype=torch.float32)\ny_test_tensor = torch.tensor(y_test, dtype=torch.long)\nX_test_reshaped = X_test_tensor.view(X_test_tensor.shape[0], 1, 28, 28)\n#Create the TensorData and DataLoader\ntest_dataset = TensorDataset(X_test_reshaped, y_test_tensor)\ntest_loader = DataLoader(test_dataset, batch_size = 1, shuffle = True)","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:16.443550Z","iopub.execute_input":"2024-06-14T19:33:16.444003Z","iopub.status.idle":"2024-06-14T19:33:16.478077Z","shell.execute_reply.started":"2024-06-14T19:33:16.443961Z","shell.execute_reply":"2024-06-14T19:33:16.476550Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preview_image (tensor, index):\n    '''\n    Preview the image of the train or test set\n    '''\n    img = tensor[index].numpy()\n    img = img.reshape(28,28)\n    plt.imshow(img, cmap = \"gray\")\n    plt.show()\n\npreview_image(X_train_tensor, 0)\npreview_image(X_train_tensor, 25)\npreview_image(X_train_tensor, 5)","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:16.479511Z","iopub.execute_input":"2024-06-14T19:33:16.479868Z","iopub.status.idle":"2024-06-14T19:33:17.193758Z","shell.execute_reply.started":"2024-06-14T19:33:16.479837Z","shell.execute_reply":"2024-06-14T19:33:17.192367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.optim as optim\n\nmodel = Net(num_classes = 10)\nprint (model)\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr = 0.001)\n\nfor epoch in range(4):\n    model.train()\n    running_loss = 0.0\n    \n    for inputs, labels in train_loader:\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n    \n        running_loss += loss.item()\n    \n    print(f'Epoch {epoch + 1}, Loss: {running_loss / len(train_loader)}')\n\nprint('Finished Training')","metadata":{"execution":{"iopub.status.busy":"2024-06-14T19:33:17.195513Z","iopub.execute_input":"2024-06-14T19:33:17.195976Z","iopub.status.idle":"2024-06-14T19:41:58.221429Z","shell.execute_reply.started":"2024-06-14T19:33:17.195933Z","shell.execute_reply":"2024-06-14T19:41:58.220030Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Evaluating Model Performance\n\nfrom torchmetrics import Recall\nfrom torchmetrics import Precision\n\nmetric_recall = Recall(task = \"multiclass\", num_classes = 10, average = \"micro\")\nmetric_precision = Precision(task = \"multiclass\", num_classes = 10, average = \"micro\")\n\n\nmodel.eval()\npreds_list = []\nlabels_list = []\n\nwith torch.no_grad():\n    for inputs, labels in test_loader:\n        outputs = model(inputs)\n        _, preds = torch.max(outputs, 1)\n        preds_list.extend(preds.tolist())\n        labels_list.extend(labels.tolist())\n        metric_precision(preds, labels)\n        metric_recall(preds, labels)\n\n    \nprecision = metric_precision.compute()\nrecall = metric_recall.compute()\n\nprint(f'Precision: {precision}')\nprint(f'Recall: {recall}')","metadata":{"execution":{"iopub.status.busy":"2024-06-14T20:18:57.848359Z","iopub.execute_input":"2024-06-14T20:18:57.848797Z","iopub.status.idle":"2024-06-14T20:19:25.413921Z","shell.execute_reply.started":"2024-06-14T20:18:57.848761Z","shell.execute_reply":"2024-06-14T20:19:25.412483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Convert predictions list to Pandas Series\nprediction_df = pd.DataFrame()\nprediction_df['Actual'] = y_test\nprediction_df['Predictions'] = preds_list\n\nprediction_df","metadata":{"execution":{"iopub.status.busy":"2024-06-14T20:19:37.087776Z","iopub.execute_input":"2024-06-14T20:19:37.088241Z","iopub.status.idle":"2024-06-14T20:19:37.111019Z","shell.execute_reply.started":"2024-06-14T20:19:37.088206Z","shell.execute_reply":"2024-06-14T20:19:37.109906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preview_image(X_test_tensor, 0)","metadata":{"execution":{"iopub.status.busy":"2024-06-14T20:11:31.655052Z","iopub.execute_input":"2024-06-14T20:11:31.656749Z","iopub.status.idle":"2024-06-14T20:11:31.935338Z","shell.execute_reply.started":"2024-06-14T20:11:31.656692Z","shell.execute_reply":"2024-06-14T20:11:31.932600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preview_image(X_test_tensor, 4)\nprediction_df.loc[4]","metadata":{"execution":{"iopub.status.busy":"2024-06-14T20:16:30.335780Z","iopub.execute_input":"2024-06-14T20:16:30.336245Z","iopub.status.idle":"2024-06-14T20:16:30.632350Z","shell.execute_reply.started":"2024-06-14T20:16:30.336179Z","shell.execute_reply":"2024-06-14T20:16:30.630917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preview_image(X_test_tensor, 12597)\n\nprediction_df.iloc[12597,]","metadata":{"execution":{"iopub.status.busy":"2024-06-14T20:18:26.525967Z","iopub.execute_input":"2024-06-14T20:18:26.526408Z","iopub.status.idle":"2024-06-14T20:18:26.759437Z","shell.execute_reply.started":"2024-06-14T20:18:26.526373Z","shell.execute_reply":"2024-06-14T20:18:26.758245Z"},"trusted":true},"execution_count":null,"outputs":[]}]}