{"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":"# 디펜스 코드와의 차별점\n# resnet18모델 -> EfficientNetV2 모델로 변경 및 batch size 128->100으로 변경","metadata":{},"execution_count":null,"outputs":[]},{"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        pass\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":"2022-11-27T16:58:35.049465Z","iopub.execute_input":"2022-11-27T16:58:35.049997Z","iopub.status.idle":"2022-11-27T16:58:36.868914Z","shell.execute_reply.started":"2022-11-27T16:58:35.049950Z","shell.execute_reply":"2022-11-27T16:58:36.867903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport os\nfrom os.path import join\nimport cv2\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torchvision import models\nfrom torch.utils.data import Dataset, DataLoader\nfrom glob import glob\nfrom PIL import Image\nimport random\n\ndevice='cuda' if torch.cuda.is_available() else 'cpu'\n\nseed = 42\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\nif torch.cuda.is_available():\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\ntorch.backends.cudnn.benchmark = False\ntorch.backends.cudnn.deterministic = True","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:36.870795Z","iopub.execute_input":"2022-11-27T16:58:36.871163Z","iopub.status.idle":"2022-11-27T16:58:36.880393Z","shell.execute_reply.started":"2022-11-27T16:58:36.871127Z","shell.execute_reply":"2022-11-27T16:58:36.878332Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class T_DS(Dataset):\n    def __init__(self, path, flag=\"\", transform=None ):\n        self.data_path=path\n        self.flag=flag\n        self.transform=transform\n        \n        if self.flag == \"train\":\n            self.label = [int(1 if p.split('/')[-2]==\"fish_trap\" else 0) for p in path]\n        \n        \n    def __len__(self):\n        return len(self.data_path)\n    \n    def __getitem__(self, idx):\n        image = Image.open(self.data_path[idx], mode='r')\n        image = image.convert('RGB')\n        image = self.transform(image)\n        \n        if self.flag == \"train\":\n            return image, torch.from_numpy(np.array(self.label[idx]))\n        else:\n            return image","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:36.882171Z","iopub.execute_input":"2022-11-27T16:58:36.883010Z","iopub.status.idle":"2022-11-27T16:58:36.892126Z","shell.execute_reply.started":"2022-11-27T16:58:36.882928Z","shell.execute_reply":"2022-11-27T16:58:36.891182Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_parent_path = '/kaggle/input/2022-ai-tp-18011637/Train_Images/Train_Dataset'\ntest_parent_path = '/kaggle/input/2022-ai-tp-18011637/Test_Images/Test'\ntrain_image_path = glob(join(train_parent_path, '*', '*'))\ntest_path = glob(join(test_parent_path, '*'))\n\ntest_image_path=[]\nfor i in range(len(test_path)):\n    test_image_path.append(test_parent_path+'/'+str(i)+'.jpg')","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:36.895155Z","iopub.execute_input":"2022-11-27T16:58:36.895528Z","iopub.status.idle":"2022-11-27T16:58:36.942405Z","shell.execute_reply.started":"2022-11-27T16:58:36.895490Z","shell.execute_reply":"2022-11-27T16:58:36.941552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transform = transforms.Compose(\n    [transforms.Resize((224, 224)),\n     transforms.ToTensor(),\n     #transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n     transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))\n    ])","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:36.943494Z","iopub.execute_input":"2022-11-27T16:58:36.943755Z","iopub.status.idle":"2022-11-27T16:58:36.949597Z","shell.execute_reply.started":"2022-11-27T16:58:36.943731Z","shell.execute_reply":"2022-11-27T16:58:36.948592Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#배치 100으로 , efficientnetv2모델","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Train_DS = T_DS(train_image_path, 'train', transform=transform)\nTest_DS = T_DS(test_image_path, 'test', transform=transform)\n\nTrain_DL=DataLoader(Train_DS, batch_size=100, shuffle=True, num_workers=2)\nTest_DL=DataLoader(Test_DS, batch_size=1, shuffle=False, num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:00:36.584078Z","iopub.execute_input":"2022-11-27T17:00:36.584502Z","iopub.status.idle":"2022-11-27T17:00:36.599138Z","shell.execute_reply.started":"2022-11-27T17:00:36.584468Z","shell.execute_reply":"2022-11-27T17:00:36.598181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!git clone https://github.com/hankyul2/EfficientNetV2-pytorch.git","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:00:38.449176Z","iopub.execute_input":"2022-11-27T17:00:38.450757Z","iopub.status.idle":"2022-11-27T17:00:39.932956Z","shell.execute_reply.started":"2022-11-27T17:00:38.450699Z","shell.execute_reply":"2022-11-27T17:00:39.931542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = torch.hub.load('hankyul2/EfficientNetV2-pytorch', 'efficientnet_v2_s', pretrained=True, nclass=1)\nmodel.classifier = nn.Linear(in_features=1280,out_features=1,bias=True)","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:00:47.615162Z","iopub.execute_input":"2022-11-27T17:00:47.616250Z","iopub.status.idle":"2022-11-27T17:00:52.213485Z","shell.execute_reply.started":"2022-11-27T17:00:47.616199Z","shell.execute_reply":"2022-11-27T17:00:52.212246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:02:12.817327Z","iopub.execute_input":"2022-11-27T17:02:12.817747Z","iopub.status.idle":"2022-11-27T17:02:12.879770Z","shell.execute_reply.started":"2022-11-27T17:02:12.817712Z","shell.execute_reply":"2022-11-27T17:02:12.878834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !pip install efficientnet_pytorch\n\n# from efficientnet_pytorch import EfficientNet\n\n# model = EfficientNet.from_pretrained('efficientnet-b7')","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:36.965786Z","iopub.execute_input":"2022-11-27T16:58:36.966307Z","iopub.status.idle":"2022-11-27T16:58:47.931242Z","shell.execute_reply.started":"2022-11-27T16:58:36.966268Z","shell.execute_reply":"2022-11-27T16:58:47.930007Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # model = models.resnet18(pretrained=True)\n# # model.fc = torch.nn.Linear(512, 1, bias=True)\n# model.fc = nn.Linear(in_features=2560, out_features=1, bias=True)   # change output\n# torch.nn.init.kaiming_normal_(model.fc.weight)\n# model=model.to(device)","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:47.933983Z","iopub.execute_input":"2022-11-27T16:58:47.934747Z","iopub.status.idle":"2022-11-27T16:58:48.068826Z","shell.execute_reply.started":"2022-11-27T16:58:47.934700Z","shell.execute_reply":"2022-11-27T16:58:48.067052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"loss = nn.BCELoss().to(device)\noptimizer = optim.Adam(model.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:01:04.782888Z","iopub.execute_input":"2022-11-27T17:01:04.783289Z","iopub.status.idle":"2022-11-27T17:01:04.792727Z","shell.execute_reply.started":"2022-11-27T17:01:04.783253Z","shell.execute_reply":"2022-11-27T17:01:04.791737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\n\ngc.collect()\ntorch.cuda.empty_cache()","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:01:08.244919Z","iopub.execute_input":"2022-11-27T17:01:08.245292Z","iopub.status.idle":"2022-11-27T17:01:08.831553Z","shell.execute_reply.started":"2022-11-27T17:01:08.245260Z","shell.execute_reply":"2022-11-27T17:01:08.830399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs=3\n\n\nmodel.train()\ncount=1\nfor e in range(epochs+1):\n    avg_cost=0\n    for x,y in Train_DL:\n        x=x.to(device)\n        y=y.unsqueeze(1).float().to(device)\n        cost=loss(torch.sigmoid(model(x)),y)\n        \n        optimizer.zero_grad()\n        cost.backward()\n        optimizer.step()\n        \n        avg_cost+=cost/len(Train_DL)\n        print(count)\n        count+=1\n    if(e%1==0):\n        print(\"{: 4d}/{} Cost: {:.6f}\".format(e,epochs,avg_cost))","metadata":{"execution":{"iopub.status.busy":"2022-11-27T17:01:09.965792Z","iopub.execute_input":"2022-11-27T17:01:09.966155Z","iopub.status.idle":"2022-11-27T17:01:35.036264Z","shell.execute_reply.started":"2022-11-27T17:01:09.966124Z","shell.execute_reply":"2022-11-27T17:01:35.034763Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with  torch.no_grad():\n    submit=pd.read_csv('/kaggle/input/2022-ai-tp-18011637/submit.csv')\n    prediction=[]\n    model.eval()\n    for x in Test_DL:\n        x=x.to(device)\n        pre=model(x)\n        b=torch.FloatTensor([0.5]).to(device)\n        predict=(torch.sigmoid(model(x))>=b).type(torch.uint8)\n        prediction.extend(predict.detach().cpu().numpy().tolist())\n    prediction=np.array(prediction)\nsubmit['Target']=prediction\nsubmit.to_csv('solve.csv',index=False)","metadata":{"execution":{"iopub.status.busy":"2022-11-27T16:58:48.076569Z","iopub.status.idle":"2022-11-27T16:58:48.077289Z","shell.execute_reply.started":"2022-11-27T16:58:48.077037Z","shell.execute_reply":"2022-11-27T16:58:48.077062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}