{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"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":"2023-10-05T06:36:45.965627Z","iopub.execute_input":"2023-10-05T06:36:45.966088Z","iopub.status.idle":"2023-10-05T06:36:45.977241Z","shell.execute_reply.started":"2023-10-05T06:36:45.966059Z","shell.execute_reply":"2023-10-05T06:36:45.976124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Importing Dependencies","metadata":{}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torchvision\nfrom torchvision import transforms\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torch.utils.data import TensorDataset\nfrom torch.utils.data import Dataset\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import train_test_split\n\nfrom torch.autograd import Variable","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:45.980092Z","iopub.execute_input":"2023-10-05T06:36:45.980720Z","iopub.status.idle":"2023-10-05T06:36:45.986791Z","shell.execute_reply.started":"2023-10-05T06:36:45.980689Z","shell.execute_reply":"2023-10-05T06:36:45.985934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\ndevice = (\n    \"cuda\"\n    if torch.cuda.is_available()\n    else \"mps\"\n    if torch.backends.mps.is_available()\n    else \"cpu\"\n)\nprint(f\"Using {device} device\")","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:45.987884Z","iopub.execute_input":"2023-10-05T06:36:45.989681Z","iopub.status.idle":"2023-10-05T06:36:46.012715Z","shell.execute_reply.started":"2023-10-05T06:36:45.989650Z","shell.execute_reply":"2023-10-05T06:36:46.011754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Loading Data","metadata":{}},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\ntest = pd.read_csv(\"/kaggle/input/Kannada-MNIST/Dig-MNIST.csv\")\nsubmission_set = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:46.013957Z","iopub.execute_input":"2023-10-05T06:36:46.014906Z","iopub.status.idle":"2023-10-05T06:36:48.900469Z","shell.execute_reply.started":"2023-10-05T06:36:46.014875Z","shell.execute_reply":"2023-10-05T06:36:48.899309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:48.903173Z","iopub.execute_input":"2023-10-05T06:36:48.903426Z","iopub.status.idle":"2023-10-05T06:36:48.918825Z","shell.execute_reply.started":"2023-10-05T06:36:48.903404Z","shell.execute_reply":"2023-10-05T06:36:48.917527Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"`Train data contains each pixel as feature and total of 785 columns with one feature as LABEL`","metadata":{}},{"cell_type":"code","source":"train['label'].unique()","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:48.920581Z","iopub.execute_input":"2023-10-05T06:36:48.921520Z","iopub.status.idle":"2023-10-05T06:36:48.934389Z","shell.execute_reply.started":"2023-10-05T06:36:48.921489Z","shell.execute_reply":"2023-10-05T06:36:48.933276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"`It is a classification problem with 10 classes`","metadata":{}},{"cell_type":"code","source":"train_img = train.drop(columns=[\"label\"])\ntrain_label = train[\"label\"]\n\ntest_img = test.drop(columns=[\"label\"])\ntest_label = test[\"label\"]\n\nprediction_image = submission_set.drop(columns=[\"id\"])","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:48.937024Z","iopub.execute_input":"2023-10-05T06:36:48.937878Z","iopub.status.idle":"2023-10-05T06:36:49.086157Z","shell.execute_reply.started":"2023-10-05T06:36:48.937844Z","shell.execute_reply":"2023-10-05T06:36:49.084990Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_img, val_img, train_label, val_label = train_test_split(train_img, train_label, test_size=0.3)","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.087999Z","iopub.execute_input":"2023-10-05T06:36:49.088839Z","iopub.status.idle":"2023-10-05T06:36:49.469204Z","shell.execute_reply.started":"2023-10-05T06:36:49.088791Z","shell.execute_reply":"2023-10-05T06:36:49.467887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_img.reset_index(drop=True, inplace=True)\ntrain_label.reset_index(drop=True, inplace=True)\n\nval_img.reset_index(drop=True, inplace=True)\nval_label.reset_index(drop=True, inplace=True)\n\ntest_img.reset_index(drop=True, inplace=True)\ntest_label.reset_index(drop=True, inplace=True)\n\nprediction_image.reset_index(drop=True, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.470675Z","iopub.execute_input":"2023-10-05T06:36:49.471168Z","iopub.status.idle":"2023-10-05T06:36:49.478863Z","shell.execute_reply.started":"2023-10-05T06:36:49.471138Z","shell.execute_reply":"2023-10-05T06:36:49.477741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"`we reset the index to order`","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = 28\n\nclass KDataset(Dataset):\n    def __init__(self, images, labels, transforms = None) -> None:\n        self.X = images\n        self.y = labels\n        self.transforms = transforms\n    \n    def __len__(self):\n        return (len(self.X))\n    \n    def __getitem__(self, i):\n        data = self.X.iloc[i,:]\n        data = np.array(data).astype(np.uint8).reshape(IMAGE_SIZE, IMAGE_SIZE, 1)\n        if self.transforms:\n            data = self.transforms(data)  \n        if self.y is not None:\n            return (data, self.y[i])\n        else:\n            return data","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.481397Z","iopub.execute_input":"2023-10-05T06:36:49.483751Z","iopub.status.idle":"2023-10-05T06:36:49.494555Z","shell.execute_reply.started":"2023-10-05T06:36:49.483722Z","shell.execute_reply":"2023-10-05T06:36:49.493534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_transforms = transforms.Compose(([\n    transforms.ToPILImage(),\n    transforms.ToTensor(),\n]))\n\nval_transforms = transforms.Compose(([\n    transforms.ToPILImage(),\n    transforms.ToTensor(),\n]))","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.498440Z","iopub.execute_input":"2023-10-05T06:36:49.500530Z","iopub.status.idle":"2023-10-05T06:36:49.512130Z","shell.execute_reply.started":"2023-10-05T06:36:49.500499Z","shell.execute_reply":"2023-10-05T06:36:49.511212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE = 45\n\ntrain_dataset = KDataset(train_img, train_label, train_transforms)\n\nval_dataset = KDataset(val_img, val_label, val_transforms)\n\ntest_dataset = KDataset(test_img, test_label, val_transforms)\n\nsubmission_dataset = KDataset(prediction_image, None, val_transforms)","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.515128Z","iopub.execute_input":"2023-10-05T06:36:49.516146Z","iopub.status.idle":"2023-10-05T06:36:49.525915Z","shell.execute_reply.started":"2023-10-05T06:36:49.516116Z","shell.execute_reply":"2023-10-05T06:36:49.524887Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataloader = DataLoader(train_dataset,\n                              batch_size = BATCH_SIZE,\n                              shuffle = True)\nval_dataloader = DataLoader(val_dataset,\n                            batch_size = BATCH_SIZE,\n                            shuffle = False)\ntest_dataloader = DataLoader(test_dataset,\n                             batch_size = BATCH_SIZE,\n                             shuffle = False)\nprediction_dataloader = DataLoader(submission_dataset,\n                                   batch_size = BATCH_SIZE,\n                                   shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.527407Z","iopub.execute_input":"2023-10-05T06:36:49.528307Z","iopub.status.idle":"2023-10-05T06:36:49.543449Z","shell.execute_reply.started":"2023-10-05T06:36:49.528278Z","shell.execute_reply":"2023-10-05T06:36:49.542334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images, labels = next(iter(train_dataloader))\nimages, labels = images[:2], labels[:2]\nplt.imshow(torchvision.utils.make_grid(images)[0,:,:], cmap=\"gray\")\nprint(labels)","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.551997Z","iopub.execute_input":"2023-10-05T06:36:49.554829Z","iopub.status.idle":"2023-10-05T06:36:49.876389Z","shell.execute_reply.started":"2023-10-05T06:36:49.554795Z","shell.execute_reply":"2023-10-05T06:36:49.875467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create ANN Model\n\nclass MLP(nn.Module):\n    def __init__(self):\n        super(MLP, self).__init__()\n        self.flatten = nn.Flatten()\n        self.linear_relu_stack = nn.Sequential(\n            nn.Linear(28*28, 512),\n            nn.ReLU(),\n            nn.Linear(512, 256),\n            nn.ReLU(),\n            nn.Linear(256, 64),\n            nn.ReLU(),\n            nn.Linear(64,10)\n        )\n\n    def forward(self, x):\n        x = self.flatten(x)\n        x = x.type(self.linear_relu_stack[0].weight.dtype)\n        logits = self.linear_relu_stack(x)\n        return logits\n\n\nmodel = MLP()\n# Define loss function and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.Adam(model.parameters(), lr=0.001)\n\n# Lists to store loss values\ntrain_losses = []\nval_losses = []\n\n# Training loop\nnum_epochs = 30\nfor epoch in range(num_epochs):\n    model.train()\n    train_loss = 0.0\n    correct_train = 0\n    total_train = 0\n\n    for inputs, labels in train_dataloader:\n        optimizer.zero_grad()\n        outputs = model(inputs)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n\n        train_loss += loss.item()\n        _, predicted = torch.max(outputs.data, 1)\n        total_train += labels.size(0)\n        correct_train += (predicted == labels).sum().item()\n\n    train_accuracy = 100 * correct_train / total_train\n    print(f\"Epoch [{epoch+1}/{num_epochs}] - Train Loss: {train_loss:.4f}, Train Accuracy: {train_accuracy:.2f}%\")\n\n    # Validation loop\n    model.eval()\n    val_loss = 0.0\n    correct_val = 0\n    total_val = 0\n\n    with torch.no_grad():\n        for inputs, labels in val_dataloader:\n            outputs = model(inputs)\n            loss = criterion(outputs, labels)\n            val_loss += loss.item()\n            _, predicted = torch.max(outputs.data, 1)\n            total_val += labels.size(0)\n            correct_val += (predicted == labels).sum().item()\n\n    val_accuracy = 100 * correct_val / total_val\n    print(f\"Epoch [{epoch+1}/{num_epochs}] - Validation Loss: {val_loss:.4f}, Validation Accuracy: {val_accuracy:.2f}%\")\n    \n    # Append loss values to the lists\n    train_losses.append(train_loss)\n    val_losses.append(val_loss)\n\n# Plotting the loss graph\nplt.figure()\nplt.plot(range(1, num_epochs+1), train_losses, label=\"Train Loss\")\nplt.plot(range(1, num_epochs+1), val_losses, label=\"Validation Loss\")\nplt.xlabel(\"Epoch\")\nplt.ylabel(\"Loss\")\nplt.title(\"Train Loss vs Validation Loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-05T06:36:49.880681Z","iopub.execute_input":"2023-10-05T06:36:49.881318Z","iopub.status.idle":"2023-10-05T06:47:54.772570Z","shell.execute_reply.started":"2023-10-05T06:36:49.881267Z","shell.execute_reply":"2023-10-05T06:47:54.771715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score\n\n# Function to calculate accuracy\ndef calculate_accuracy(predictions, labels):\n    _, predicted = torch.max(predictions, 1)\n    accuracy = accuracy_score(predicted.cpu().numpy(), labels.cpu().numpy())\n    return accuracy\n# Evaluation for test data\nmodel.eval()\ntest_loss = 0.0\ntest_accuracy = 0.0\n\nwith torch.no_grad():\n    for images, labels in test_dataloader:\n        images, labels = images, labels\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        \n        test_loss += loss.item()\n        test_accuracy += calculate_accuracy(outputs, labels)\n\ntest_loss /= len(test_dataloader)\ntest_accuracy /= len(test_dataloader)\n\nprint(f'Test Loss: {test_loss:.4f}')\nprint(f'Test Accuracy: {test_accuracy * 100:.2f}%')","metadata":{"execution":{"iopub.status.busy":"2023-10-05T07:24:24.475093Z","iopub.execute_input":"2023-10-05T07:24:24.475428Z","iopub.status.idle":"2023-10-05T07:24:27.089504Z","shell.execute_reply.started":"2023-10-05T07:24:24.475401Z","shell.execute_reply":"2023-10-05T07:24:27.088497Z"},"trusted":true},"execution_count":null,"outputs":[]}]}