{"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":6799,"databundleVersionId":4225553,"sourceType":"competition"},{"sourceId":7368600,"sourceType":"datasetVersion","datasetId":4280953},{"sourceId":7375038,"sourceType":"datasetVersion","datasetId":4285350}],"dockerImageVersionId":30627,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from typing import Optional\n\nimport json\nimport os\nimport shutil\nimport time\nimport matplotlib.pyplot as plt\nimport torch\nfrom PIL import Image\nfrom torch import optim\nimport torchvision\nfrom torchvision import transforms,models\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.models import feature_extraction\nfrom torch.utils.data import DataLoader,Dataset","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:45.102047Z","iopub.execute_input":"2024-01-10T06:54:45.102369Z","iopub.status.idle":"2024-01-10T06:54:49.112044Z","shell.execute_reply.started":"2024-01-10T06:54:45.102342Z","shell.execute_reply":"2024-01-10T06:54:49.111056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"DEVICE=torch.device('cuda')","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:49.113959Z","iopub.execute_input":"2024-01-10T06:54:49.114349Z","iopub.status.idle":"2024-01-10T06:54:49.118672Z","shell.execute_reply.started":"2024-01-10T06:54:49.114323Z","shell.execute_reply":"2024-01-10T06:54:49.117735Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"motor=[os.path.join(motor_dir,name) for name in os.listdir(motor_dir)]\nbicycle=[os.path.join(bicycle_dir,name) for name in os.listdir(bicycle_dir)]","metadata":{"execution":{"iopub.status.busy":"2024-01-10T04:09:16.482246Z","iopub.execute_input":"2024-01-10T04:09:16.482542Z","iopub.status.idle":"2024-01-10T04:09:17.253211Z","shell.execute_reply.started":"2024-01-10T04:09:16.482513Z","shell.execute_reply":"2024-01-10T04:09:17.252251Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"indices=np.random.randint(1,100,9)\nfig = plt.figure(figsize=(10,10))\nfor i in range(len(indices)):\n    img=plt.imread(bicycle[indices[i]])\n    ax=plt.subplot(3,3,i+1)\n    plt.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T02:01:24.410418Z","iopub.execute_input":"2024-01-09T02:01:24.411304Z","iopub.status.idle":"2024-01-09T02:01:26.201201Z","shell.execute_reply.started":"2024-01-09T02:01:24.411268Z","shell.execute_reply":"2024-01-09T02:01:26.200296Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ImagenetDataset(torch.utils.data.Dataset):\n    \"\"\"\n    A tiny version of PASCAL VOC 2007 Detection dataset that includes images and\n    annotations with small images and no difficult boxes.\n    \"\"\"\n\n    def __init__(\n        self,\n        dataset_dir: str,\n        motor_fol:str,\n        cycle_fol:str,\n        image_size: int = 224,\n        repeat:int=5\n    ):\n        \"\"\"\n        Args:\n            \n            image_size: Size of imges in the batch. The shorter edge of images\n                will be resized to this size, followed by a center crop. \n        \"\"\"\n        super().__init__()\n        self.image_size = image_size\n        self.classes=['motorbike','bicyle']\n        \n        # Load instances from JSON file:\n        motor_dir=os.path.join(dataset_dir,motor_fol)\n        bicycle_dir=os.path.join(dataset_dir,cycle_fol)\n        \n        motor=[os.path.join(motor_dir,file) for file in os.listdir(motor_dir)]*repeat\n        bicycle=[os.path.join(bicycle_dir,file) for file in os.listdir(bicycle_dir)]*repeat\n        instances=list()\n        for i in range(len(motor)):\n            temp={'name':motor[i],'label':1}\n            instances.append(temp)\n            \n        for i in range(len(bicycle)):\n            temp={'name':bicycle[i],'label':0}\n            instances.append(temp)\n            \n        self.instances=instances\n        self.dataset_dir = dataset_dir\n\n        # Define a transformation function for image: Resize the shorter image\n        # edge then take a center crop (optional) and normalize.\n        _transforms = [\n            transforms.Resize(image_size),\n            transforms.CenterCrop(image_size),\n            transforms.ToTensor(),\n             transforms.Normalize(\n               mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]\n            ),\n            transforms.RandomRotation((0.1,0.5)),\n            transforms.RandomHorizontalFlip(p=0.5),\n            transforms.RandomVerticalFlip(p=0.5)\n        ]\n      \n        self.image_transform = transforms.Compose(_transforms)\n    def __len__(self):\n            return len(self.instances)\n\n    def __getitem__(self, index: int):\n        # PIL image and dictionary of annotations.\n        instance=self.instances[index]\n        image_path, label=instance['name'],instance['label']\n\n        image_path = os.path.join(self.dataset_dir, image_path)\n        image = Image.open(image_path).convert(\"RGB\")\n\n        # Transform input image to CHW tensor.\n        image = self.image_transform(image)\n\n        # Return image path because it is needed for evaluation.\n        return image_path, image, label","metadata":{"execution":{"iopub.status.busy":"2024-01-10T09:35:07.821138Z","iopub.execute_input":"2024-01-10T09:35:07.821793Z","iopub.status.idle":"2024-01-10T09:35:07.835254Z","shell.execute_reply.started":"2024-01-10T09:35:07.821763Z","shell.execute_reply":"2024-01-10T09:35:07.834371Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Classifier(nn.Module):\n    def __init__(self,hidden_unit=128,num_class=1,verbose=True,image_size=224,):\n        super().__init__()\n        cnn = models.regnet_x_400mf(weights='DEFAULT')\n        self.backbone = feature_extraction.create_feature_extractor(\n        cnn,\n        return_nodes={\n            \n            \"avgpool\":'avgpool'\n                },\n        )\n        for child in self.backbone.parameters():\n            child.requires_grad=False\n        # image_size\n        \n        dummy=torch.randn(2,3,image_size,image_size)\n        out_shape=self.backbone(dummy)['avgpool'].shape\n        if verbose:\n            print('output shape of backbone: ',out_shape)\n            \n        self.linear=nn.Sequential(nn.Linear(out_shape[1],hidden_unit,bias=True),\n                                  nn.ReLU(),\n                                  nn.Dropout(p=0.5))\n        self.cls=nn.Linear(hidden_unit,num_class,bias=True)\n    def unfreeze(self):\n        for child in self.backbone.parameters():\n            child.requires_grad=True\n    def forward(self,images):\n        x=self.backbone(images)['avgpool']       \n        x=x.view(images.shape[0],-1)\n        x=self.linear(x)\n        x=self.cls(x)                 \n        x=F.sigmoid(x)\n        return x.squeeze(dim=-1)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:49.137136Z","iopub.execute_input":"2024-01-10T06:54:49.137439Z","iopub.status.idle":"2024-01-10T06:54:49.151763Z","shell.execute_reply.started":"2024-01-10T06:54:49.137414Z","shell.execute_reply":"2024-01-10T06:54:49.150704Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"trainset=ImagenetDataset('/kaggle/input/imagenet-object-localization-challenge/ILSVRC/Data/CLS-LOC/train',\n                        motor_fol='n03791053',\n                        cycle_fol='n03792782')","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:49.15309Z","iopub.execute_input":"2024-01-10T06:54:49.153519Z","iopub.status.idle":"2024-01-10T06:54:49.949564Z","shell.execute_reply.started":"2024-01-10T06:54:49.153493Z","shell.execute_reply":"2024-01-10T06:54:49.948546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_loader=DataLoader(trainset,shuffle=True,batch_size=128,pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:50.08919Z","iopub.execute_input":"2024-01-10T06:54:50.089566Z","iopub.status.idle":"2024-01-10T06:54:50.094386Z","shell.execute_reply.started":"2024-01-10T06:54:50.089538Z","shell.execute_reply":"2024-01-10T06:54:50.093395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample=iter(train_loader)\nsample=next(sample)\ntorch.mean(sample[1][3][:,:,0])","metadata":{"execution":{"iopub.status.busy":"2024-01-10T04:10:29.191337Z","iopub.execute_input":"2024-01-10T04:10:29.191688Z","iopub.status.idle":"2024-01-10T04:10:31.793709Z","shell.execute_reply.started":"2024-01-10T04:10:29.191658Z","shell.execute_reply":"2024-01-10T04:10:31.792875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=Classifier()","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:55.483275Z","iopub.execute_input":"2024-01-10T06:54:55.483907Z","iopub.status.idle":"2024-01-10T06:54:56.323337Z","shell.execute_reply.started":"2024-01-10T06:54:55.483875Z","shell.execute_reply":"2024-01-10T06:54:56.322386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.to(DEVICE)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:54:57.306408Z","iopub.execute_input":"2024-01-10T06:54:57.307256Z","iopub.status.idle":"2024-01-10T06:54:57.506779Z","shell.execute_reply.started":"2024-01-10T06:54:57.307221Z","shell.execute_reply":"2024-01-10T06:54:57.505818Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer=torch.optim.Adam([{'params':model.linear.parameters(),'lr':1e-3},\n                           {'params':model.cls.parameters(),'lr':1e-3}],\n                            lr=1e-6)\nloss_fn=torch.nn.BCELoss(reduction='mean')","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:55:03.590639Z","iopub.execute_input":"2024-01-10T06:55:03.591076Z","iopub.status.idle":"2024-01-10T06:55:03.597448Z","shell.execute_reply.started":"2024-01-10T06:55:03.591046Z","shell.execute_reply":"2024-01-10T06:55:03.596218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def accuracy(pred,target,sigmoid=False):\n    # if pred>0.5 =>set to 1\n    if sigmoid:\n        pred=F.sigmoid(pred)\n    pred[pred>0.5]=1.\n    pred[pred<=0.5]=0.\n    acc=(pred==target).to(float)\n    return torch.mean(acc)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:55:04.314214Z","iopub.execute_input":"2024-01-10T06:55:04.315106Z","iopub.status.idle":"2024-01-10T06:55:04.320283Z","shell.execute_reply.started":"2024-01-10T06:55:04.315071Z","shell.execute_reply":"2024-01-10T06:55:04.31929Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train_one_epoch(model,data_loader,optimizer,loss_fn,DEVICE=torch.device('cuda')):\n    running_loss = 0.0\n    running_acc= 0.0\n    for i, data in enumerate(data_loader):\n        _, inputs, labels = data\n        \n        # Zero the parameter gradients\n        optimizer.zero_grad()\n        \n        # Forward pass, track history if using gradients for model analysis\n        outputs = model(inputs.to(DEVICE))\n        loss = loss_fn(outputs.to(float), labels.to(float).to(DEVICE))\n        acc=accuracy(outputs.to(float), labels.to(float).to(DEVICE))\n        # Backward pass and optimization\n        loss.backward()\n        optimizer.step()\n\n        # Print statistics\n        running_loss += loss.item()\n        running_acc+=acc\n        if i % 20 == 19:  # Print every 20 mini-batches\n            print('loss: %.3f' % (running_loss / 20))\n            print(' acc: %.3f' % (running_acc / 20))\n            running_loss = 0.0\n            running_acc=0.0\n                ","metadata":{"execution":{"iopub.status.busy":"2024-01-10T06:55:08.139133Z","iopub.execute_input":"2024-01-10T06:55:08.139509Z","iopub.status.idle":"2024-01-10T06:55:08.147737Z","shell.execute_reply.started":"2024-01-10T06:55:08.139479Z","shell.execute_reply":"2024-01-10T06:55:08.146741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCH=5\nfor epoch in range(5):  # Adjust number of epochs\n    print(f\"EPOCH: {EPOCH+epoch+1}\")\n    train_one_epoch(model,train_loader,optimizer,loss_fn)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T07:11:53.884382Z","iopub.execute_input":"2024-01-10T07:11:53.885176Z","iopub.status.idle":"2024-01-10T07:22:55.664829Z","shell.execute_reply.started":"2024-01-10T07:11:53.885145Z","shell.execute_reply":"2024-01-10T07:22:55.663954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epoch_number=9\nmodel_path = '/kaggle/working/model{}.pt'.format(epoch_number+1)\ntorch.save(model.state_dict(), model_path)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T07:27:12.524387Z","iopub.execute_input":"2024-01-10T07:27:12.525219Z","iopub.status.idle":"2024-01-10T07:27:12.595402Z","shell.execute_reply.started":"2024-01-10T07:27:12.525174Z","shell.execute_reply":"2024-01-10T07:27:12.594485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2. Finetune with Hanoi dataset","metadata":{}},{"cell_type":"code","source":"hanoi_trainset=ImagenetDataset('/kaggle/input/hanoi-bike/BIKE/train',\n                        motor_fol='motorbike',\n                        cycle_fol='bicycle')\nhanoi_valset=ImagenetDataset('/kaggle/input/hanoi-bike/BIKE/val',\n                        motor_fol='motorbike',\n                        cycle_fol='bicycle',repeat=1)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T09:35:22.485277Z","iopub.execute_input":"2024-01-10T09:35:22.485995Z","iopub.status.idle":"2024-01-10T09:35:22.500666Z","shell.execute_reply.started":"2024-01-10T09:35:22.485962Z","shell.execute_reply":"2024-01-10T09:35:22.499741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hanoi_trainloader=DataLoader(hanoi_trainset,shuffle=True,batch_size=128,pin_memory=True)\nhanoi_valloader=DataLoader(hanoi_valset,shuffle=True,batch_size=32,pin_memory=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T09:35:23.626729Z","iopub.execute_input":"2024-01-10T09:35:23.62746Z","iopub.status.idle":"2024-01-10T09:35:23.632964Z","shell.execute_reply.started":"2024-01-10T09:35:23.627431Z","shell.execute_reply":"2024-01-10T09:35:23.631914Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epoch_number=0\nEPOCHS=10\nbest_vloss = 10\nfor epoch in range(epoch_number,EPOCHS):\n    print('EPOCH {}:'.format(epoch_number + 1))\n\n    # Make sure gradient tracking is on, and do a pass over the data\n    model.train(True)\n    train_one_epoch(model,hanoi_trainloader,optimizer,loss_fn)\n    running_vloss = 0.0\n    running_vacc=0.0\n    # Set the model to evaluation mode, disabling dropout and using population\n    # statistics for batch normalization.\n    model.eval()\n\n    # Disable gradient computation and reduce memory consumption.\n    with torch.no_grad():\n        for i, vdata in enumerate(hanoi_valloader):\n            vinputs=vdata[1].to(DEVICE)\n            vlabels=vdata[2].to(DEVICE)\n            voutputs = model(vinputs)\n            vloss = loss_fn(voutputs.to(float), vlabels.to(float))\n            running_vloss += vloss\n            vacc=accuracy(voutputs.to(float), vlabels.to(float))\n            running_vacc += vacc\n\n    avg_vloss = running_vloss / (i + 1)\n    avg_vacc = running_vacc / (i + 1)\n    \n    print('VALID LOSS: %.3f' % (avg_vloss ))\n    print('VALID ACC: %.3f' % (avg_vacc ))\n    print('\\n')\n    if avg_vloss < best_vloss:\n        best_vloss = avg_vloss\n        model_path = '/kaggle/working/model_finetune{}.pt'.format(epoch_number+1)\n        torch.save(model.state_dict(), model_path)\n\n    epoch_number += 1","metadata":{"execution":{"iopub.status.busy":"2024-01-10T07:27:46.98631Z","iopub.execute_input":"2024-01-10T07:27:46.986655Z","iopub.status.idle":"2024-01-10T07:56:09.603231Z","shell.execute_reply.started":"2024-01-10T07:27:46.98663Z","shell.execute_reply":"2024-01-10T07:56:09.602239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Unfreeze the model and let it train for another 10 epochs.","metadata":{}},{"cell_type":"code","source":"model.unfreeze()","metadata":{"execution":{"iopub.status.busy":"2024-01-10T08:01:22.129371Z","iopub.execute_input":"2024-01-10T08:01:22.130272Z","iopub.status.idle":"2024-01-10T08:01:22.136068Z","shell.execute_reply.started":"2024-01-10T08:01:22.130239Z","shell.execute_reply":"2024-01-10T08:01:22.135044Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer=torch.optim.Adam([{'params':model.linear.parameters(),'lr':1e-3},\n                           {'params':model.cls.parameters(),'lr':1e-3},\n                           {'params':model.backbone.parameters(),'lr':1e-6}],\n                            )\nloss_fn=torch.nn.BCELoss(reduction='mean')","metadata":{"execution":{"iopub.status.busy":"2024-01-10T08:01:39.774652Z","iopub.execute_input":"2024-01-10T08:01:39.775039Z","iopub.status.idle":"2024-01-10T08:01:39.782751Z","shell.execute_reply.started":"2024-01-10T08:01:39.77501Z","shell.execute_reply":"2024-01-10T08:01:39.781825Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epoch_number=40\nEPOCHS=60\n# best_vloss = 10\nfor epoch in range(epoch_number,EPOCHS):\n    print('EPOCH {}:'.format(epoch_number + 1))\n\n    # Make sure gradient tracking is on, and do a pass over the data\n    model.train(True)\n    train_one_epoch(model,hanoi_trainloader,optimizer,loss_fn)\n    running_vloss = 0.0\n    running_vacc=0.0\n    # Set the model to evaluation mode, disabling dropout and using population\n    # statistics for batch normalization.\n    model.eval()\n\n    # Disable gradient computation and reduce memory consumption.\n    with torch.no_grad():\n        for i, vdata in enumerate(hanoi_valloader):\n            vinputs=vdata[1].to(DEVICE)\n            vlabels=vdata[2].to(DEVICE)\n            voutputs = model(vinputs)\n            vloss = loss_fn(voutputs.to(float), vlabels.to(float))\n            running_vloss += vloss\n            vacc=accuracy(voutputs.to(float), vlabels.to(float))\n            running_vacc += vacc\n\n    avg_vloss = running_vloss / (i + 1)\n    avg_vacc = running_vacc / (i + 1)\n    \n    print('VALID LOSS: %.3f' % (avg_vloss ))\n    print('VALID ACC: %.3f' % (avg_vacc ))\n    print('\\n')\n    if avg_vloss < best_vloss:\n        best_vloss = avg_vloss\n        model_path = '/kaggle/working/model_{}.pt'.format(epoch_number+1)\n        torch.save(model.state_dict(), model_path)\n\n    epoch_number += 1","metadata":{"execution":{"iopub.status.busy":"2024-01-10T09:35:39.237484Z","iopub.execute_input":"2024-01-10T09:35:39.238269Z","iopub.status.idle":"2024-01-10T10:33:36.270585Z","shell.execute_reply.started":"2024-01-10T09:35:39.238234Z","shell.execute_reply":"2024-01-10T10:33:36.269521Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = '/kaggle/working/model_finetune{}.pt'.format(60)\ntorch.save(model.state_dict(), model_path)","metadata":{"execution":{"iopub.status.busy":"2024-01-10T10:39:04.635036Z","iopub.execute_input":"2024-01-10T10:39:04.635986Z","iopub.status.idle":"2024-01-10T10:39:04.707617Z","shell.execute_reply.started":"2024-01-10T10:39:04.635955Z","shell.execute_reply":"2024-01-10T10:39:04.706828Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCH=10\nfor epoch in range(5):  # Adjust number of epochs\n    print(f\"EPOCH: {EPOCH+epoch+1}\")\n    train_one_epoch(model,train_loader,optimizer,loss_fn)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T08:24:11.5787Z","iopub.execute_input":"2024-01-09T08:24:11.579527Z","iopub.status.idle":"2024-01-09T08:25:56.917674Z","shell.execute_reply.started":"2024-01-09T08:24:11.57949Z","shell.execute_reply":"2024-01-09T08:25:56.916766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def accuracy(pred,target,sigmoid=False):\n    # if pred>0.5 =>set to 1\n    if sigmoid:\n        pred=F.sigmoid(pred)\n    pred[pred>0.5]=1.\n    pred[pred<=0.5]=0.\n    acc=(pred==target).to(float)\n    return torch.mean(acc)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T08:34:11.383776Z","iopub.execute_input":"2024-01-09T08:34:11.384755Z","iopub.status.idle":"2024-01-09T08:34:11.389883Z","shell.execute_reply.started":"2024-01-09T08:34:11.384719Z","shell.execute_reply":"2024-01-09T08:34:11.389058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with torch.no_grad():\n    pred=model(sample[]).detach()\n    target","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred=torch.tensor([1,2,3])\ntarget=torch.tensor([2,2,1])\nacc=(pred==target).to(float)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T08:33:37.232739Z","iopub.execute_input":"2024-01-09T08:33:37.233462Z","iopub.status.idle":"2024-01-09T08:33:37.238484Z","shell.execute_reply.started":"2024-01-09T08:33:37.23343Z","shell.execute_reply":"2024-01-09T08:33:37.23756Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc","metadata":{"execution":{"iopub.status.busy":"2024-01-09T08:33:40.912975Z","iopub.execute_input":"2024-01-09T08:33:40.913647Z","iopub.status.idle":"2024-01-09T08:33:40.920172Z","shell.execute_reply.started":"2024-01-09T08:33:40.913613Z","shell.execute_reply":"2024-01-09T08:33:40.919222Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample=iter(train_loader)\nsample=next(sample)\ntest=sample[1].to(DEVICE)\ntarget=sample[2]\npred=model(test)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T03:06:11.115514Z","iopub.execute_input":"2024-01-09T03:06:11.116503Z","iopub.status.idle":"2024-01-09T03:06:11.784439Z","shell.execute_reply.started":"2024-01-09T03:06:11.116461Z","shell.execute_reply":"2024-01-09T03:06:11.783503Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test[1]","metadata":{"execution":{"iopub.status.busy":"2024-01-09T03:06:11.786227Z","iopub.execute_input":"2024-01-09T03:06:11.786584Z","iopub.status.idle":"2024-01-09T03:06:11.856219Z","shell.execute_reply.started":"2024-01-09T03:06:11.786551Z","shell.execute_reply":"2024-01-09T03:06:11.855209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred","metadata":{"execution":{"iopub.status.busy":"2024-01-09T03:07:28.780004Z","iopub.execute_input":"2024-01-09T03:07:28.780404Z","iopub.status.idle":"2024-01-09T03:07:28.790784Z","shell.execute_reply.started":"2024-01-09T03:07:28.780375Z","shell.execute_reply":"2024-01-09T03:07:28.7899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"target","metadata":{"execution":{"iopub.status.busy":"2024-01-09T03:07:36.538283Z","iopub.execute_input":"2024-01-09T03:07:36.539281Z","iopub.status.idle":"2024-01-09T03:07:36.546548Z","shell.execute_reply.started":"2024-01-09T03:07:36.539242Z","shell.execute_reply":"2024-01-09T03:07:36.545644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cnn = models.mobilenet_v2(weights='DEFAULT')","metadata":{"execution":{"iopub.status.busy":"2024-01-08T16:09:35.657729Z","iopub.execute_input":"2024-01-08T16:09:35.658472Z","iopub.status.idle":"2024-01-08T16:09:35.909799Z","shell.execute_reply.started":"2024-01-08T16:09:35.658441Z","shell.execute_reply":"2024-01-08T16:09:35.908945Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"backbone = feature_extraction.create_feature_extractor(\n        cnn,\n        return_nodes={\n            \n            \"features.18\":'linear1'\n                },\n        )","metadata":{"execution":{"iopub.status.busy":"2024-01-08T16:12:34.426995Z","iopub.execute_input":"2024-01-08T16:12:34.427896Z","iopub.status.idle":"2024-01-08T16:12:34.527028Z","shell.execute_reply.started":"2024-01-08T16:12:34.427858Z","shell.execute_reply":"2024-01-08T16:12:34.526102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"backbone","metadata":{"execution":{"iopub.status.busy":"2024-01-08T16:12:49.642238Z","iopub.execute_input":"2024-01-08T16:12:49.642916Z","iopub.status.idle":"2024-01-08T16:12:49.651914Z","shell.execute_reply.started":"2024-01-08T16:12:49.642881Z","shell.execute_reply":"2024-01-08T16:12:49.650968Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nimport os\nfrom IPython.display import FileLink\n\ndef zip_dir(directory = '', file_name = 'directory.zip'):\n    \"\"\"\n    zip all the files in a directory\n    \n    Parameters\n    _____\n    directory: str\n        directory needs to be zipped, defualt is current working directory\n        \n    file_name: str\n        the name of the zipped file (including .zip), default is 'directory.zip'\n        \n    Returns\n    _____\n    Creates a hyperlink, which can be used to download the zip file)\n    \"\"\"\n    os.chdir(directory)\n    zip_ref = zipfile.ZipFile(file_name, mode='w')\n    for folder, _, files in os.walk(directory):\n        for file in files:\n            if file_name in file:\n                pass\n            else:\n                zip_ref.write(os.path.join(folder, file))\n\n    return FileLink(file_name)","metadata":{"execution":{"iopub.status.busy":"2024-01-09T07:40:10.840547Z","iopub.execute_input":"2024-01-09T07:40:10.840937Z","iopub.status.idle":"2024-01-09T07:40:10.847617Z","shell.execute_reply.started":"2024-01-09T07:40:10.840897Z","shell.execute_reply":"2024-01-09T07:40:10.846698Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"zip_dir('/kaggle/input/imagenet-object-localization-challenge/ILSVRC/Data/CLS-LOC/train/n03791053','motorbike.zip')","metadata":{"execution":{"iopub.status.busy":"2024-01-09T07:42:06.724563Z","iopub.execute_input":"2024-01-09T07:42:06.725754Z","iopub.status.idle":"2024-01-09T07:42:07.174361Z","shell.execute_reply.started":"2024-01-09T07:42:06.725715Z","shell.execute_reply":"2024-01-09T07:42:07.173157Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}