{"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","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":"nvidiaTeslaT4","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":"markdown","source":"# Example 1: Train a multi layer Perceptron to classify MNIST digits\n---\nDataset information: [MNIST database](http://yann.lecun.com/exdb/mnist/) hand-written digit database.\n\n","metadata":{"_uuid":"ad6d2291cd71417d9df4ae3525021ca4f00b0033"}},{"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":{"_uuid":"b10febf7b1e1774132e7eb5d976678cdde13f98c","execution":{"iopub.status.busy":"2024-01-16T14:39:36.583513Z","iopub.execute_input":"2024-01-16T14:39:36.584120Z","iopub.status.idle":"2024-01-16T14:39:36.592173Z","shell.execute_reply.started":"2024-01-16T14:39:36.584076Z","shell.execute_reply":"2024-01-16T14:39:36.590670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 2. Define Custom dataset class","metadata":{}},{"cell_type":"markdown","source":"Nguyên tắc: 1 custom dataset class bao gồm cũng có 3 methods:\n\n1. __getitem__ : trả về data (và/hoặc label) khi biết số index\n2. __len__ : trả về số mẫu trong dataset\n3. __init__: thực hiện các thao tác trong khi khởi tạo 1 object dataset","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":{"_uuid":"584462e29167042d6ab91465abf29682a19ca7b9","execution":{"iopub.status.busy":"2024-01-16T14:39:36.594816Z","iopub.execute_input":"2024-01-16T14:39:36.595895Z","iopub.status.idle":"2024-01-16T14:39:36.611244Z","shell.execute_reply.started":"2024-01-16T14:39:36.595853Z","shell.execute_reply":"2024-01-16T14:39:36.610188Z"},"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":{"_uuid":"cc2462c5b61c2ce5e36ab979fbd06a67b2e76906","execution":{"iopub.status.busy":"2024-01-16T14:39:36.612753Z","iopub.execute_input":"2024-01-16T14:39:36.613437Z","iopub.status.idle":"2024-01-16T14:39:36.624114Z","shell.execute_reply.started":"2024-01-16T14:39:36.613367Z","shell.execute_reply":"2024-01-16T14:39:36.622902Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n### 3. Load and Visualize the [Data](http://pytorch.org/docs/stable/torchvision/datasets.html)\n\nThử dùng 2 class dataset cho 2 tập test và train ở trên để visualize data","metadata":{"_uuid":"7645b3c96629001448adfd2ed86b10c7c849bc79"}},{"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":{"_uuid":"9fcbee0f621939a82823b2842e1cf969c6ae35dd","execution":{"iopub.status.busy":"2024-01-16T14:39:36.626711Z","iopub.execute_input":"2024-01-16T14:39:36.627080Z","iopub.status.idle":"2024-01-16T14:39:40.751370Z","shell.execute_reply.started":"2024-01-16T14:39:36.627045Z","shell.execute_reply":"2024-01-16T14:39:40.750275Z"},"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 = 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":{"_uuid":"09a9b606cbcc82b3d2e42f95788354c147f060f0","execution":{"iopub.status.busy":"2024-01-16T14:39:40.752843Z","iopub.execute_input":"2024-01-16T14:39:40.753260Z","iopub.status.idle":"2024-01-16T14:39:40.760749Z","shell.execute_reply.started":"2024-01-16T14:39:40.753221Z","shell.execute_reply":"2024-01-16T14:39:40.759708Z"},"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, 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() gets the value contained in a Tensor\n    ax.set_title(str(labels[idx].item()))","metadata":{"_uuid":"4221b1b8f71ef7edb36c286c10c10150e8da866f","execution":{"iopub.status.busy":"2024-01-16T14:39:40.762343Z","iopub.execute_input":"2024-01-16T14:39:40.762876Z","iopub.status.idle":"2024-01-16T14:39:41.929866Z","shell.execute_reply.started":"2024-01-16T14:39:40.762844Z","shell.execute_reply":"2024-01-16T14:39:41.928844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n### 4. Thiết kế 1 mạng NN đơn giản [Architecture](http://pytorch.org/docs/stable/nn.html)\n\nThiết kế 1 mạng neural network đơn giản cho việc phân loại","metadata":{"_uuid":"5a64b7de7835b6171b01542ac5282aa1fb5bdc67"}},{"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\nmodel = Net()\nprint(model)","metadata":{"_uuid":"7b62834c92649b8c4578b2a382245ae1d1ac39af","execution":{"iopub.status.busy":"2024-01-16T14:39:41.932473Z","iopub.execute_input":"2024-01-16T14:39:41.932782Z","iopub.status.idle":"2024-01-16T14:39:41.947003Z","shell.execute_reply.started":"2024-01-16T14:39:41.932755Z","shell.execute_reply":"2024-01-16T14:39:41.946055Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###  5. Chọn [Loss Function](http://pytorch.org/docs/stable/nn.html#loss-functions) và [Optimizer](http://pytorch.org/docs/stable/optim.html)\n\n","metadata":{"_uuid":"869671841b5922527a521fb98c81cf567265b6b4"}},{"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":{"_uuid":"3fc4df3f886fa7677d9523ddd4f8202646eba2ee","execution":{"iopub.status.busy":"2024-01-16T14:39:41.948236Z","iopub.execute_input":"2024-01-16T14:39:41.948568Z","iopub.status.idle":"2024-01-16T14:39:41.956356Z","shell.execute_reply.started":"2024-01-16T14:39:41.948539Z","shell.execute_reply":"2024-01-16T14:39:41.955531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n### 6. Train the Network\n","metadata":{"_uuid":"acd559ded95cc6ac73d1256efb18640ab12a282d"}},{"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":{"_uuid":"108ed27f4199c4ecb086dd1b32d9c2e9f795eb98","execution":{"iopub.status.busy":"2024-01-16T14:39:41.957743Z","iopub.execute_input":"2024-01-16T14:39:41.958141Z","iopub.status.idle":"2024-01-16T14:46:03.144259Z","shell.execute_reply.started":"2024-01-16T14:39:41.958109Z","shell.execute_reply":"2024-01-16T14:46:03.143212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"###  Load the Model with the Lowest Validation Loss","metadata":{"_uuid":"5739526c3eceba40018641fa9138832a87815133"}},{"cell_type":"code","source":"model.load_state_dict(torch.load('model.pt'))","metadata":{"_uuid":"5df15b169108c21d69fe157611ed770e369a60e4","execution":{"iopub.status.busy":"2024-01-16T14:46:03.146015Z","iopub.execute_input":"2024-01-16T14:46:03.146415Z","iopub.status.idle":"2024-01-16T14:46:03.156770Z","shell.execute_reply.started":"2024-01-16T14:46:03.146363Z","shell.execute_reply":"2024-01-16T14:46:03.155374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n## Test the Trained Network\n\nFinally, we test our best model on previously unseen **test data** and evaluate it's performance. Testing on unseen data is a good way to check that our model generalizes well. It may also be useful to be granular in this analysis and take a look at how this model performs on each class as well as looking at its overall loss and accuracy.","metadata":{"_uuid":"7df21ab196469532fc5c2b1a0103c41b669a79a6"}},{"cell_type":"markdown","source":"### Visualize Sample Test Results\n\nThis cell displays test images and their labels in this format: `predicted (ground-truth)`. The text will be green for accurately classified examples and red for incorrect predictions.","metadata":{"_uuid":"d3b265b4f80ff8b14341ac02cafbcc9d733952ba"}},{"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, 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":{"_uuid":"051970cff13e735d6ba16b1a16b1cf6b986ae137","execution":{"iopub.status.busy":"2024-01-16T14:46:03.158576Z","iopub.execute_input":"2024-01-16T14:46:03.159176Z","iopub.status.idle":"2024-01-16T14:46:04.500300Z","shell.execute_reply.started":"2024-01-16T14:46:03.159140Z","shell.execute_reply":"2024-01-16T14:46:04.499214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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, \n    num_workers=num_workers)\n","metadata":{"_uuid":"6fca0360024d210720b333484050f86cc68a7001","execution":{"iopub.status.busy":"2024-01-16T14:46:04.501801Z","iopub.execute_input":"2024-01-16T14:46:04.502213Z","iopub.status.idle":"2024-01-16T14:46:04.507632Z","shell.execute_reply.started":"2024-01-16T14:46:04.502170Z","shell.execute_reply":"2024-01-16T14:46:04.506468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\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","metadata":{"_uuid":"f8fdf66ab03e98f9b1b6295d76e0cd29004bd5c9","execution":{"iopub.status.busy":"2024-01-16T14:46:04.509073Z","iopub.execute_input":"2024-01-16T14:46:04.509666Z","iopub.status.idle":"2024-01-16T14:46:04.519542Z","shell.execute_reply.started":"2024-01-16T14:46:04.509631Z","shell.execute_reply":"2024-01-16T14:46:04.518377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Obtain predictions\npredictions = predict(model, test_loader)\n\n# Ensure consistent shapes\nconsistent_predictions = [tensor.numpy() for tensor in predictions]\n\n# Convert to NumPy array\npredictions_array = np.array(consistent_predictions)","metadata":{"execution":{"iopub.status.busy":"2024-01-16T14:46:04.520764Z","iopub.execute_input":"2024-01-16T14:46:04.521053Z","iopub.status.idle":"2024-01-16T14:46:07.798754Z","shell.execute_reply.started":"2024-01-16T14:46:04.521013Z","shell.execute_reply":"2024-01-16T14:46:07.797896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# predictions_array = predict(model,test_loader)\n# predictions = np.array(predictions)","metadata":{"_uuid":"1ee21bfa8bfd26d300557560318e8c8b602d9612","execution":{"iopub.status.busy":"2024-01-16T14:46:07.802041Z","iopub.execute_input":"2024-01-16T14:46:07.802324Z","iopub.status.idle":"2024-01-16T14:46:07.806571Z","shell.execute_reply.started":"2024-01-16T14:46:07.802300Z","shell.execute_reply":"2024-01-16T14:46:07.805544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\n\n\nsubmission = pd.DataFrame(data={\n    \"id\": test_data.index,\n    \"label\": predictions_array[:, 0]\n})\nsubmission.to_csv(\"submission.csv\", index=None)","metadata":{"_uuid":"72d92030cd2804203698185ef5cf6d5984349bdb","execution":{"iopub.status.busy":"2024-01-16T14:46:07.807959Z","iopub.execute_input":"2024-01-16T14:46:07.808314Z","iopub.status.idle":"2024-01-16T14:46:08.151531Z","shell.execute_reply.started":"2024-01-16T14:46:07.808282Z","shell.execute_reply":"2024-01-16T14:46:08.150687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"_uuid":"c3c6d900b9d75615e3f09ba3643965c44537b5f9"},"execution_count":null,"outputs":[]}]}