{"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":"none","dataSources":[{"sourceId":16017,"databundleVersionId":708189,"sourceType":"competition"}],"isInternetEnabled":false,"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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","trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:08:31.224144Z","iopub.execute_input":"2024-12-20T15:08:31.224452Z","iopub.status.idle":"2024-12-20T15:08:31.229269Z","shell.execute_reply.started":"2024-12-20T15:08:31.224426Z","shell.execute_reply":"2024-12-20T15:08:31.228167Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"1. Importing library","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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:08:36.017722Z","iopub.execute_input":"2024-12-20T15:08:36.018041Z","iopub.status.idle":"2024-12-20T15:08:41.484387Z","shell.execute_reply.started":"2024-12-20T15:08:36.018019Z","shell.execute_reply":"2024-12-20T15:08:41.483340Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"2. Define Custom dataset class","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:08:44.135785Z","iopub.execute_input":"2024-12-20T15:08:44.136342Z","iopub.status.idle":"2024-12-20T15:08:44.143202Z","shell.execute_reply.started":"2024-12-20T15:08:44.136309Z","shell.execute_reply":"2024-12-20T15:08:44.141941Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:08:46.346899Z","iopub.execute_input":"2024-12-20T15:08:46.347306Z","iopub.status.idle":"2024-12-20T15:08:46.353365Z","shell.execute_reply.started":"2024-12-20T15:08:46.347276Z","shell.execute_reply":"2024-12-20T15:08:46.352241Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:08:49.658105Z","iopub.execute_input":"2024-12-20T15:08:49.658479Z","iopub.status.idle":"2024-12-20T15:08:54.917702Z","shell.execute_reply.started":"2024-12-20T15:08:49.658450Z","shell.execute_reply":"2024-12-20T15:08:54.916515Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# number of subprogress to use for data loading\nnum_workers = 0\n\n# how many samples per batch to load\nbatch_size = 20\n\n# covert data to torch.FloatTensor\n# transform = transform.ToTensor()\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:08:57.196244Z","iopub.execute_input":"2024-12-20T15:08:57.196705Z","iopub.status.idle":"2024-12-20T15:08:57.202063Z","shell.execute_reply.started":"2024-12-20T15:08:57.196673Z","shell.execute_reply":"2024-12-20T15:08:57.200822Z"}},"outputs":[],"execution_count":null},{"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, int(20/2), idx+1, xticks=[], yticks=[])\n    ax.imshow(np.squeeze(images[idx]), cmap='gray')\n    # print out the correct label for each image\n    # .item() get the value contained in a Tensor\n    ax.set_title(str(labels[idx].item()))","metadata":{"execution":{"iopub.status.busy":"2024-12-20T15:08:59.836434Z","iopub.execute_input":"2024-12-20T15:08:59.836767Z","iopub.status.idle":"2024-12-20T15:09:00.902931Z","shell.execute_reply.started":"2024-12-20T15:08:59.836741Z","shell.execute_reply":"2024-12-20T15:09:00.901853Z"},"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"4 Thiết kế 1 mạng NN đơn giản Architecture","metadata":{}},{"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    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.logsigmoid(self.fc1(x))\n        # add hidden layer, with relu activation function\n        x = F.logsigmoid(self.fc2(x))\n        # add output layer\n        x = self.fc3(x)\n        return x\n\n# initialize the NN\nmodel = Net()\nprint(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:09:03.333579Z","iopub.execute_input":"2024-12-20T15:09:03.333970Z","iopub.status.idle":"2024-12-20T15:09:03.350645Z","shell.execute_reply.started":"2024-12-20T15:09:03.333938Z","shell.execute_reply":"2024-12-20T15:09:03.349580Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"5. Chọn Loss Function và Optimizer","metadata":{}},{"cell_type":"code","source":"# specify loss function (categorical cross-entropy)\ncriterion = nn.CrossEntropyLoss()\n\n# specify optimizer (stochastic gradient descent) and learning rate = 0.01\noptimizer = torch.optim.SGD(model.parameters(), lr=0.01)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:09:07.781441Z","iopub.execute_input":"2024-12-20T15:09:07.781798Z","iopub.status.idle":"2024-12-20T15:09:07.786477Z","shell.execute_reply.started":"2024-12-20T15:09:07.781769Z","shell.execute_reply":"2024-12-20T15:09:07.785225Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"6. Train the Network","metadata":{}},{"cell_type":"code","source":"# number of epochs to train the model\nn_epochs = 20\n\n# initialize tracker for minimum validation loss\ntrain_loss_min = np.Inf # set initial \"min\" to infinity\n\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 train_loader:\n        # clear the gradients of all optimized variables\n        optimizer.zero_grad()\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:09:10.467757Z","iopub.execute_input":"2024-12-20T15:09:10.468142Z","iopub.status.idle":"2024-12-20T15:15:36.406193Z","shell.execute_reply.started":"2024-12-20T15:09:10.468095Z","shell.execute_reply":"2024-12-20T15:15:36.405199Z"}},"outputs":[],"execution_count":null},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:16:28.215387Z","iopub.execute_input":"2024-12-20T15:16:28.215749Z","iopub.status.idle":"2024-12-20T15:16:28.226979Z","shell.execute_reply.started":"2024-12-20T15:16:28.215722Z","shell.execute_reply":"2024-12-20T15:16:28.225875Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#### Test the Trained Network","metadata":{}},{"cell_type":"markdown","source":"#### Visualize Sample Test Results","metadata":{}},{"cell_type":"code","source":"# obtain one batch of test images\ndataiter = iter(test_loader)\nimages = next(dataiter)\n\n# get sample outputs\noutput = model(images)\n# convert output probabilites to predicted class\n_, preds = torch.max(output, 1)\n# prep images for display\nimages = images.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, int(20/2), idx+1, xticks=[], yticks=[])\n    ax.imshow(np.squeeze(images[idx]), cmap='gray')\n    ax.set_title(\"{}\".format(str(preds[idx].item())))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:16:37.893881Z","iopub.execute_input":"2024-12-20T15:16:37.894277Z","iopub.status.idle":"2024-12-20T15:16:38.919701Z","shell.execute_reply.started":"2024-12-20T15:16:37.894246Z","shell.execute_reply":"2024-12-20T15:16:38.918388Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"7. Predict digit dựa vào input >> Tạo file submission trong kaggle","metadata":{}},{"cell_type":"code","source":"test_loader = torch.utils.data.DataLoader(test_data, batch_size=1, num_workers=num_workers)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:16:43.014439Z","iopub.execute_input":"2024-12-20T15:16:43.014781Z","iopub.status.idle":"2024-12-20T15:16:43.019425Z","shell.execute_reply.started":"2024-12-20T15:16:43.014756Z","shell.execute_reply":"2024-12-20T15:16:43.018249Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def 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","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:16:43.601380Z","iopub.execute_input":"2024-12-20T15:16:43.601733Z","iopub.status.idle":"2024-12-20T15:16:43.607032Z","shell.execute_reply.started":"2024-12-20T15:16:43.601702Z","shell.execute_reply":"2024-12-20T15:16:43.605840Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions = predict(model, test_loader)\npredictions = np.array(predictions).flatten()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:16:46.586320Z","iopub.execute_input":"2024-12-20T15:16:46.586685Z","iopub.status.idle":"2024-12-20T15:16:49.729599Z","shell.execute_reply.started":"2024-12-20T15:16:46.586654Z","shell.execute_reply":"2024-12-20T15:16:49.728485Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_data = pd.read_csv('/kaggle/input/Kannada-MNIST/test.csv')\n\nsubmission = pd.DataFrame(data={\n    \"id\": test_data.index,\n    \"label\": predictions\n})\nsubmission.to_csv(\"submission.csv\", index=None)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-20T15:16:49.731870Z","iopub.execute_input":"2024-12-20T15:16:49.732194Z","iopub.status.idle":"2024-12-20T15:16:49.998712Z","shell.execute_reply.started":"2024-12-20T15:16:49.732166Z","shell.execute_reply":"2024-12-20T15:16:49.997760Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}