{"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":16017,"databundleVersionId":708189,"sourceType":"competition"}],"dockerImageVersionId":30786,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# 1. Importing library","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T01:59:52.495839Z","iopub.execute_input":"2024-11-24T01:59:52.496255Z","iopub.status.idle":"2024-11-24T01:59:57.999742Z","shell.execute_reply.started":"2024-11-24T01:59:52.496218Z","shell.execute_reply":"2024-11-24T01:59:57.998639Z"}},"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-11-24T01:59:58.001938Z","iopub.execute_input":"2024-11-24T01:59:58.002587Z","iopub.status.idle":"2024-11-24T01:59:58.010498Z","shell.execute_reply.started":"2024-11-24T01:59:58.002538Z","shell.execute_reply":"2024-11-24T01:59:58.009231Z"}},"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-11-24T01:59:58.011744Z","iopub.execute_input":"2024-11-24T01:59:58.012184Z","iopub.status.idle":"2024-11-24T01:59:58.025292Z","shell.execute_reply.started":"2024-11-24T01:59:58.012136Z","shell.execute_reply":"2024-11-24T01:59:58.024010Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3. Load and Visualise the data","metadata":{}},{"cell_type":"code","source":"train_data = TrainMNIST('../input/Kannada-MNIST/train.csv', transform=transforms.ToTensor())\ntest_data = TestMNIST('../input/Kannada-MNIST/test.csv', transform=transforms.ToTensor())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T01:59:58.028252Z","iopub.execute_input":"2024-11-24T01:59:58.028739Z","iopub.status.idle":"2024-11-24T02:00:03.058904Z","shell.execute_reply.started":"2024-11-24T01:59:58.028690Z","shell.execute_reply":"2024-11-24T02:00:03.057761Z"}},"outputs":[],"execution_count":null},{"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 = 20\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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T02:00:03.060262Z","iopub.execute_input":"2024-11-24T02:00:03.060732Z","iopub.status.idle":"2024-11-24T02:00:03.067136Z","shell.execute_reply.started":"2024-11-24T02:00:03.060674Z","shell.execute_reply":"2024-11-24T02:00:03.065971Z"}},"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, 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":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T02:00:03.068493Z","iopub.execute_input":"2024-11-24T02:00:03.068888Z","iopub.status.idle":"2024-11-24T02:00:04.152575Z","shell.execute_reply.started":"2024-11-24T02:00:03.068854Z","shell.execute_reply":"2024-11-24T02:00:04.151499Z"}},"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): # Khởi tạo kiến trúc của Neural Network\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): # Mô phỏng mô hình sử lý dữ liệu (forward propagation)\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\nmodel = Net()\nprint(model)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T02:00:04.154149Z","iopub.execute_input":"2024-11-24T02:00:04.154506Z","iopub.status.idle":"2024-11-24T02:00:04.173951Z","shell.execute_reply.started":"2024-11-24T02:00:04.154472Z","shell.execute_reply":"2024-11-24T02:00:04.172774Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Chọn Loss Function và Optimiser","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-11-24T02:00:04.175143Z","iopub.execute_input":"2024-11-24T02:00:04.175478Z","iopub.status.idle":"2024-11-24T02:00:04.185160Z","shell.execute_reply.started":"2024-11-24T02:00:04.175445Z","shell.execute_reply":"2024-11-24T02:00:04.183997Z"}},"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-11-24T02:00:04.186450Z","iopub.execute_input":"2024-11-24T02:00:04.186853Z","iopub.status.idle":"2024-11-24T02:06:09.191929Z","shell.execute_reply.started":"2024-11-24T02:00:04.186821Z","shell.execute_reply":"2024-11-24T02:06:09.190686Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 7. 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-11-24T02:06:09.195058Z","iopub.execute_input":"2024-11-24T02:06:09.195444Z","iopub.status.idle":"2024-11-24T02:06:09.207301Z","shell.execute_reply.started":"2024-11-24T02:06:09.195409Z","shell.execute_reply":"2024-11-24T02:06:09.206159Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 8. Test the trained network","metadata":{}},{"cell_type":"markdown","source":"## Visualise 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 probabilities 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, 10, 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-11-24T02:06:09.208602Z","iopub.execute_input":"2024-11-24T02:06:09.208950Z","iopub.status.idle":"2024-11-24T02:06:10.412759Z","shell.execute_reply.started":"2024-11-24T02:06:09.208915Z","shell.execute_reply":"2024-11-24T02:06:10.411372Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 8. 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, \n    num_workers=num_workers)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T02:06:10.414029Z","iopub.execute_input":"2024-11-24T02:06:10.414430Z","iopub.status.idle":"2024-11-24T02:06:10.421342Z","shell.execute_reply.started":"2024-11-24T02:06:10.414377Z","shell.execute_reply":"2024-11-24T02:06:10.419694Z"}},"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-11-24T02:06:10.422981Z","iopub.execute_input":"2024-11-24T02:06:10.423494Z","iopub.status.idle":"2024-11-24T02:06:10.439752Z","shell.execute_reply.started":"2024-11-24T02:06:10.423442Z","shell.execute_reply":"2024-11-24T02:06:10.438579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions = predict(model,test_loader)\n#predictions = np.array(predictions)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T02:06:10.441312Z","iopub.execute_input":"2024-11-24T02:06:10.441871Z","iopub.status.idle":"2024-11-24T02:06:13.379178Z","shell.execute_reply.started":"2024-11-24T02:06:10.441820Z","shell.execute_reply":"2024-11-24T02:06:13.377946Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"new_predictions = []\nfor p in predictions:\n     new_predictions.append(p.item())\npredictions = new_predictions","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-11-24T02:06:13.380761Z","iopub.execute_input":"2024-11-24T02:06:13.381123Z","iopub.status.idle":"2024-11-24T02:06:13.395710Z","shell.execute_reply.started":"2024-11-24T02:06:13.381088Z","shell.execute_reply":"2024-11-24T02:06:13.394345Z"}},"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-11-24T02:06:13.397800Z","iopub.execute_input":"2024-11-24T02:06:13.398144Z","iopub.status.idle":"2024-11-24T02:06:13.663673Z","shell.execute_reply.started":"2024-11-24T02:06:13.398111Z","shell.execute_reply":"2024-11-24T02:06:13.662634Z"}},"outputs":[],"execution_count":null}]}