{"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":30636,"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-13T04:38:11.039731Z","iopub.execute_input":"2024-01-13T04:38:11.040007Z","iopub.status.idle":"2024-01-13T04:38:11.933295Z","shell.execute_reply.started":"2024-01-13T04:38:11.039980Z","shell.execute_reply":"2024-01-13T04:38:11.932251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. Import libraries","metadata":{}},{"cell_type":"code","source":"import 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-13T04:38:11.936910Z","iopub.execute_input":"2024-01-13T04:38:11.937333Z","iopub.status.idle":"2024-01-13T04:38:15.454843Z","shell.execute_reply.started":"2024-01-13T04:38:11.937306Z","shell.execute_reply":"2024-01-13T04:38:15.453894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Define custom dataset class","metadata":{}},{"cell_type":"code","source":"class TrainMNIST(Dataset):\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        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\n\n\nclass TestMNIST(Dataset):\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        image = self.data.iloc[index, 1:].values.astype(np.uint8).reshape((28,28,1))\n        \n        if self.transform is not None:\n            image = self.transform(image)\n    \n        return image","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:38:15.456031Z","iopub.execute_input":"2024-01-13T04:38:15.456434Z","iopub.status.idle":"2024-01-13T04:38:15.465651Z","shell.execute_reply.started":"2024-01-13T04:38:15.456407Z","shell.execute_reply":"2024-01-13T04:38:15.464795Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 3. Load and Visualize the data","metadata":{}},{"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-13T04:38:15.469588Z","iopub.execute_input":"2024-01-13T04:38:15.470317Z","iopub.status.idle":"2024-01-13T04:38:20.322544Z","shell.execute_reply.started":"2024-01-13T04:38:15.470291Z","shell.execute_reply":"2024-01-13T04:38:20.321279Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:38:20.323987Z","iopub.execute_input":"2024-01-13T04:38:20.324568Z","iopub.status.idle":"2024-01-13T04:38:20.334569Z","shell.execute_reply.started":"2024-01-13T04:38:20.324527Z","shell.execute_reply":"2024-01-13T04:38:20.330648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_workers = 0\nbatch_size = 20\n\ntrain_loader = torch.utils.data.DataLoader(train_data, batch_size = batch_size, \n                                           num_workers = num_workers)\n# test_loader = torch.utils.data.DataLoader(test_data, batch_size = batch_size,\n#                                          num_workers = num_workers)  \n# test_loader này chỉ để dùng visualize test.csv nếu muốn, chứ không dùng để predict. Predict thì batch_size=1.","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:38:20.335784Z","iopub.execute_input":"2024-01-13T04:38:20.336121Z","iopub.status.idle":"2024-01-13T04:38:20.351695Z","shell.execute_reply.started":"2024-01-13T04:38:20.336085Z","shell.execute_reply":"2024-01-13T04:38:20.350513Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"## Visualize train.csv\nimport 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, int(20/2), idx+1, xticks=[], yticks=[])\n    ax.imshow(np.squeeze(images[idx]), cmap = 'gray')\n    ax.set_title(str(labels[idx].item()))","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:38:20.353439Z","iopub.execute_input":"2024-01-13T04:38:20.353816Z","iopub.status.idle":"2024-01-13T04:38:21.653330Z","shell.execute_reply.started":"2024-01-13T04:38:20.353780Z","shell.execute_reply":"2024-01-13T04:38:21.652394Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 4. Build a simple Neural Network","metadata":{}},{"cell_type":"code","source":"import torch.nn as nn\nimport torch.nn.functional as F\n\nclass Net(nn.Module):\n    def __init__(self):\n        super(Net, self).__init__()\n        hidden_1 = 512\n        hidden_2 = 512\n        self.fc1 = nn.Linear(28*28, hidden_1)\n        self.fc2 = nn.Linear(hidden_1, hidden_2)\n        self.fc3 = nn.Linear(hidden_2, 10)\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        x = F.relu(self.fc2(x))\n        x = self.fc3(x)\n        return x\n    \nmodel = Net()\nprint(model)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:38:21.654664Z","iopub.execute_input":"2024-01-13T04:38:21.655059Z","iopub.status.idle":"2024-01-13T04:38:21.670540Z","shell.execute_reply.started":"2024-01-13T04:38:21.655024Z","shell.execute_reply":"2024-01-13T04:38:21.669691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 5. Loss Function and Optimizer","metadata":{}},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:38:21.671799Z","iopub.execute_input":"2024-01-13T04:38:21.672316Z","iopub.status.idle":"2024-01-13T04:38:21.677137Z","shell.execute_reply.started":"2024-01-13T04:38:21.672278Z","shell.execute_reply":"2024-01-13T04:38:21.676210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 6. Train the network","metadata":{}},{"cell_type":"code","source":"n_epochs = 32\ntrain_loss_min = np.Inf\n\nfor epoch in range(n_epochs):\n    train_loss = 0.0\n    model.train()\n    for data, target in train_loader:\n        optimizer.zero_grad()   # clear the gradients of all optimized variables\n        output = model(data)\n        loss = criterion(output, target)\n        loss.backward()\n        optimizer.step()   # perform a single optimization step (parameter update)\n        train_loss += loss.item()*data.size(0)\n        \n    train_loss = train_loss/len(train_loader.dataset)\n    print('Epoch: {} \\t Training loss {:.6f}'.format(epoch+1, train_loss))\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(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-13T04:38:21.680352Z","iopub.execute_input":"2024-01-13T04:38:21.680652Z","iopub.status.idle":"2024-01-13T04:47:46.630238Z","shell.execute_reply.started":"2024-01-13T04:38:21.680618Z","shell.execute_reply":"2024-01-13T04:47:46.629300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Load the model with the lowest validation loss","metadata":{}},{"cell_type":"code","source":"model.load_state_dict(torch.load('model.pt'))","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:47:46.631676Z","iopub.execute_input":"2024-01-13T04:47:46.632227Z","iopub.status.idle":"2024-01-13T04:47:46.640794Z","shell.execute_reply.started":"2024-01-13T04:47:46.632197Z","shell.execute_reply":"2024-01-13T04:47:46.639823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 7. Predict Kannada digit based on input","metadata":{}},{"cell_type":"code","source":"test_loader = torch.utils.data.DataLoader(test_data, batch_size=1,num_workers=num_workers)\n\n\ndef predict(model, dataloader):\n    prediction_list = []\n    for i, batch in enumerate(dataloader):\n        outputs = model(batch)\n        _, predicted = torch.max(outputs.data, 1) \n        prediction_list.append(predicted.cpu())\n    return prediction_list\n\n\npredictions = predict(model,test_loader)\n# predictions = np.array(predictions)  # error: The requested array has an inhomogeneous shape after 1 dimensions.\noutput = []\nfor i in predictions:\n    output.append(i.item())\noutput = np.array(output)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:47:46.642183Z","iopub.execute_input":"2024-01-13T04:47:46.642612Z","iopub.status.idle":"2024-01-13T04:47:49.595936Z","shell.execute_reply.started":"2024-01-13T04:47:46.642578Z","shell.execute_reply":"2024-01-13T04:47:49.595139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 8. Create file submission on kaggle","metadata":{}},{"cell_type":"code","source":"test_df = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\n\nsubmission = pd.DataFrame(data={\n    \"id\": test_df['id'],\n    \"label\": output\n})\nsubmission.to_csv(\"submission.csv\", index=None)","metadata":{"execution":{"iopub.status.busy":"2024-01-13T04:47:49.597382Z","iopub.execute_input":"2024-01-13T04:47:49.597735Z","iopub.status.idle":"2024-01-13T04:47:49.900685Z","shell.execute_reply.started":"2024-01-13T04:47:49.597704Z","shell.execute_reply":"2024-01-13T04:47:49.899928Z"},"trusted":true},"execution_count":null,"outputs":[]}]}