{"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":"gpu","dataSources":[{"sourceId":16017,"databundleVersionId":708189,"sourceType":"competition"}],"dockerImageVersionId":30636,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"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\nimport torch.nn as nn\nimport torch.nn.functional as F","metadata":{"execution":{"iopub.status.busy":"2024-01-16T03:32:31.342973Z","iopub.execute_input":"2024-01-16T03:32:31.343732Z","iopub.status.idle":"2024-01-16T03:32:31.350241Z","shell.execute_reply.started":"2024-01-16T03:32:31.343697Z","shell.execute_reply":"2024-01-16T03:32:31.349212Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-01-16T03:32:31.352080Z","iopub.execute_input":"2024-01-16T03:32:31.352383Z","iopub.status.idle":"2024-01-16T03:32:31.360970Z","shell.execute_reply.started":"2024-01-16T03:32:31.352360Z","shell.execute_reply":"2024-01-16T03:32:31.360253Z"},"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":{"execution":{"iopub.status.busy":"2024-01-16T03:32:31.362028Z","iopub.execute_input":"2024-01-16T03:32:31.362374Z","iopub.status.idle":"2024-01-16T03:32:31.373290Z","shell.execute_reply.started":"2024-01-16T03:32:31.362340Z","shell.execute_reply":"2024-01-16T03:32:31.372514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-01-16T03:32:31.374468Z","iopub.execute_input":"2024-01-16T03:32:31.374792Z","iopub.status.idle":"2024-01-16T03:32:34.920822Z","shell.execute_reply.started":"2024-01-16T03:32:31.374763Z","shell.execute_reply":"2024-01-16T03:32:34.920048Z"},"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":{"execution":{"iopub.status.busy":"2024-01-16T03:32:34.924024Z","iopub.execute_input":"2024-01-16T03:32:34.924321Z","iopub.status.idle":"2024-01-16T03:32:34.929676Z","shell.execute_reply.started":"2024-01-16T03:32:34.924296Z","shell.execute_reply":"2024-01-16T03:32:34.928806Z"},"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":"2024-01-16T03:32:34.930700Z","iopub.execute_input":"2024-01-16T03:32:34.930963Z","iopub.status.idle":"2024-01-16T03:32:36.033317Z","shell.execute_reply.started":"2024-01-16T03:32:34.930935Z","shell.execute_reply":"2024-01-16T03:32:36.032347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 4. Thiết kế 1 mạng NN đơn giản","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        \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        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = self.fc3(x)\n        return x\n\n# initialize the NN\ndevice = torch.device(\"cuda\")\n\nmodel = Net().to(device)\nprint(model)","metadata":{"execution":{"iopub.status.busy":"2024-01-16T03:32:36.034736Z","iopub.execute_input":"2024-01-16T03:32:36.035133Z","iopub.status.idle":"2024-01-16T03:32:36.052490Z","shell.execute_reply.started":"2024-01-16T03:32:36.035094Z","shell.execute_reply":"2024-01-16T03:32:36.051356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 5. Loss Function and Optimizer","metadata":{}},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2024-01-16T03:32:36.054319Z","iopub.execute_input":"2024-01-16T03:32:36.054645Z","iopub.status.idle":"2024-01-16T03:32:36.061766Z","shell.execute_reply.started":"2024-01-16T03:32:36.054618Z","shell.execute_reply":"2024-01-16T03:32:36.060938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 6. Train the Network","metadata":{}},{"cell_type":"code","source":"from tqdm import tqdm\n# number of epochs to train the model\nn_epochs = 100\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 tqdm(train_loader):\n        # clear the gradients of all optimized variables\n        optimizer.zero_grad()\n        # move to gpu\n        data = data.to(device)\n        target = target.to(device)\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":{"execution":{"iopub.status.busy":"2024-01-16T03:32:36.062976Z","iopub.execute_input":"2024-01-16T03:32:36.063533Z","iopub.status.idle":"2024-01-16T03:32:50.271419Z","shell.execute_reply.started":"2024-01-16T03:32:36.063500Z","shell.execute_reply":"2024-01-16T03:32:50.270449Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_state_dict(torch.load('model.pt'))","metadata":{"execution":{"iopub.status.busy":"2024-01-16T03:32:50.272724Z","iopub.execute_input":"2024-01-16T03:32:50.273079Z","iopub.status.idle":"2024-01-16T03:32:50.282851Z","shell.execute_reply.started":"2024-01-16T03:32:50.273046Z","shell.execute_reply":"2024-01-16T03:32:50.281910Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### 7. Predict digit dựa vào input","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-01-16T03:32:50.284162Z","iopub.execute_input":"2024-01-16T03:32:50.284517Z","iopub.status.idle":"2024-01-16T03:32:50.292292Z","shell.execute_reply.started":"2024-01-16T03:32:50.284485Z","shell.execute_reply":"2024-01-16T03:32:50.291437Z"},"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        data = batch\n        data = data.to(device)\n        outputs = model(data)\n        _, predicted = torch.max(outputs.data, 1) \n        prediction_list.append(predicted.cpu())\n    return prediction_list","metadata":{"execution":{"iopub.status.busy":"2024-01-16T03:32:50.293453Z","iopub.execute_input":"2024-01-16T03:32:50.295380Z","iopub.status.idle":"2024-01-16T03:32:50.303717Z","shell.execute_reply.started":"2024-01-16T03:32:50.295354Z","shell.execute_reply":"2024-01-16T03:32:50.302976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = predict(model,test_loader)\nnew_predictions = []\nfor p in predictions:\n     new_predictions.append(p.item())\npredictions = new_predictions","metadata":{"execution":{"iopub.status.busy":"2024-01-16T03:32:50.304707Z","iopub.execute_input":"2024-01-16T03:32:50.306825Z","iopub.status.idle":"2024-01-16T03:32:53.527469Z","shell.execute_reply.started":"2024-01-16T03:32:50.306799Z","shell.execute_reply":"2024-01-16T03:32:53.526632Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":{"execution":{"iopub.status.busy":"2024-01-16T03:32:53.530897Z","iopub.execute_input":"2024-01-16T03:32:53.531223Z","iopub.status.idle":"2024-01-16T03:32:53.846116Z","shell.execute_reply.started":"2024-01-16T03:32:53.531197Z","shell.execute_reply":"2024-01-16T03:32:53.845195Z"},"trusted":true},"execution_count":null,"outputs":[]}]}