{"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","_kg_hide-input":false,"_kg_hide-output":false,"execution":{"iopub.status.busy":"2022-10-06T12:46:42.612308Z","iopub.execute_input":"2022-10-06T12:46:42.613218Z","iopub.status.idle":"2022-10-06T12:46:58.488859Z","shell.execute_reply.started":"2022-10-06T12:46:42.613182Z","shell.execute_reply":"2022-10-06T12:46:58.487758Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%mkdir checkpoint","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:13:28.344588Z","iopub.execute_input":"2022-10-14T07:13:28.345266Z","iopub.status.idle":"2022-10-14T07:13:29.310668Z","shell.execute_reply.started":"2022-10-14T07:13:28.345171Z","shell.execute_reply":"2022-10-14T07:13:29.309399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport os\nimport matplotlib.pyplot as plt\nimport seaborn as sn\nimport cv2\n\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset,DataLoader\nfrom torchvision import transforms\nfrom torchvision.utils import make_grid\n\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\nfrom sklearn.metrics import confusion_matrix\nimport matplotlib.pyplot as plt\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-10-14T09:54:03.507892Z","iopub.execute_input":"2022-10-14T09:54:03.508259Z","iopub.status.idle":"2022-10-14T09:54:03.520627Z","shell.execute_reply.started":"2022-10-14T09:54:03.508227Z","shell.execute_reply":"2022-10-14T09:54:03.519392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Check data set**","metadata":{}},{"cell_type":"code","source":"!ls -l /kaggle/input/happy-whale-and-dolphin\n\ndata_path = \"/kaggle/input/happy-whale-and-dolphin\"","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:13:42.819584Z","iopub.execute_input":"2022-10-14T07:13:42.820200Z","iopub.status.idle":"2022-10-14T07:13:43.774425Z","shell.execute_reply.started":"2022-10-14T07:13:42.820165Z","shell.execute_reply":"2022-10-14T07:13:43.773084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = pd.read_csv('/kaggle/input/happy-whale-and-dolphin/train.csv')\nsubmission = pd.read_csv('/kaggle/input/happy-whale-and-dolphin/sample_submission.csv')\n\n","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:13:47.154412Z","iopub.execute_input":"2022-10-14T07:13:47.154795Z","iopub.status.idle":"2022-10-14T07:13:47.300509Z","shell.execute_reply.started":"2022-10-14T07:13:47.154765Z","shell.execute_reply":"2022-10-14T07:13:47.299556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.shape","metadata":{"execution":{"iopub.status.busy":"2022-10-13T14:45:50.130431Z","iopub.execute_input":"2022-10-13T14:45:50.130822Z","iopub.status.idle":"2022-10-13T14:45:50.139622Z","shell.execute_reply.started":"2022-10-13T14:45:50.130790Z","shell.execute_reply":"2022-10-13T14:45:50.138624Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-13T14:45:52.568898Z","iopub.execute_input":"2022-10-13T14:45:52.569264Z","iopub.status.idle":"2022-10-13T14:45:52.587186Z","shell.execute_reply.started":"2022-10-13T14:45:52.569231Z","shell.execute_reply":"2022-10-13T14:45:52.585968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-13T14:32:08.606702Z","iopub.execute_input":"2022-10-13T14:32:08.607129Z","iopub.status.idle":"2022-10-13T14:32:08.620325Z","shell.execute_reply.started":"2022-10-13T14:32:08.607093Z","shell.execute_reply":"2022-10-13T14:32:08.619421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data['path'] = '../input/happy-whale-and-dolphin/train_images/' + train_data['image']\nsubmission['path'] = '../input/happy-whale-and-dolphin/test_images/' + submission['image']","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:13:50.939944Z","iopub.execute_input":"2022-10-14T07:13:50.940336Z","iopub.status.idle":"2022-10-14T07:13:50.967262Z","shell.execute_reply.started":"2022-10-14T07:13:50.940305Z","shell.execute_reply":"2022-10-14T07:13:50.965983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-13T15:01:49.031064Z","iopub.execute_input":"2022-10-13T15:01:49.031487Z","iopub.status.idle":"2022-10-13T15:01:49.044135Z","shell.execute_reply.started":"2022-10-13T15:01:49.031452Z","shell.execute_reply":"2022-10-13T15:01:49.043182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission['image'].nunique()","metadata":{"execution":{"iopub.status.busy":"2022-10-13T14:46:04.861349Z","iopub.execute_input":"2022-10-13T14:46:04.862197Z","iopub.status.idle":"2022-10-13T14:46:04.879468Z","shell.execute_reply.started":"2022-10-13T14:46:04.862159Z","shell.execute_reply":"2022-10-13T14:46:04.878114Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(f\"Images in train data: {train_data.image.nunique()}\")\nprint(f\"Species in train data: {train_data.species.nunique()}\")\nprint(f\"Individual_id in train data: {train_data.individual_id.nunique()}\")\n\n","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:13:56.061326Z","iopub.execute_input":"2022-10-14T07:13:56.062456Z","iopub.status.idle":"2022-10-14T07:13:56.088987Z","shell.execute_reply.started":"2022-10-14T07:13:56.062416Z","shell.execute_reply":"2022-10-14T07:13:56.087972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"encoder = LabelEncoder()\ntrain_data[\"encoded_id\"] = encoder.fit_transform(train_data[\"individual_id\"])","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:13:58.926238Z","iopub.execute_input":"2022-10-14T07:13:58.927286Z","iopub.status.idle":"2022-10-14T07:13:58.975845Z","shell.execute_reply.started":"2022-10-14T07:13:58.927243Z","shell.execute_reply":"2022-10-14T07:13:58.974900Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-13T15:30:55.562910Z","iopub.execute_input":"2022-10-13T15:30:55.563294Z","iopub.status.idle":"2022-10-13T15:30:55.583339Z","shell.execute_reply.started":"2022-10-13T15:30:55.563257Z","shell.execute_reply":"2022-10-13T15:30:55.582478Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len_species = len(train_data[\"species\"].unique())\nfig, axarr = plt.subplots(ncols=5, nrows=len_species, figsize=(12, len_species * 2))\n\nfor i, (name, dfg) in enumerate(train_data.groupby(\"species\")):\n    axarr[i, 0].set_title(name)\n    for j, (_, row) in enumerate(dfg[:5].iterrows()):\n        im_path = os.path.join(data_path, \"train_images\", row[\"image\"])\n        img = plt.imread(im_path)\n        axarr[i, j].imshow(img)\n        axarr[i, j].set_axis_off()","metadata":{"execution":{"iopub.status.busy":"2022-10-14T04:15:43.738817Z","iopub.execute_input":"2022-10-14T04:15:43.739206Z","iopub.status.idle":"2022-10-14T04:17:12.015687Z","shell.execute_reply.started":"2022-10-14T04:15:43.739173Z","shell.execute_reply":"2022-10-14T04:17:12.014377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img.shape","metadata":{"execution":{"iopub.status.busy":"2022-10-13T14:34:33.781717Z","iopub.execute_input":"2022-10-13T14:34:33.782145Z","iopub.status.idle":"2022-10-13T14:34:33.789774Z","shell.execute_reply.started":"2022-10-13T14:34:33.782111Z","shell.execute_reply":"2022-10-13T14:34:33.788433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Loader\n","metadata":{}},{"cell_type":"code","source":"#https://pytorch.org/tutorials/beginner/basics/data_tutorial.html\n#https://www.kaggle.com/code/palash97/happywhale-pytorch-vgg16-starter\n#https://www.kaggle.com/code/clemchris/pytorch-backfin-convnext-arcface\nclass CustomImageDataset(Dataset):\n    def __init__(self,df,img_dir,transform=None):   #(self,csv_path,images_folder,transform)\n        self.df=df\n        self.file_names = self.df['path'].values\n        self.img_dir = img_dir.values\n        self.label = self.df['encoded_id'].values\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        image_path = self.file_names[index]\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        label = self.label[index]\n        \n        image = self.transform(image)\n        return image, torch.tensor(label,dtype=torch.long)\n    ","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:14:07.206277Z","iopub.execute_input":"2022-10-14T07:14:07.206688Z","iopub.status.idle":"2022-10-14T07:14:07.214636Z","shell.execute_reply.started":"2022-10-14T07:14:07.206657Z","shell.execute_reply":"2022-10-14T07:14:07.213554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose([transforms.ToPILImage(),\n                                transforms.Resize((224,224)),   # each original image has different size\n                                transforms.CenterCrop(size=(200,200)),\n                                transforms.ToTensor(),\n                                transforms.Resize((64,64)),\n                                transforms.RandomRotation(30),\n                                transforms.RandomHorizontalFlip(),\n                                transforms.Normalize(mean=[0.4766, 0.4527, 0.3926], std=[0.2275, 0.2224, 0.2210]),\n                                transforms.Grayscale(num_output_channels=1)])  \n#","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:14:14.774494Z","iopub.execute_input":"2022-10-14T07:14:14.774868Z","iopub.status.idle":"2022-10-14T07:14:14.782461Z","shell.execute_reply.started":"2022-10-14T07:14:14.774839Z","shell.execute_reply":"2022-10-14T07:14:14.781081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#from torch.utils.data import RandomSampler,Subset\n\nimg_dir = train_data['path']\n#csv_path = '/kaggle/input/happy-whale-and-dolphin/train.csv'\n\nBATCH_SIZE=256\n\n#indices = torch.arange(10000)\n#sample_data = Subset(train_data,indices)\n#sampler = RandomSampler(sample_data)\n\ndataset = CustomImageDataset(train_data,\n                             img_dir,\n                             transform)\n\ntrain_loader = DataLoader(dataset, batch_size=BATCH_SIZE, shuffle=True)","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:14:18.533037Z","iopub.execute_input":"2022-10-14T07:14:18.533745Z","iopub.status.idle":"2022-10-14T07:14:18.539969Z","shell.execute_reply.started":"2022-10-14T07:14:18.533709Z","shell.execute_reply":"2022-10-14T07:14:18.538598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataiter = iter(train_loader)\n\nimages, labels = dataiter.next()    #images, targets = next(iter(train_loader))","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:14:22.916538Z","iopub.execute_input":"2022-10-14T07:14:22.917488Z","iopub.status.idle":"2022-10-14T07:14:51.437270Z","shell.execute_reply.started":"2022-10-14T07:14:22.917452Z","shell.execute_reply":"2022-10-14T07:14:51.436049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_names=train_data.individual_id.unique()\nnp.set_printoptions(formatter=dict(int=lambda x: f'{x:5}')) # to widen the printed array\n\n# Grab the first batch of 10 images\nfor images,labels in train_loader: \n    break\n\n# Print the labels\nprint('Label:', labels[0:5].numpy())\n#print('Class: ', *np.array(targets[1]))\n\n# Print the images\nim = make_grid(images[0:5], nrow=5)  # the default nrow is 8\nplt.figure(figsize=(10,4))\nplt.imshow(np.transpose(im.numpy(), (1, 2, 0)));","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:15:03.795758Z","iopub.execute_input":"2022-10-14T07:15:03.796542Z","iopub.status.idle":"2022-10-14T07:15:32.303395Z","shell.execute_reply.started":"2022-10-14T07:15:03.796507Z","shell.execute_reply":"2022-10-14T07:15:32.302405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images.shape, labels.shape    ","metadata":{"execution":{"iopub.status.busy":"2022-10-13T14:40:44.920350Z","iopub.execute_input":"2022-10-13T14:40:44.920765Z","iopub.status.idle":"2022-10-13T14:40:44.929094Z","shell.execute_reply.started":"2022-10-13T14:40:44.920733Z","shell.execute_reply":"2022-10-13T14:40:44.927528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# **Building Model:**","metadata":{}},{"cell_type":"code","source":"class Net(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.features = nn.Sequential(\n            nn.Conv2d(1, 36, kernel_size=3, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=3, stride=2),\n            nn.Conv2d(36, 128, kernel_size=3, padding=2),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=3, stride=2),\n            nn.Conv2d(128, 224, kernel_size=3, padding=1),\n            nn.ReLU(),\n            nn.MaxPool2d(kernel_size=3, stride=2)\n        )\n        self.avgpool = nn.AdaptiveAvgPool2d((6, 6))\n        self.classifier = nn.Sequential(\n            nn.Dropout(),\n            nn.Linear(224 * 6 * 6, 96),\n            nn.BatchNorm1d(96),\n            nn.ReLU(),\n            nn.Linear(96, 54),\n            nn.ReLU(),\n            nn.Linear(54, 15587)\n        )\n    def forward(self, x):\n        x = self.features(x)\n        x = self.avgpool(x)\n        x = torch.flatten(x, 1)\n        x = self.classifier(x)\n        return x\n\nnet = Net()","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:16:25.003429Z","iopub.execute_input":"2022-10-14T07:16:25.003844Z","iopub.status.idle":"2022-10-14T07:16:25.039296Z","shell.execute_reply.started":"2022-10-14T07:16:25.003812Z","shell.execute_reply":"2022-10-14T07:16:25.038029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"if torch.cuda.is_available():\n    device = torch.device(\"cuda\")\nelse:\n    device = torch.device(\"cpu\")\nnet.to(device=\"cuda\")","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:16:28.544503Z","iopub.execute_input":"2022-10-14T07:16:28.544882Z","iopub.status.idle":"2022-10-14T07:16:31.573246Z","shell.execute_reply.started":"2022-10-14T07:16:28.544851Z","shell.execute_reply":"2022-10-14T07:16:31.572195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.optim as optim\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size= 1, gamma=0.97)\n\n#lr_sched = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=10, eta_min=0)","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:16:35.793761Z","iopub.execute_input":"2022-10-14T07:16:35.794210Z","iopub.status.idle":"2022-10-14T07:16:35.800760Z","shell.execute_reply.started":"2022-10-14T07:16:35.794174Z","shell.execute_reply":"2022-10-14T07:16:35.799480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#net.train()\n#nsamples = 100\nfor epoch in range(5):  \n\n    running_loss = 0.0\n    for i, data in enumerate(train_loader, 0):\n        #if i > nsamples:\n            #break\n        # get the inputs; data is a list of [inputs, labels]\n        images, labels = data\n        images = images.to(device=\"cuda\")\n        labels= labels.to(device=\"cuda\")\n\n        # zero the parameter gradients\n        optimizer.zero_grad()\n\n        # forward + backward + optimize\n        outputs = net(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        \n        #save state_dict\n        torch.save({\n            'epoch': epoch,\n            'model_state_dict': net.state_dict(),\n            'optimizer_state_dict': optimizer.state_dict(),\n            'scheduler_state_dict':scheduler.state_dict(),\n            'loss': loss,\n            }, './checkpoint/model.pth')\n\n        # print statistics\n        running_loss += loss.item()\n        if i % 10 == 9:    # print every 10 mini-batches\n            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 10:.3f}')\n            running_loss = 0.0\n\nprint('Finished Training')","metadata":{"execution":{"iopub.status.busy":"2022-10-14T07:17:24.374011Z","iopub.execute_input":"2022-10-14T07:17:24.374728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint = torch.load('./checkpoint/model.pth')\n# load model weights state_dict\nnet.load_state_dict(checkpoint['model_state_dict'])\nprint('Previously trained model weights state_dict loaded...')\n# load trained optimizer state_dict\noptimizer.load_state_dict(checkpoint['optimizer_state_dict'])\nprint('Previously trained optimizer state_dict loaded...')\nscheduler.load_state_dict(checkpoint['scheduler_state_dict'])\nprint('Previously trained scheduler_state_dict loaded...')\nepochs = checkpoint['epoch']\n# load the criterion\nloss = checkpoint['loss']\nprint('Trained model loss function loaded...')\nprint(f\"Previously trained for {epochs} number of epochs...\")\n\n\n\nfor epoch in range(3):  \n\n    running_loss = 0.0\n    for i, data in enumerate(train_loader, 0):\n\n        # get the inputs; data is a list of [inputs, labels]\n        images, labels = data\n        images = images.to(device=\"cuda\")\n        labels = labels.to(device=\"cuda\")\n\n        # zero the parameter gradients\n        optimizer.zero_grad()\n\n        # forward + backward + optimize\n        outputs = net(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\n        \n        #save state_dict\n        torch.save({\n            'epoch': epoch,\n            'model_state_dict': net.state_dict(),\n            'optimizer_state_dict': optimizer.state_dict(),\n            'scheduler_state_dict':scheduler.state_dict(),\n            'loss': loss,\n            }, './checkpoint/model.pth')\n\n        # print statistics\n        running_loss += loss.item()\n        if i % 10 == 9:    # print every 10 mini-batches\n            print(f'[{epoch + 1}, {i + 1:5d}] loss: {running_loss / 10:.3f}')\n            running_loss = 0.0\n\nprint('Finished Training')","metadata":{"execution":{"iopub.status.busy":"2022-10-14T09:54:27.853066Z","iopub.execute_input":"2022-10-14T09:54:27.853508Z","iopub.status.idle":"2022-10-14T14:22:53.264245Z","shell.execute_reply.started":"2022-10-14T09:54:27.853476Z","shell.execute_reply":"2022-10-14T14:22:53.255950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Predict images","metadata":{}},{"cell_type":"code","source":"submission.head()","metadata":{"execution":{"iopub.status.busy":"2022-10-14T14:30:03.178220Z","iopub.execute_input":"2022-10-14T14:30:03.178596Z","iopub.status.idle":"2022-10-14T14:30:03.203311Z","shell.execute_reply.started":"2022-10-14T14:30:03.178565Z","shell.execute_reply":"2022-10-14T14:30:03.202178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#https://www.kaggle.com/code/clemchris/pytorch-backfin-convnext-arcface\n","metadata":{"execution":{"iopub.status.busy":"2022-10-08T02:07:13.822632Z","iopub.execute_input":"2022-10-08T02:07:13.823007Z","iopub.status.idle":"2022-10-08T02:07:13.835210Z","shell.execute_reply.started":"2022-10-08T02:07:13.822976Z","shell.execute_reply":"2022-10-08T02:07:13.834088Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#https://www.kaggle.com/code/sirisap/whales-dolphins-vision-transformer\nclass CustomImageTestset(Dataset):\n    def __init__(self, df, transforms=None):\n        self.df = df\n        self.file_names = df['path'].values\n        self.transforms = transform\n        \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, index):\n        image_path = self.file_names[index]\n        image = cv2.imread(image_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        image = self.transforms(image)\n            \n        return image","metadata":{"execution":{"iopub.status.busy":"2022-10-14T14:40:07.194583Z","iopub.execute_input":"2022-10-14T14:40:07.194969Z","iopub.status.idle":"2022-10-14T14:40:07.202629Z","shell.execute_reply.started":"2022-10-14T14:40:07.194940Z","shell.execute_reply":"2022-10-14T14:40:07.201641Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose([transforms.ToPILImage(),\n                                transforms.ToTensor(),\n                                transforms.Resize((64,64)),\n                                transforms.Normalize(mean=[0.4766, 0.4527, 0.3926], std=[0.2275, 0.2224, 0.2210]),\n                                transforms.Grayscale(num_output_channels=1)])  ","metadata":{"execution":{"iopub.status.busy":"2022-10-14T14:40:10.359179Z","iopub.execute_input":"2022-10-14T14:40:10.360048Z","iopub.status.idle":"2022-10-14T14:40:10.365738Z","shell.execute_reply.started":"2022-10-14T14:40:10.360013Z","shell.execute_reply":"2022-10-14T14:40:10.364657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#test_dir = '../input/happy-whale-and-dolphin/test_images/'\n\nBATCH_SIZE=256\n\nTestdata = CustomImageTestset(submission,\n                             transform)\n\ntest_loader = DataLoader(Testdata, batch_size=BATCH_SIZE, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-10-14T14:40:14.267205Z","iopub.execute_input":"2022-10-14T14:40:14.267946Z","iopub.status.idle":"2022-10-14T14:40:14.274762Z","shell.execute_reply.started":"2022-10-14T14:40:14.267911Z","shell.execute_reply":"2022-10-14T14:40:14.273803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"testiter = iter(test_loader)\n\nimages = testiter.next() ","metadata":{"execution":{"iopub.status.busy":"2022-10-14T14:40:58.927860Z","iopub.execute_input":"2022-10-14T14:40:58.928248Z","iopub.status.idle":"2022-10-14T14:41:42.241486Z","shell.execute_reply.started":"2022-10-14T14:40:58.928216Z","shell.execute_reply":"2022-10-14T14:41:42.240492Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#https://www.kaggle.com/code/raininbox/pytorch-train-infer\n#checkpoint = torch.load('model.pt')\n#net.load_state_dict(checkpoint['model_state_dict'])\nnet.eval()\n\npred_list=[]      \nfor i, data in enumerate(test_loader):\n    with torch.no_grad():\n        images = data\n        images = images.to(device=\"cuda\")\n        #labels = labels.to(device=\"cuda\")\n        \n        outputs = net(images)    \n        _, predicted = torch.topk(outputs,5,dim=1)\n        predicted = predicted.detach().cpu().numpy()\n        pred_list.extend(predicted)\n           \n\n\n\n\n\n","metadata":{"execution":{"iopub.status.busy":"2022-10-14T16:17:35.467650Z","iopub.execute_input":"2022-10-14T16:17:35.468032Z","iopub.status.idle":"2022-10-14T17:41:40.289077Z","shell.execute_reply.started":"2022-10-14T16:17:35.468002Z","shell.execute_reply":"2022-10-14T17:41:40.286075Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"id_pred = []\n# convert dummy number to id name\nfor pred in enumerate(pred_list):\n    final_pred = \"\"\n    names = encoder.inverse_transform(pred)\n    for idx, name in enumerate(names):\n        if idx < 4:\n            final_pred += name + \" \"\n        else:\n            final_pred += name\n    id_pred.append(final_pred)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission = pd.DataFrame(submission)\nsubmission['predictions'] = id_pred\nsubmission = submission[0:4,0:1]\nsubmission","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"submission.to_csv('submission.csv', index=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Make Submission\nHit the blue Publish button at the top of your notebook screen. It will take some time for your kernel to run. When it has finished your navigation bar at the top of the screen will have a tab for Output. This only shows up if you have written an output file (like we did in the Prepare Submission File step).Make Submission\nHit the blue Publish button at the top of your notebook screen. It will take some time for your kernel to run. When it has finished your navigation bar at the top of the screen will have a tab for Output. This only shows up if you have written an output file (like we did in the Prepare Submission File step).","metadata":{}}]}