{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","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":30732,"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":{"execution":{"iopub.status.busy":"2024-06-26T11:19:40.609523Z","iopub.execute_input":"2024-06-26T11:19:40.609962Z","iopub.status.idle":"2024-06-26T11:19:43.749871Z","shell.execute_reply.started":"2024-06-26T11:19:40.609920Z","shell.execute_reply":"2024-06-26T11:19:43.748681Z"},"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":{"execution":{"iopub.status.busy":"2024-06-26T11:19:43.751983Z","iopub.execute_input":"2024-06-26T11:19:43.752509Z","iopub.status.idle":"2024-06-26T11:19:43.760834Z","shell.execute_reply.started":"2024-06-26T11:19:43.752476Z","shell.execute_reply":"2024-06-26T11:19:43.759797Z"},"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        if self.transform is not None:\n            image = self.transform(image)\n            \n        return image","metadata":{"execution":{"iopub.status.busy":"2024-06-26T11:19:43.762361Z","iopub.execute_input":"2024-06-26T11:19:43.762683Z","iopub.status.idle":"2024-06-26T11:19:43.777347Z","shell.execute_reply.started":"2024-06-26T11:19:43.762656Z","shell.execute_reply":"2024-06-26T11:19:43.776178Z"},"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":{}},{"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-06-26T11:19:43.779433Z","iopub.execute_input":"2024-06-26T11:19:43.779759Z","iopub.status.idle":"2024-06-26T11:19:47.542739Z","shell.execute_reply.started":"2024-06-26T11:19:43.779731Z","shell.execute_reply":"2024-06-26T11:19:47.541678Z"},"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":{"execution":{"iopub.status.busy":"2024-06-26T11:19:47.543931Z","iopub.execute_input":"2024-06-26T11:19:47.544251Z","iopub.status.idle":"2024-06-26T11:19:47.552690Z","shell.execute_reply.started":"2024-06-26T11:19:47.544208Z","shell.execute_reply":"2024-06-26T11:19:47.551765Z"},"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) #dataiter.next()\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":{"execution":{"iopub.status.busy":"2024-06-26T11:19:47.553956Z","iopub.execute_input":"2024-06-26T11:19:47.554384Z","iopub.status.idle":"2024-06-26T11:19:48.662181Z","shell.execute_reply.started":"2024-06-26T11:19:47.554344Z","shell.execute_reply":"2024-06-26T11:19:48.661267Z"},"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":{}},{"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":{"execution":{"iopub.status.busy":"2024-06-26T11:19:48.663604Z","iopub.execute_input":"2024-06-26T11:19:48.664039Z","iopub.status.idle":"2024-06-26T11:19:48.681673Z","shell.execute_reply.started":"2024-06-26T11:19:48.663998Z","shell.execute_reply":"2024-06-26T11:19:48.680237Z"},"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":{}},{"cell_type":"code","source":"# specify loss function (categorical cross-entropy)\ncriterion = nn.CrossEntropyLoss()\n\n# specify optimizer (stochastic gradient descent) and learning rate = 0.001\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T11:19:48.683152Z","iopub.execute_input":"2024-06-26T11:19:48.683769Z","iopub.status.idle":"2024-06-26T11:19:48.689694Z","shell.execute_reply.started":"2024-06-26T11:19:48.683728Z","shell.execute_reply":"2024-06-26T11:19:48.688709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n### 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    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-06-26T11:19:48.690995Z","iopub.execute_input":"2024-06-26T11:19:48.691830Z","iopub.status.idle":"2024-06-26T11:32:17.597547Z","shell.execute_reply.started":"2024-06-26T11:19:48.691792Z","shell.execute_reply":"2024-06-26T11:32:17.596414Z"},"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-06-26T11:32:17.600580Z","iopub.execute_input":"2024-06-26T11:32:17.600930Z","iopub.status.idle":"2024-06-26T11:32:17.611287Z","shell.execute_reply.started":"2024-06-26T11:32:17.600899Z","shell.execute_reply":"2024-06-26T11:32:17.610297Z"},"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":{}},{"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":{}},{"cell_type":"code","source":"# obtain one batch of test images\ndataiter = iter(test_loader)\nimages = next(dataiter) #dataiter.next()\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":{"execution":{"iopub.status.busy":"2024-06-26T11:32:17.612634Z","iopub.execute_input":"2024-06-26T11:32:17.613124Z","iopub.status.idle":"2024-06-26T11:32:18.851484Z","shell.execute_reply.started":"2024-06-26T11:32:17.613084Z","shell.execute_reply":"2024-06-26T11:32:18.850185Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T11:32:18.852902Z","iopub.execute_input":"2024-06-26T11:32:18.853291Z","iopub.status.idle":"2024-06-26T11:32:18.858171Z","shell.execute_reply.started":"2024-06-26T11:32:18.853257Z","shell.execute_reply":"2024-06-26T11:32:18.857157Z"},"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        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-06-26T11:32:18.859435Z","iopub.execute_input":"2024-06-26T11:32:18.859764Z","iopub.status.idle":"2024-06-26T11:32:18.871592Z","shell.execute_reply.started":"2024-06-26T11:32:18.859734Z","shell.execute_reply":"2024-06-26T11:32:18.870567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = predict(model,test_loader)\n#predictions = np.array(predictions)\n# Ensure consistent shapes\n#consistent_predictions = [tensor.numpy() for tensor in predictions]\n\n# Convert to NumPy array\n#predictions_array = np.array(consistent_predictions)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T11:32:18.872888Z","iopub.execute_input":"2024-06-26T11:32:18.873297Z","iopub.status.idle":"2024-06-26T11:32:21.389345Z","shell.execute_reply.started":"2024-06-26T11:32:18.873252Z","shell.execute_reply":"2024-06-26T11:32:21.388458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\n\n# Flatten the predictions array to make it 1-dimensional\n#predictions = predictions.flatten()\n\nsubmission = pd.DataFrame(data={\n    \"id\": test_data.index,\n    \"label\": np.array(predictions).reshape(-1)#predictions_array[:, 0]\n})\nsubmission.to_csv(\"submission.csv\", index=None)","metadata":{"execution":{"iopub.status.busy":"2024-06-26T11:32:21.390475Z","iopub.execute_input":"2024-06-26T11:32:21.391630Z","iopub.status.idle":"2024-06-26T11:32:21.697394Z","shell.execute_reply.started":"2024-06-26T11:32:21.391597Z","shell.execute_reply":"2024-06-26T11:32:21.696305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission","metadata":{"execution":{"iopub.status.busy":"2024-06-26T11:32:21.698621Z","iopub.execute_input":"2024-06-26T11:32:21.698961Z","iopub.status.idle":"2024-06-26T11:32:21.721107Z","shell.execute_reply.started":"2024-06-26T11:32:21.698930Z","shell.execute_reply":"2024-06-26T11:32:21.720260Z"},"trusted":true},"execution_count":null,"outputs":[]}]}