{"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":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-10-03T02:44:53.495757Z","iopub.execute_input":"2023-10-03T02:44:53.496766Z","iopub.status.idle":"2023-10-03T02:44:53.517687Z","shell.execute_reply.started":"2023-10-03T02:44:53.496726Z","shell.execute_reply":"2023-10-03T02:44:53.516693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Bước 1: import 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":"2023-10-03T02:04:21.291603Z","iopub.execute_input":"2023-10-03T02:04:21.292014Z","iopub.status.idle":"2023-10-03T02:04:25.498687Z","shell.execute_reply.started":"2023-10-03T02:04:21.291985Z","shell.execute_reply":"2023-10-03T02:04:25.497640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Bước 2: Define custome 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":"2023-10-03T02:04:25.503522Z","iopub.execute_input":"2023-10-03T02:04:25.506166Z","iopub.status.idle":"2023-10-03T02:04:25.517353Z","shell.execute_reply.started":"2023-10-03T02:04:25.506131Z","shell.execute_reply":"2023-10-03T02:04:25.514797Z"},"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":"2023-10-03T02:04:25.523172Z","iopub.execute_input":"2023-10-03T02:04:25.525502Z","iopub.status.idle":"2023-10-03T02:04:25.534614Z","shell.execute_reply.started":"2023-10-03T02:04:25.525469Z","shell.execute_reply":"2023-10-03T02:04:25.533630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Bước 3: Load train va test dataset, then visualize the train dataset","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":"2023-10-03T02:04:25.538858Z","iopub.execute_input":"2023-10-03T02:04:25.540516Z","iopub.status.idle":"2023-10-03T02:04:29.517389Z","shell.execute_reply.started":"2023-10-03T02:04:25.540486Z","shell.execute_reply":"2023-10-03T02:04:29.516463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_shape_train = train_data[0][0].shape\nprint(sample_shape_train)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:04:29.518666Z","iopub.execute_input":"2023-10-03T02:04:29.519186Z","iopub.status.idle":"2023-10-03T02:04:29.557531Z","shell.execute_reply.started":"2023-10-03T02:04:29.519153Z","shell.execute_reply":"2023-10-03T02:04:29.556564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_shape_train = test_data[0][0].shape\nprint(sample_shape_train)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:04:29.558660Z","iopub.execute_input":"2023-10-03T02:04:29.559531Z","iopub.status.idle":"2023-10-03T02:04:29.573716Z","shell.execute_reply.started":"2023-10-03T02:04:29.559501Z","shell.execute_reply":"2023-10-03T02:04:29.572806Z"},"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":"2023-10-03T02:04:29.575008Z","iopub.execute_input":"2023-10-03T02:04:29.575640Z","iopub.status.idle":"2023-10-03T02:04:29.581220Z","shell.execute_reply.started":"2023-10-03T02:04:29.575610Z","shell.execute_reply":"2023-10-03T02:04:29.580342Z"},"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-03T02:04:29.582660Z","iopub.execute_input":"2023-10-03T02:04:29.583219Z","iopub.status.idle":"2023-10-03T02:04:30.737369Z","shell.execute_reply.started":"2023-10-03T02:04:29.583191Z","shell.execute_reply":"2023-10-03T02:04:30.736492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Bước 4: thiết kế mạng neural network\n### tạo ra 3 layer, với số node lần lượt là 512, 512 và 256","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        hidden_3 = 256\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        self.fc3 = nn.Linear(hidden_2, hidden_3)\n        # linear layer (n_hidden -> 10)\n        self.fc4 = nn.Linear(hidden_3, 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        x = F.relu(self.fc3(x))\n        # add output layer\n        x = self.fc4(x)\n        return x\n\n# initialize the NN\nmodel = Net()\nprint(model)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:04:30.738770Z","iopub.execute_input":"2023-10-03T02:04:30.739332Z","iopub.status.idle":"2023-10-03T02:04:30.754910Z","shell.execute_reply.started":"2023-10-03T02:04:30.739300Z","shell.execute_reply":"2023-10-03T02:04:30.753903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## bước 5: chọn loss function và Optimizer","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":{"execution":{"iopub.status.busy":"2023-10-03T02:04:30.758335Z","iopub.execute_input":"2023-10-03T02:04:30.758620Z","iopub.status.idle":"2023-10-03T02:04:30.763241Z","shell.execute_reply.started":"2023-10-03T02:04:30.758599Z","shell.execute_reply":"2023-10-03T02:04:30.762298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"## Bước 6: Train network\n### chọn epoch = 30","metadata":{}},{"cell_type":"code","source":"# number of epochs to train the model\nn_epochs = 30\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":{"execution":{"iopub.status.busy":"2023-10-03T02:04:30.764636Z","iopub.execute_input":"2023-10-03T02:04:30.765240Z","iopub.status.idle":"2023-10-03T02:12:10.262081Z","shell.execute_reply.started":"2023-10-03T02:04:30.765210Z","shell.execute_reply":"2023-10-03T02:12:10.261140Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Bước 7: Load model có train_loss thấp nhất --> tốt nhất","metadata":{}},{"cell_type":"code","source":"model.load_state_dict(torch.load('model.pt'))","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:12:10.263243Z","iopub.execute_input":"2023-10-03T02:12:10.264106Z","iopub.status.idle":"2023-10-03T02:12:10.273120Z","shell.execute_reply.started":"2023-10-03T02:12:10.264074Z","shell.execute_reply":"2023-10-03T02:12:10.272123Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Bước 8: Chạy nn trên tập test","metadata":{}},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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":"2023-10-03T02:12:10.276606Z","iopub.execute_input":"2023-10-03T02:12:10.277051Z","iopub.status.idle":"2023-10-03T02:12:10.282289Z","shell.execute_reply.started":"2023-10-03T02:12:10.277015Z","shell.execute_reply":"2023-10-03T02:12:10.281440Z"},"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":"2023-10-03T02:12:10.283558Z","iopub.execute_input":"2023-10-03T02:12:10.284088Z","iopub.status.idle":"2023-10-03T02:12:10.292987Z","shell.execute_reply.started":"2023-10-03T02:12:10.284058Z","shell.execute_reply":"2023-10-03T02:12:10.292107Z"},"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().item())\n    return prediction_list","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:12:10.294364Z","iopub.execute_input":"2023-10-03T02:12:10.294931Z","iopub.status.idle":"2023-10-03T02:12:10.302856Z","shell.execute_reply.started":"2023-10-03T02:12:10.294898Z","shell.execute_reply":"2023-10-03T02:12:10.302029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = predict(model,test_loader)\npredictions = np.array(predictions)","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:12:10.304120Z","iopub.execute_input":"2023-10-03T02:12:10.304461Z","iopub.status.idle":"2023-10-03T02:12:13.158778Z","shell.execute_reply.started":"2023-10-03T02:12:10.304426Z","shell.execute_reply":"2023-10-03T02:12:13.157832Z"},"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":{"execution":{"iopub.status.busy":"2023-10-03T02:12:13.160034Z","iopub.execute_input":"2023-10-03T02:12:13.162847Z","iopub.status.idle":"2023-10-03T02:12:13.373838Z","shell.execute_reply.started":"2023-10-03T02:12:13.162816Z","shell.execute_reply":"2023-10-03T02:12:13.372934Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-03T02:12:13.375059Z","iopub.execute_input":"2023-10-03T02:12:13.375586Z","iopub.status.idle":"2023-10-03T02:12:13.389690Z","shell.execute_reply.started":"2023-10-03T02:12:13.375556Z","shell.execute_reply":"2023-10-03T02:12:13.388605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}