{"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-17T14:21:01.837415Z","iopub.execute_input":"2023-10-17T14:21:01.838363Z","iopub.status.idle":"2023-10-17T14:21:02.162193Z","shell.execute_reply.started":"2023-10-17T14:21:01.838326Z","shell.execute_reply":"2023-10-17T14:21:02.161281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install py7zr","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:21:02.164067Z","iopub.execute_input":"2023-10-17T14:21:02.164494Z","iopub.status.idle":"2023-10-17T14:21:15.745773Z","shell.execute_reply.started":"2023-10-17T14:21:02.164447Z","shell.execute_reply":"2023-10-17T14:21:15.744697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"################################### IMPORTS ###################################\n###\nimport numpy as np\nimport pandas as pd\nimport os\nimport copy\nimport matplotlib.pyplot as plt\n\n###\nfrom PIL import Image\n\n###\nimport torch\n# neural network modules, nn.Linear, nn.Conv2d, loss functions\nimport torch.nn as nn\n# activation functions\nimport torch.nn.functional as F\n# optimizers\nimport torch.optim as optim\n# transformations \nimport torchvision.transforms as transforms\n\nfrom torchvision import models\nimport torchvision\nfrom torch.utils.data import DataLoader, Dataset, Subset\n\n###\nfrom sklearn.model_selection import train_test_split\n\n# device config\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n###\nimport warnings\nwarnings.filterwarnings(\"ignore\")\n\n###\nfrom py7zr import unpack_7zarchive\nimport shutil\nshutil.register_unpack_format('7zip', ['.7z'], unpack_7zarchive)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:21:15.747370Z","iopub.execute_input":"2023-10-17T14:21:15.748073Z","iopub.status.idle":"2023-10-17T14:21:20.069503Z","shell.execute_reply.started":"2023-10-17T14:21:15.748037Z","shell.execute_reply":"2023-10-17T14:21:20.068588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nnum_epochs = 3\nbatch_size = 32\nlr = 0.01","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:21:37.666320Z","iopub.execute_input":"2023-10-17T14:21:37.666784Z","iopub.status.idle":"2023-10-17T14:21:37.673196Z","shell.execute_reply.started":"2023-10-17T14:21:37.666756Z","shell.execute_reply":"2023-10-17T14:21:37.670469Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nclass CifarLoader(Dataset):\n  def __init__(self, root_dir, csv_file = None, transform = None):\n\n    # images directory \n    self.root_dir = root_dir\n    # transformations if any\n    self.transform = transform\n\n    if csv_file:\n      # read csv file\n      self.df = pd.read_csv(csv_file)\n\n      # {class: lbl}\n      self.annot_dict = {}\n\n      for i, lbl in enumerate(self.df['label'].unique()):\n        self.annot_dict[lbl] = i\n\n      # {lbl: class}\n      self.annot_dict_reversed = {v:k for k,v in self.annot_dict.items()}\n\n      # add a column with decoded labels\n      self.df['encoded'] = self.df['label'].map(self.annot_dict)\n\n    else: \n      # if no csv file provided -> create a df, fill labels with 0's\n      self.df = pd.DataFrame({\n          'id': list(range(1, len(os.listdir(self.root_dir)) + 1)),\n          'label': np.zeros(len(os.listdir(self.root_dir))),\n          'encoded': np.zeros(len(os.listdir(self.root_dir)))\n      })\n\n\n  def __len__(self):\n    # num of records in the df\n    return len(self.df)\n\n  def __getitem__(self, index):\n    # path to the image\n    img_path = os.path.join(self.root_dir, str(self.df.iloc[index, 0]) + '.png')\n    # read image\n    image = np.array(Image.open(img_path).convert('RGB'))\n    # get label\n    y_label = torch.tensor(int(self.df.iloc[index, 2]))\n\n    # apply transformations\n    if self.transform:\n      image = self.transform(image)\n    \n    return (image, y_label)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:22:12.494649Z","iopub.execute_input":"2023-10-17T14:22:12.495005Z","iopub.status.idle":"2023-10-17T14:22:12.503336Z","shell.execute_reply.started":"2023-10-17T14:22:12.494977Z","shell.execute_reply":"2023-10-17T14:22:12.502390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# transform tensors to normalized range form [0, 1] to [-1, 1]\nmean = np.array([0.5, 0.5, 0.5])\nstd = np.array([0.25, 0.25, 0.25])\n\ntr = transforms.Compose([\n        transforms.ToPILImage(),\n        transforms.Resize((224, 224)),  \n        transforms.ToTensor(),        \n        transforms.Normalize(mean, std)\n    ])","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:22:36.137814Z","iopub.execute_input":"2023-10-17T14:22:36.138352Z","iopub.status.idle":"2023-10-17T14:22:36.144192Z","shell.execute_reply.started":"2023-10-17T14:22:36.138325Z","shell.execute_reply":"2023-10-17T14:22:36.142838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# unzip train and test data\nshutil.unpack_archive('../input/cifar-10/train.7z')","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:22:52.671411Z","iopub.execute_input":"2023-10-17T14:22:52.671729Z","iopub.status.idle":"2023-10-17T14:23:33.899063Z","shell.execute_reply.started":"2023-10-17T14:22:52.671703Z","shell.execute_reply":"2023-10-17T14:23:33.898128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = CifarLoader(csv_file = '../input/cifar-10/trainLabels.csv', \n                      root_dir = './train',\n                      transform = tr)\n\nprint(dataset.df.head())","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:30:57.405417Z","iopub.execute_input":"2023-10-17T14:30:57.405784Z","iopub.status.idle":"2023-10-17T14:30:57.473826Z","shell.execute_reply.started":"2023-10-17T14:30:57.405756Z","shell.execute_reply":"2023-10-17T14:30:57.472849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"indexes = list(range(len(dataset)))\n\ntrain_indexes, val_indexes = train_test_split(indexes, test_size=0.2)\n\ndata = {}\ndata['train'] = Subset(dataset, train_indexes)\ndata['val'] = Subset(dataset, val_indexes)\n\ndataloader_train = DataLoader(dataset = data['train'], batch_size = batch_size, shuffle=False)\ndataloader_val = DataLoader(dataset = data['val'], batch_size = batch_size, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:31:15.080203Z","iopub.execute_input":"2023-10-17T14:31:15.080545Z","iopub.status.idle":"2023-10-17T14:31:15.100323Z","shell.execute_reply.started":"2023-10-17T14:31:15.080517Z","shell.execute_reply":"2023-10-17T14:31:15.099317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_indexes), len(val_indexes))","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:31:28.671343Z","iopub.execute_input":"2023-10-17T14:31:28.671681Z","iopub.status.idle":"2023-10-17T14:31:28.676650Z","shell.execute_reply.started":"2023-10-17T14:31:28.671655Z","shell.execute_reply":"2023-10-17T14:31:28.675583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def images_show(images, lbls=None):\n  # show only 4 first images from each batch\n  for i in range(4):\n    plt.subplot(1, 4, i + 1)\n    # convert to numpy\n    img = images[i].numpy().transpose((1, 2, 0))\n    # unnormalize\n    img = img * std + mean \n    img = np.clip(img, a_min=0, a_max=1)\n    plt.imshow(img)\n \n    if lbls != None:\n      # decode labels using reversed annotation dictionary\n      plt.title(dataset.annot_dict_reversed[lbls[i].item()])\n    plt.axis('off')\n  plt.tight_layout(pad=0.5)\n  plt.show()","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:32:06.504258Z","iopub.execute_input":"2023-10-17T14:32:06.505270Z","iopub.status.idle":"2023-10-17T14:32:06.510876Z","shell.execute_reply.started":"2023-10-17T14:32:06.505233Z","shell.execute_reply":"2023-10-17T14:32:06.509968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataiter = iter(dataloader_train)\nimages, labels = next(dataiter)\nprint(f'Shape: {images.shape}')\nprint(f'Max: {torch.max(images[0]):.2f}')\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:36:50.384850Z","iopub.execute_input":"2023-10-17T14:36:50.385886Z","iopub.status.idle":"2023-10-17T14:36:50.562881Z","shell.execute_reply.started":"2023-10-17T14:36:50.385842Z","shell.execute_reply":"2023-10-17T14:36:50.561869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in range(3):\n  images, labels = next(dataiter)\n  images_show(images, labels)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:37:17.333221Z","iopub.execute_input":"2023-10-17T14:37:17.333559Z","iopub.status.idle":"2023-10-17T14:37:18.926610Z","shell.execute_reply.started":"2023-10-17T14:37:17.333533Z","shell.execute_reply":"2023-10-17T14:37:18.925727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load a pretrained model and reset final fully connected layer\n\n# load a pretrained model \nmodel = models.resnet152(pretrained=True)\n\n# reset final fully connected layer\nnum_ftrs = model.fc.in_features\n\nmodel.classifier = nn.Sequential(\n                        nn.Linear(num_ftrs, 256),  \n                        nn.ReLU(), \n                        nn.Dropout(0.3),\n                        nn.Linear(256, 10))\n\n# copy weights for futher retraining on full train dataset\nmodel_wts = copy.deepcopy(model.state_dict())\n\n# move model to a device\nmodel = model.to(device)\n\n# loss\ncriterion = nn.CrossEntropyLoss()\n\n# all parameters are being optimized\noptimizer = optim.SGD(model.parameters(), lr=lr)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:37:48.846250Z","iopub.execute_input":"2023-10-17T14:37:48.846597Z","iopub.status.idle":"2023-10-17T14:37:54.661380Z","shell.execute_reply.started":"2023-10-17T14:37:48.846571Z","shell.execute_reply":"2023-10-17T14:37:54.660223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train(model, criterion, optimizer, num_epochs, \n          dataloader_train, dataloader_val = None):\n\n  history = {\n        'loss': [],\n        'accuracy': [],\n        'val_loss': [],\n        'val_accuracy': [],\n        'best train acc': (0, 0)\n        }\n\n  best_model_wts = copy.deepcopy(model.state_dict())\n  best_acc = 0.0\n\n\n  for epoch in range(num_epochs):\n    print('Epoch {}/{}'.format(epoch + 1, num_epochs))\n\n    # set model to the training mode\n    model.train()\n\n    n_samples = 0\n    correct_train = 0\n    epoch_loss_train = 0\n    epoch_loss_val = 0\n\n\n    for i, (images, labels) in enumerate(dataloader_train):\n      # origin shape: [4, 3, 32, 32] = 4, 3, 1024\n    \n      images = images.to(device)\n      labels = labels.to(device)\n\n      # forward pass (pred)\n      pred = model(images)\n\n      # loss\n      loss = criterion(pred, labels)\n\n      # mean loss * num samples in batch\n      epoch_loss_train += labels.shape[0] * loss.item()\n\n      # empty gradients\n      optimizer.zero_grad()\n\n      # gradient (backpropagation)\n      loss.backward()\n\n      # update weights\n      optimizer.step()\n\n      # values, indexes\n      value, predicted = torch.max(pred, 1)\n\n      # += batch_size\n      n_samples += labels.shape[0]\n      # num of correctly predicted in this batch\n      correct_train += (predicted==labels).sum().item()\n\n    # train acc per epoch\n    train_acc = 100 * correct_train / n_samples\n    # train loss per epoch\n    epoch_loss_train = epoch_loss_train / n_samples\n\n    print(f'Train accuracy: {train_acc:.2f}, loss: {epoch_loss_train:.2f}')\n    #print(f'Best accuracy: {best_acc:.2f}')\n\n    history['accuracy'].append(train_acc)\n    history['loss'].append(epoch_loss_train)\n\n    # find best accuracy on training data\n    if train_acc > best_acc:\n\n      #print('*New best accuracy*')\n      best_acc = train_acc\n\n      # copy current model weights\n      best_model_wts = copy.deepcopy(model.state_dict())\n      history['best train acc'] = (epoch, best_acc)\n\n\n\n    if dataloader_val:\n\n      # evaluation mode\n      model.eval()\n\n      with torch.no_grad():\n        correct_val = 0\n        n_samples = 0\n\n        for images, labels in dataloader_val: \n          images = images.to(device)\n          labels = labels.to(device)\n\n          outputs = model(images)\n\n          loss = criterion(outputs, labels)\n          epoch_loss_val += labels.shape[0] * loss.item()\n\n          # value, index\n          _, pred = torch.max(outputs, 1)\n          n_samples += labels.shape[0]\n          correct_val += (pred==labels).sum().item()\n\n        # calculate validation accuracy and loss for each epoch\n        val_acc = 100 * correct_val / len(data['val'])\n        epoch_loss_val = epoch_loss_val / len(data['val'])\n\n        print(f'Val accuracy: {val_acc:.2f}, loss: {epoch_loss_val:.2f}')\n\n        history['val_accuracy'].append(val_acc)\n        history['val_loss'].append(epoch_loss_val)\n      \n    print('=' * 80)\n\n\n  print('Best train acc: {:2f}'.format(best_acc))\n\n  # load best weights\n  model.load_state_dict(best_model_wts)\n\n  return model, history","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:38:17.675260Z","iopub.execute_input":"2023-10-17T14:38:17.675593Z","iopub.status.idle":"2023-10-17T14:38:17.687413Z","shell.execute_reply.started":"2023-10-17T14:38:17.675565Z","shell.execute_reply":"2023-10-17T14:38:17.686339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model, history = train(model, criterion, optimizer, num_epochs, \n                       dataloader_train, dataloader_val)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T14:38:34.790937Z","iopub.execute_input":"2023-10-17T14:38:34.791461Z","iopub.status.idle":"2023-10-17T15:07:56.787157Z","shell.execute_reply.started":"2023-10-17T14:38:34.791425Z","shell.execute_reply":"2023-10-17T15:07:56.786211Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_history(history):\n   \n    loss = history['loss']\n    accuracy = history['accuracy']\n    val_loss = history['val_loss']\n    val_accuracy = history['val_accuracy']\n    x = range(len(loss))\n\n    plt.figure(figsize=(12, 5))\n    plt.subplot(1, 2, 1)\n    plt.plot(x, accuracy, label='Training acc', color='#03045e', linewidth=2)\n    if len(val_loss) != 0:\n      plt.plot(x, val_accuracy, label='Validation acc', color='#48cae4', linewidth=2)\n    plt.plot(history['best train acc'][0], \n             history['best train acc'][1], \n             'bo', label='Best train acc', markersize=7, color='black')\n    plt.title('Accuracy')\n    plt.grid(True)\n    plt.legend()\n    \n    \n    plt.subplot(1, 2, 2)\n    plt.plot(x, loss, label='Training loss', color='#03045e', linewidth=2)\n    if len(val_loss) != 0:\n      plt.plot(x, val_loss, label='Validation loss', color='#48cae4', linewidth=2)\n    plt.title('Loss')\n    plt.grid(True)\n    plt.legend()","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:11:35.151276Z","iopub.execute_input":"2023-10-17T15:11:35.151609Z","iopub.status.idle":"2023-10-17T15:11:35.159344Z","shell.execute_reply.started":"2023-10-17T15:11:35.151581Z","shell.execute_reply":"2023-10-17T15:11:35.158508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_history(history)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:11:50.165794Z","iopub.execute_input":"2023-10-17T15:11:50.166169Z","iopub.status.idle":"2023-10-17T15:11:50.735547Z","shell.execute_reply.started":"2023-10-17T15:11:50.166134Z","shell.execute_reply":"2023-10-17T15:11:50.734715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def evaluate(model, dataloader):\n\n  with torch.no_grad():\n    model.eval()\n    n_correct = 0\n    n_samples = 0\n\n    for images, labels in dataloader: \n      images = images.to(device)\n      labels = labels.to(device)\n\n      outputs = model(images)\n\n      # value, index\n      v, pred = torch.max(outputs, 1)\n\n      n_samples += labels.shape[0]\n      n_correct += (pred==labels).sum().item()\n\n    acc = 100.0 * n_correct / n_samples\n    print(acc)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:14:02.205181Z","iopub.execute_input":"2023-10-17T15:14:02.205511Z","iopub.status.idle":"2023-10-17T15:14:02.211691Z","shell.execute_reply.started":"2023-10-17T15:14:02.205484Z","shell.execute_reply":"2023-10-17T15:14:02.210748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"evaluate(model, dataloader_val)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:14:14.565517Z","iopub.execute_input":"2023-10-17T15:14:14.565835Z","iopub.status.idle":"2023-10-17T15:15:07.128072Z","shell.execute_reply.started":"2023-10-17T15:14:14.565808Z","shell.execute_reply":"2023-10-17T15:15:07.127114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataloader = DataLoader(dataset = dataset, batch_size = batch_size, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:16:12.148689Z","iopub.execute_input":"2023-10-17T15:16:12.149054Z","iopub.status.idle":"2023-10-17T15:16:12.154500Z","shell.execute_reply.started":"2023-10-17T15:16:12.149025Z","shell.execute_reply":"2023-10-17T15:16:12.153446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.unpack_archive('../input/cifar-10/test.7z')\ndataset_test = CifarLoader(root_dir = './test',\n                      transform = tr)\n\ndataloader_test = DataLoader(dataset = dataset_test, \n                             batch_size = batch_size, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:16:28.532521Z","iopub.execute_input":"2023-10-17T15:16:28.532845Z","iopub.status.idle":"2023-10-17T15:29:27.126359Z","shell.execute_reply.started":"2023-10-17T15:16:28.532820Z","shell.execute_reply":"2023-10-17T15:29:27.125397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_state_dict(model_wts)\n\n# loss\ncriterion = nn.CrossEntropyLoss()\n\n# all parameters are being optimized\noptimizer = optim.SGD(model.parameters(), lr=lr)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:29:38.099690Z","iopub.execute_input":"2023-10-17T15:29:38.100045Z","iopub.status.idle":"2023-10-17T15:29:38.204133Z","shell.execute_reply.started":"2023-10-17T15:29:38.100017Z","shell.execute_reply":"2023-10-17T15:29:38.203218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model, history = train(model, criterion, optimizer, 3, dataloader)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T15:29:53.069382Z","iopub.execute_input":"2023-10-17T15:29:53.069727Z","iopub.status.idle":"2023-10-17T16:02:56.551145Z","shell.execute_reply.started":"2023-10-17T15:29:53.069699Z","shell.execute_reply":"2023-10-17T16:02:56.550227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(dataset_test))","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:03:07.889300Z","iopub.execute_input":"2023-10-17T16:03:07.889631Z","iopub.status.idle":"2023-10-17T16:03:07.895488Z","shell.execute_reply.started":"2023-10-17T16:03:07.889604Z","shell.execute_reply":"2023-10-17T16:03:07.894459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = np.array([])\n\nwith torch.no_grad():\n    model.eval()\n\n    for images, _ in dataloader_test:\n      images = images.to(device)\n\n      outputs = model(images)\n\n      # value, index\n      v, pred = torch.max(outputs, 1)\n\n      pred = pred.cpu().numpy()\n\n      predictions = np.concatenate((predictions, pred), axis = None)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:03:27.859521Z","iopub.execute_input":"2023-10-17T16:03:27.859844Z","iopub.status.idle":"2023-10-17T16:29:51.495825Z","shell.execute_reply.started":"2023-10-17T16:03:27.859817Z","shell.execute_reply":"2023-10-17T16:29:51.494796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset_test.df['encoded'] = predictions.astype(int)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:29:51.497506Z","iopub.execute_input":"2023-10-17T16:29:51.498397Z","iopub.status.idle":"2023-10-17T16:29:51.538289Z","shell.execute_reply.started":"2023-10-17T16:29:51.498352Z","shell.execute_reply":"2023-10-17T16:29:51.537455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset_test.df['label'] = dataset_test.df['encoded'].map(dataset.annot_dict_reversed)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:30:47.588344Z","iopub.execute_input":"2023-10-17T16:30:47.588669Z","iopub.status.idle":"2023-10-17T16:30:47.601646Z","shell.execute_reply.started":"2023-10-17T16:30:47.588643Z","shell.execute_reply":"2023-10-17T16:30:47.600765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset_test.df.head()","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:30:51.027598Z","iopub.execute_input":"2023-10-17T16:30:51.028740Z","iopub.status.idle":"2023-10-17T16:30:51.040859Z","shell.execute_reply.started":"2023-10-17T16:30:51.028701Z","shell.execute_reply":"2023-10-17T16:30:51.039714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataiter = iter(dataloader_test)\nimages, labels = next(dataiter)\n\nfor i in range(3):\n    images, labels = next(dataiter)\n    images_show(images, labels)\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:32:31.861276Z","iopub.execute_input":"2023-10-17T16:32:31.861606Z","iopub.status.idle":"2023-10-17T16:32:33.459745Z","shell.execute_reply.started":"2023-10-17T16:32:31.861579Z","shell.execute_reply":"2023-10-17T16:32:33.458890Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset_test.df.drop(columns ='encoded', inplace=True)\ndataset_test.df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:32:55.194090Z","iopub.execute_input":"2023-10-17T16:32:55.194603Z","iopub.status.idle":"2023-10-17T16:32:55.684043Z","shell.execute_reply.started":"2023-10-17T16:32:55.194563Z","shell.execute_reply":"2023-10-17T16:32:55.683131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%rm -rf ./train\n%rm -rf ./test","metadata":{"execution":{"iopub.status.busy":"2023-10-17T16:33:07.394722Z","iopub.execute_input":"2023-10-17T16:33:07.395065Z","iopub.status.idle":"2023-10-17T16:33:20.503976Z","shell.execute_reply.started":"2023-10-17T16:33:07.395037Z","shell.execute_reply":"2023-10-17T16:33:20.502706Z"},"trusted":true},"execution_count":null,"outputs":[]}]}