{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":16017,"databundleVersionId":708189,"sourceType":"competition"}],"dockerImageVersionId":30635,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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-01-17T11:58:37.861849Z","iopub.execute_input":"2024-01-17T11:58:37.862843Z","iopub.status.idle":"2024-01-17T11:58:38.708271Z","shell.execute_reply.started":"2024-01-17T11:58:37.862808Z","shell.execute_reply":"2024-01-17T11:58:38.707270Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import libraries\nimport torch\nfrom torch.utils.data import DataLoader, Dataset\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data.sampler import SubsetRandomSampler\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:38.710523Z","iopub.execute_input":"2024-01-17T11:58:38.711311Z","iopub.status.idle":"2024-01-17T11:58:42.210142Z","shell.execute_reply.started":"2024-01-17T11:58:38.711279Z","shell.execute_reply":"2024-01-17T11:58:42.209090Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class TrainMNIST(Dataset):\n    \n    def __init__(self, file_path, transform=None):\n        self.data = pd.read_csv(file_path)\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, index):\n        # load image as ndarray type (Height * Width * Channels)\n        # be carefull for converting dtype to np.uint8 [Unsigned integer (0 to 255)]\n        # in this example, we use ToTensor(), so we define the numpy array like (H, W, C)\n        image = self.data.iloc[index, 1:].values.astype(np.uint8).reshape((28, 28, 1))\n        label = self.data.iloc[index, 0]\n        \n        if self.transform is not None:\n            image = self.transform(image)\n            \n        return image, label","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:42.211437Z","iopub.execute_input":"2024-01-17T11:58:42.211881Z","iopub.status.idle":"2024-01-17T11:58:42.219594Z","shell.execute_reply.started":"2024-01-17T11:58:42.211854Z","shell.execute_reply":"2024-01-17T11:58:42.218359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class TestMNIST(Dataset):\n    \n    def __init__(self, file_path, transform=None):\n        self.data = pd.read_csv(file_path)\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, index):\n        # load image as ndarray type (Height * Width * Channels)\n        # be carefull for converting dtype to np.uint8 [Unsigned integer (0 to 255)]\n        # in this example, we use ToTensor(), so we define the numpy array like (H, W, C)\n        image = self.data.iloc[index, 1:].values.astype(np.uint8).reshape((28, 28, 1))\n    \n        \n        if self.transform is not None:\n            image = self.transform(image)\n            \n        return image","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:42.220928Z","iopub.execute_input":"2024-01-17T11:58:42.221324Z","iopub.status.idle":"2024-01-17T11:58:42.231136Z","shell.execute_reply.started":"2024-01-17T11:58:42.221246Z","shell.execute_reply":"2024-01-17T11:58:42.230262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:42.234690Z","iopub.execute_input":"2024-01-17T11:58:42.234978Z","iopub.status.idle":"2024-01-17T11:58:42.244291Z","shell.execute_reply.started":"2024-01-17T11:58:42.234956Z","shell.execute_reply":"2024-01-17T11:58:42.243331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = TrainMNIST('/kaggle/input/Kannada-MNIST/train.csv', transform=transforms.ToTensor())\ntest_data = TestMNIST('/kaggle/input/Kannada-MNIST/test.csv', transform=transforms.ToTensor())","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:42.245421Z","iopub.execute_input":"2024-01-17T11:58:42.245701Z","iopub.status.idle":"2024-01-17T11:58:47.607473Z","shell.execute_reply.started":"2024-01-17T11:58:42.245678Z","shell.execute_reply":"2024-01-17T11:58:47.606577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Count samples\nnum_train_samples = len(train_data)\nnum_test_samples = len(test_data)\nprint('Number of samples in trainset:  ',num_train_samples)\nprint('Number of samples in trainset:  ',num_test_samples)# Count samples","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:47.608605Z","iopub.execute_input":"2024-01-17T11:58:47.608923Z","iopub.status.idle":"2024-01-17T11:58:47.615050Z","shell.execute_reply.started":"2024-01-17T11:58:47.608896Z","shell.execute_reply":"2024-01-17T11:58:47.613965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# number of subprocesses to use for data loading\nnum_workers = 0\n# how many samples per batch to load\nbatch_size = 64\n\n# convert data to torch.FloatTensor\n#transform = transforms.ToTensor()\n\n\n# prepare data loaders\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size,\n     num_workers=num_workers,)\ntest_loader = torch.utils.data.DataLoader(test_data, batch_size=batch_size, \n    num_workers=num_workers)","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:47.616550Z","iopub.execute_input":"2024-01-17T11:58:47.616937Z","iopub.status.idle":"2024-01-17T11:58:47.624260Z","shell.execute_reply.started":"2024-01-17T11:58:47.616904Z","shell.execute_reply":"2024-01-17T11:58:47.623222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\n    \n# obtain one batch of training images\ndataiter = iter(train_loader)\nimages, labels = next(dataiter)\nimages = images.numpy()\n\n# plot the images in the batch, along with the corresponding labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n    ax = fig.add_subplot(2, 10, idx+1, xticks=[], yticks=[])\n    ax.imshow(np.squeeze(images[idx]), cmap='gray')\n    # print out the correct label for each image\n    # .item() gets the value contained in a Tensor\n    ax.set_title(str(labels[idx].item()))","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:47.625524Z","iopub.execute_input":"2024-01-17T11:58:47.625861Z","iopub.status.idle":"2024-01-17T11:58:49.019977Z","shell.execute_reply.started":"2024-01-17T11:58:47.625835Z","shell.execute_reply":"2024-01-17T11:58:49.019017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.nn as nn\nimport torch.nn.functional as F\n\n# define the NN architecture\nclass Net(nn.Module):\n    def __init__(self):\n        super(Net, self).__init__()\n        # number of hidden nodes in each layer (512)\n        hidden_1 = 512\n        hidden_2 = 512\n        # linear layer (784 -> hidden_1)\n        self.fc1 = nn.Linear(28 * 28, hidden_1)\n        # linear layer (n_hidden -> hidden_2)\n        self.fc2 = nn.Linear(hidden_1, hidden_2)\n        # linear layer (n_hidden -> 10)\n        self.fc3 = nn.Linear(hidden_2, 10)\n\n\n    def forward(self, x):\n        # flatten image input\n        x = x.view(-1, 28 * 28)\n        # add hidden layer, with relu activation function\n        x = F.relu(self.fc1(x))\n        # add hidden layer, with relu activation function\n        x = F.relu(self.fc2(x))\n        # add output layer\n        x = self.fc3(x)\n        return x\n\n# initialize the NN\ndevice = torch.device(\"cuda\")\nmodel = Net().to(device)\nprint(model)","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:49.021279Z","iopub.execute_input":"2024-01-17T11:58:49.021591Z","iopub.status.idle":"2024-01-17T11:58:49.200623Z","shell.execute_reply.started":"2024-01-17T11:58:49.021565Z","shell.execute_reply":"2024-01-17T11:58:49.199656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\n# specify loss function (categorical cross-entropy)\ncriterion = nn.CrossEntropyLoss()\n\n# specify optimizer (stochastic gradient descent) and learning rate = 0.01\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:49.201811Z","iopub.execute_input":"2024-01-17T11:58:49.202119Z","iopub.status.idle":"2024-01-17T11:58:49.207298Z","shell.execute_reply.started":"2024-01-17T11:58:49.202095Z","shell.execute_reply":"2024-01-17T11:58:49.206340Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm import tqdm\n# number of epochs to train the model\nn_epochs = 16\n# initialize tracker for minimum validation loss\ntrain_loss_min = np.Inf # set initial \"min\" to infinity\nfor epoch in range(n_epochs):\n    # monitor training loss\n    train_loss = 0.0\n    \n    ###################\n    # train the model #\n    ###################\n    model.train() # prep model for training\n    for data, target in tqdm(train_loader):\n        # clear the gradients of all optimized variables\n        optimizer.zero_grad()\n        # move to GPU\n        data = data.to(device)\n        target = target.to(device)\n        # forward pass: compute predicted outputs by passing inputs to the model\n        output = model(data)\n        # calculate the loss\n        loss = criterion(output, target)\n        # backward pass: compute gradient of the loss with respect to model parameters\n        loss.backward()\n        # perform a single optimization step (parameter update)\n        optimizer.step()\n        # update running training loss\n        train_loss += loss.item()*data.size(0)\n        \n   \n    train_loss = train_loss/len(train_loader.dataset)\n    \n    print('Epoch: {} \\tTraining Loss: {:.6f}'.format(\n        epoch+1, \n        train_loss,\n        ))\n    \n    # save model if validation loss has decreased\n    if train_loss <= train_loss_min:\n        print('Training loss decreased ({:.6f} --> {:.6f}).  Saving model ...'.format(\n        train_loss_min,\n        train_loss))\n        torch.save(model.state_dict(), 'model.pt')\n        train_loss_min = train_loss","metadata":{"execution":{"iopub.status.busy":"2024-01-17T11:58:49.208457Z","iopub.execute_input":"2024-01-17T11:58:49.208737Z","iopub.status.idle":"2024-01-17T12:02:20.699263Z","shell.execute_reply.started":"2024-01-17T11:58:49.208708Z","shell.execute_reply":"2024-01-17T12:02:20.698336Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_state_dict(torch.load('model.pt'))","metadata":{"execution":{"iopub.status.busy":"2024-01-17T12:02:20.700550Z","iopub.execute_input":"2024-01-17T12:02:20.700864Z","iopub.status.idle":"2024-01-17T12:02:20.711373Z","shell.execute_reply.started":"2024-01-17T12:02:20.700838Z","shell.execute_reply":"2024-01-17T12:02:20.710318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# obtain one batch of test images\ndataiter = iter(test_loader)\nimages = next(dataiter)\nimages = images.to(device)\n\n# get sample outputs\noutput = model(images)\n# convert output probabilities to predicted class\n_, preds = torch.max(output, 1)\n# prep images for display\nimages = images.cpu().numpy()\n\n# plot the images in the batch, along with predicted and true labels\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(20):\n    ax = fig.add_subplot(2, 10, idx+1, xticks=[], yticks=[])\n    ax.imshow(np.squeeze(images[idx]), cmap='gray')\n    ax.set_title(\"{}\".format(str(preds[idx].item())))","metadata":{"execution":{"iopub.status.busy":"2024-01-17T12:02:20.715205Z","iopub.execute_input":"2024-01-17T12:02:20.715612Z","iopub.status.idle":"2024-01-17T12:02:21.946233Z","shell.execute_reply.started":"2024-01-17T12:02:20.715585Z","shell.execute_reply":"2024-01-17T12:02:21.945172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loader = torch.utils.data.DataLoader(test_data, batch_size=1, \n    num_workers=num_workers)","metadata":{"execution":{"iopub.status.busy":"2024-01-17T12:02:21.947547Z","iopub.execute_input":"2024-01-17T12:02:21.947926Z","iopub.status.idle":"2024-01-17T12:02:21.953346Z","shell.execute_reply.started":"2024-01-17T12:02:21.947893Z","shell.execute_reply":"2024-01-17T12:02:21.952294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict(model, dataloader):\n    prediction_list = []\n    for i, batch in enumerate(dataloader):\n        batch = batch.to(device)\n        outputs = model(batch)\n        _, predicted = torch.max(outputs.data, 1) \n        prediction_list.append(predicted.cpu())\n    return prediction_list","metadata":{"execution":{"iopub.status.busy":"2024-01-17T12:02:21.954558Z","iopub.execute_input":"2024-01-17T12:02:21.954902Z","iopub.status.idle":"2024-01-17T12:02:21.964083Z","shell.execute_reply.started":"2024-01-17T12:02:21.954875Z","shell.execute_reply":"2024-01-17T12:02:21.963068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = predict(model,test_loader)\npredictions = torch.cat(predictions, dim=0)\npredictions = predictions.cpu().numpy().astype(int)","metadata":{"execution":{"iopub.status.busy":"2024-01-17T12:02:21.965483Z","iopub.execute_input":"2024-01-17T12:02:21.965781Z","iopub.status.idle":"2024-01-17T12:02:24.946620Z","shell.execute_reply.started":"2024-01-17T12:02:21.965757Z","shell.execute_reply":"2024-01-17T12:02:24.945818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\n\n\nsubmission = pd.DataFrame(data={\n    \"id\": test_data.index,\n    \"label\": predictions\n})\nsubmission.to_csv(\"submission.csv\", index=None)","metadata":{"execution":{"iopub.status.busy":"2024-01-17T12:11:28.369474Z","iopub.execute_input":"2024-01-17T12:11:28.369864Z","iopub.status.idle":"2024-01-17T12:11:28.701330Z","shell.execute_reply.started":"2024-01-17T12:11:28.369835Z","shell.execute_reply":"2024-01-17T12:11:28.700460Z"},"trusted":true},"execution_count":null,"outputs":[]}]}