{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Ex 2: Train a MLP to classify MNIST FASHIONS\n\n\n### Yêu cầu: tạo 1 mô hình Perceptron để classify tập MNIST Fashion\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":"2023-10-03T00:16:08.703030Z","iopub.execute_input":"2023-10-03T00:16:08.703750Z","iopub.status.idle":"2023-10-03T00:16:14.080115Z","shell.execute_reply.started":"2023-10-03T00:16:08.703715Z","shell.execute_reply":"2023-10-03T00:16:14.079104Z"},"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":"2023-10-03T00:16:14.081690Z","iopub.execute_input":"2023-10-03T00:16:14.082351Z","iopub.status.idle":"2023-10-03T00:16:14.089288Z","shell.execute_reply.started":"2023-10-03T00:16:14.082319Z","shell.execute_reply":"2023-10-03T00:16:14.088466Z"},"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":"2023-10-03T00:16:14.090749Z","iopub.execute_input":"2023-10-03T00:16:14.091357Z","iopub.status.idle":"2023-10-03T00:16:14.102903Z","shell.execute_reply.started":"2023-10-03T00:16:14.091326Z","shell.execute_reply":"2023-10-03T00:16:14.101916Z"},"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('/kaggle/input/Kannada-MNIST/train.csv', transform=transforms.ToTensor())\ntest_data = TestMNIST('/kaggle/input/Kannada-MNIST/test.csv', transform=transforms.ToTensor())","metadata":{"_uuid":"9fcbee0f621939a82823b2842e1cf969c6ae35dd","execution":{"iopub.status.busy":"2023-10-03T00:16:14.105690Z","iopub.execute_input":"2023-10-03T00:16:14.106363Z","iopub.status.idle":"2023-10-03T00:16:18.201250Z","shell.execute_reply.started":"2023-10-03T00:16:14.106333Z","shell.execute_reply":"2023-10-03T00:16:18.200305Z"},"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 = 32\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":"2023-10-03T00:16:18.202484Z","iopub.execute_input":"2023-10-03T00:16:18.203038Z","iopub.status.idle":"2023-10-03T00:16:18.209154Z","shell.execute_reply.started":"2023-10-03T00:16:18.203005Z","shell.execute_reply":"2023-10-03T00:16:18.208307Z"},"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, 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":{"execution":{"iopub.status.busy":"2023-10-03T00:16:18.210575Z","iopub.execute_input":"2023-10-03T00:16:18.211341Z","iopub.status.idle":"2023-10-03T00:16:19.274844Z","shell.execute_reply.started":"2023-10-03T00:16:18.211310Z","shell.execute_reply":"2023-10-03T00:16:19.273982Z"},"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        hidden_3 = 512\n        hidden_4 = 512\n        # linear layer (784 -> hidden_1)\n        \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_hidden2 -> hidden_3)\n        self.fc3 = nn.Linear(hidden_2, hidden_3)\n        # linear layer (n_hidden3 -> hidden_4)\n        self.fc4 = nn.Linear(hidden_3, hidden_4)\n        # linear layer (n_hidden -> 10)\n        self.fc5 = nn.Linear(hidden_4, 10)\n\n\n    def forward(self, x):\n        # flatten image input\n        x = x.view(-1, 28 * 28)\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = F.relu(self.fc3(x))\n        x = F.relu(self.fc4(x))\n        x = self.fc5(x)\n        return x\n\n# initialize the NN\nmodel = Net()\nprint(model)","metadata":{"_uuid":"7b62834c92649b8c4578b2a382245ae1d1ac39af","execution":{"iopub.status.busy":"2023-10-03T00:16:19.276049Z","iopub.execute_input":"2023-10-03T00:16:19.276947Z","iopub.status.idle":"2023-10-03T00:16:19.298504Z","shell.execute_reply.started":"2023-10-03T00:16:19.276914Z","shell.execute_reply":"2023-10-03T00:16:19.297396Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model(torch.zeros((20,28,28,1)))","metadata":{"execution":{"iopub.status.busy":"2023-10-03T00:16:19.299796Z","iopub.execute_input":"2023-10-03T00:16:19.300320Z","iopub.status.idle":"2023-10-03T00:16:19.380841Z","shell.execute_reply.started":"2023-10-03T00:16:19.300291Z","shell.execute_reply":"2023-10-03T00:16:19.379948Z"},"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":"2023-10-03T00:16:19.381963Z","iopub.execute_input":"2023-10-03T00:16:19.382757Z","iopub.status.idle":"2023-10-03T00:16:19.387481Z","shell.execute_reply.started":"2023-10-03T00:16:19.382726Z","shell.execute_reply":"2023-10-03T00:16:19.386663Z"},"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":"2023-10-03T00:16:19.390984Z","iopub.execute_input":"2023-10-03T00:16:19.391221Z"},"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"---\n## Test the Trained Network\n","metadata":{"_uuid":"7df21ab196469532fc5c2b1a0103c41b669a79a6"}},{"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","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().item())\n    return prediction_list","metadata":{"_uuid":"f8fdf66ab03e98f9b1b6295d76e0cd29004bd5c9","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = predict(model,test_loader)\npredictions = np.array(predictions)","metadata":{"_uuid":"1ee21bfa8bfd26d300557560318e8c8b602d9612","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = pd.read_csv(\"/kaggle/input/Kannada-MNIST/test.csv\")\n\n\nsubmission = pd.DataFrame(data={\n    \"id\": test_data.index,\n    \"label\": predictions\n})\nsubmission.to_csv(\"submission.csv\", index=None)","metadata":{"_uuid":"72d92030cd2804203698185ef5cf6d5984349bdb","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Kết quả thực tế trên Kaggle: Accuracy ~ 94%","metadata":{}},{"cell_type":"code","source":"submission","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}