{"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":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# Import necessary libraries\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.utils.data import DataLoader\nfrom sklearn.model_selection import train_test_split as split","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:54.276977Z","iopub.execute_input":"2024-11-10T11:18:54.277572Z","iopub.status.idle":"2024-11-10T11:18:54.284576Z","shell.execute_reply.started":"2024-11-10T11:18:54.277523Z","shell.execute_reply":"2024-11-10T11:18:54.282785Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Import the dataset\nimport pandas as pd\n\ndf = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\n# test = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\nX = df.iloc[:, 1:].values\ny = df.iloc[:, 0].values\n# test_X = test.iloc[:, 1:].values\n# test_y = test.iloc[:, 0].values","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:54.287252Z","iopub.execute_input":"2024-11-10T11:18:54.288309Z","iopub.status.idle":"2024-11-10T11:18:56.906912Z","shell.execute_reply.started":"2024-11-10T11:18:54.288247Z","shell.execute_reply":"2024-11-10T11:18:56.905453Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_X, test_X, train_y, test_y = split(\n    X,  # Features\n    y,   # Labels\n    test_size=0.2,             # 20% test data\n    random_state=42            # For reproducibility\n)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:56.909409Z","iopub.execute_input":"2024-11-10T11:18:56.909947Z","iopub.status.idle":"2024-11-10T11:18:57.339077Z","shell.execute_reply.started":"2024-11-10T11:18:56.909890Z","shell.execute_reply":"2024-11-10T11:18:57.337752Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"# Dataset class\nfrom torch.utils.data import Dataset, DataLoader\n\nclass CSVDataset(Dataset):\n    def __init__(self, data, labels, transform=None):\n        self.data = torch.tensor(data, dtype=torch.float32)\n        self.labels = torch.tensor(labels, dtype=torch.long)\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        sample = self.data[idx]\n        label = self.labels[idx]\n\n        if self.transform:\n            sample = self.transform(sample)\n\n        return sample, label\n    ","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:57.340421Z","iopub.execute_input":"2024-11-10T11:18:57.340903Z","iopub.status.idle":"2024-11-10T11:18:57.349132Z","shell.execute_reply.started":"2024-11-10T11:18:57.340850Z","shell.execute_reply":"2024-11-10T11:18:57.347956Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = CSVDataset(data=train_X, labels=train_y)\ntrainloader = DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)\ntest_dataset = CSVDataset(data=test_X, labels=test_y)\ntestloader = DataLoader(dataset=test_dataset, batch_size=64, shuffle=True)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:57.351550Z","iopub.execute_input":"2024-11-10T11:18:57.351938Z","iopub.status.idle":"2024-11-10T11:18:57.445508Z","shell.execute_reply.started":"2024-11-10T11:18:57.351897Z","shell.execute_reply":"2024-11-10T11:18:57.444334Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch.nn as nn\n\nclass ANN(nn.Module):\n    def __init__(self):\n        super(ANN, self).__init__()\n        self.fc1 = nn.Linear(28*28, 10)\n        self.fc2 = nn.Linear(10, 10)\n        self.fc3 = nn.Linear(10, 10)\n\n    def forward(self, x):\n        x = x.view(x.size(0), -1)\n        x = torch.relu(self.fc1(x))\n        x = torch.relu(self.fc2(x))\n        x = self.fc3(x)\n\n        return x\n\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:57.446978Z","iopub.execute_input":"2024-11-10T11:18:57.447354Z","iopub.status.idle":"2024-11-10T11:18:57.455373Z","shell.execute_reply.started":"2024-11-10T11:18:57.447319Z","shell.execute_reply":"2024-11-10T11:18:57.454019Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"lr = 0.001\nepochs = 500\n\nmodel = ANN()\n\ncriterion = nn.CrossEntropyLoss()\n\noptimizer = optim.Adam(model.parameters(), lr=lr)\n\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:18:57.456816Z","iopub.execute_input":"2024-11-10T11:18:57.457297Z","iopub.status.idle":"2024-11-10T11:18:57.469921Z","shell.execute_reply.started":"2024-11-10T11:18:57.457256Z","shell.execute_reply":"2024-11-10T11:18:57.468590Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for epoch in range(epochs):\n    model.train()\n    running_loss = 0.0\n\n    for images, label in trainloader:\n        optimizer.zero_grad()\n\n        op = model(images)\n        loss = criterion(op, label)\n\n        loss.backward()\n        optimizer.step()\n\n        running_loss += loss.item()\n\n    print(f'Epoch [{epoch+1}/{epochs}], Loss: {running_loss/len(trainloader):.4f}')","metadata":{"execution":{"iopub.status.busy":"2024-11-10T11:18:57.471398Z","iopub.execute_input":"2024-11-10T11:18:57.471804Z","iopub.status.idle":"2024-11-10T11:19:03.135580Z","shell.execute_reply.started":"2024-11-10T11:18:57.471765Z","shell.execute_reply":"2024-11-10T11:19:03.134368Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\ncorrect = 0\ntotal = 0\n\nwith torch.no_grad():\n    for images, labels in trainloader:\n        op = model(images)\n        _, predicted = torch.max(op.data, 1)\n        total += labels.size(0)\n        correct += (predicted==labels).sum().item()\n\nprint(f\"Training Accuracy: {correct/total}\")\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:19:03.136925Z","iopub.execute_input":"2024-11-10T11:19:03.137272Z","iopub.status.idle":"2024-11-10T11:19:03.716484Z","shell.execute_reply.started":"2024-11-10T11:19:03.137238Z","shell.execute_reply":"2024-11-10T11:19:03.715253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\ncorrect = 0\ntotal = 0\n\nwith torch.no_grad():\n    for images, labels in testloader:\n        op = model(images)\n        _, predicted = torch.max(op.data, 1)\n        total += labels.size(0)\n        correct += (predicted==labels).sum().item()\n\nprint(f\"Testing Accuracy: {correct/total}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-10T11:19:03.717919Z","iopub.execute_input":"2024-11-10T11:19:03.718326Z","iopub.status.idle":"2024-11-10T11:19:03.850746Z","shell.execute_reply.started":"2024-11-10T11:19:03.718287Z","shell.execute_reply":"2024-11-10T11:19:03.849399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}