{"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":"2021-12-18T20:08:15.313910Z","iopub.execute_input":"2021-12-18T20:08:15.314295Z","iopub.status.idle":"2021-12-18T20:08:15.345879Z","shell.execute_reply.started":"2021-12-18T20:08:15.314206Z","shell.execute_reply":"2021-12-18T20:08:15.345180Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip /kaggle/input/dogs-vs-cats/train.zip\n!unzip /kaggle/input/dogs-vs-cats/test1.zip","metadata":{"_kg_hide-input":false,"_kg_hide-output":true,"scrolled":true,"execution":{"iopub.status.busy":"2021-12-18T20:08:15.347306Z","iopub.execute_input":"2021-12-18T20:08:15.347632Z","iopub.status.idle":"2021-12-18T20:08:33.378257Z","shell.execute_reply.started":"2021-12-18T20:08:15.347589Z","shell.execute_reply":"2021-12-18T20:08:33.377349Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = './train'\ntest_dir = './test1'\ntrain_files = os.listdir(train_dir)\ntest_files = os.listdir(test_dir)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:11:07.469220Z","iopub.execute_input":"2021-12-18T20:11:07.469825Z","iopub.status.idle":"2021-12-18T20:11:07.495950Z","shell.execute_reply.started":"2021-12-18T20:11:07.469785Z","shell.execute_reply":"2021-12-18T20:11:07.495343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport os\nimport torch\nimport torch.nn as nn\nimport cv2\nimport matplotlib.pyplot as plt\nimport torchvision\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset\nfrom torchvision import transforms\nimport copy\nfrom tqdm import tqdm\nfrom PIL import Image\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:07:50.112908Z","iopub.execute_input":"2021-12-18T21:07:50.113201Z","iopub.status.idle":"2021-12-18T21:07:50.124599Z","shell.execute_reply.started":"2021-12-18T21:07:50.113168Z","shell.execute_reply":"2021-12-18T21:07:50.123773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CatDogDataset(Dataset):\n    def __init__(self, file_list, dir, mode='train', transform = None):\n        self.file_list = file_list\n        self.dir = dir\n        self.mode= mode\n        self.transform = transform\n        if self.mode == 'train':\n            if 'dog' in self.file_list[0]:\n                self.label = 1\n            else:\n                self.label = 0\n            \n    def __len__(self):\n        return len(self.file_list)\n    \n    def __getitem__(self, idx):\n        img = Image.open(os.path.join(self.dir, self.file_list[idx]))\n        \n        if self.transform:\n            img = self.transform(img)\n        if self.mode == 'train':\n            img = img.numpy()\n            return img.astype('float32'), self.label\n        else:\n            img = img.numpy()\n            return img.astype('float32'), self.file_list[idx]\n\nIMG_SIZE = (128, 128)\nNORMALIZE_MEAN = (0.5, 0.5, 0.5)\nNORMALIZE_STD = (0.5, 0.5, 0.5)\n\ndata_transform = transforms.Compose([\n    transforms.Resize(IMG_SIZE),\n    transforms.ToTensor(),\n])","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:05:41.279375Z","iopub.execute_input":"2021-12-18T21:05:41.279948Z","iopub.status.idle":"2021-12-18T21:05:41.289219Z","shell.execute_reply.started":"2021-12-18T21:05:41.279914Z","shell.execute_reply":"2021-12-18T21:05:41.288263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_files = [tf for tf in train_files if 'cat' in tf]\ndog_files = [tf for tf in train_files if 'dog' in tf]\n\ncats = CatDogDataset(cat_files[:int(len(cat_files)*0.9)], train_dir, transform = data_transform)\ndogs = CatDogDataset(dog_files[:int(len(cat_files)*0.9)], train_dir, transform = data_transform)\n\ncat_val = CatDogDataset(cat_files[(int(len(cat_files)*0.9) + 1):], train_dir, transform = data_transform)\ndog_val = CatDogDataset(dog_files[(int(len(cat_files)*0.9) + 1):], train_dir, transform = data_transform)\n\ncatdogs = ConcatDataset([cats, dogs])\ndataloader = DataLoader(catdogs, batch_size = 32, shuffle=True, num_workers=2)\n\nval_catdogs = ConcatDataset([cat_val, dog_val])\nval_dataloader = DataLoader(val_catdogs, batch_size = 32, shuffle=True, num_workers=2)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:05:41.904275Z","iopub.execute_input":"2021-12-18T21:05:41.904896Z","iopub.status.idle":"2021-12-18T21:05:41.917888Z","shell.execute_reply.started":"2021-12-18T21:05:41.904861Z","shell.execute_reply":"2021-12-18T21:05:41.916436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Number of cat files: \",len(cat_files))\nprint(\"Number of dog files: \",len(dog_files))","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:05:42.808495Z","iopub.execute_input":"2021-12-18T21:05:42.809164Z","iopub.status.idle":"2021-12-18T21:05:42.814659Z","shell.execute_reply.started":"2021-12-18T21:05:42.809105Z","shell.execute_reply":"2021-12-18T21:05:42.813939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Test if dataloader worked\nsamples, labels = iter(dataloader).next()\nplt.figure(figsize=(16,24))\ngrid_imgs = torchvision.utils.make_grid(samples[:24])\nnp_grid_imgs = grid_imgs.numpy()\n# in tensor, image is (batch, width, height), so you have to transpose it to (width, height, batch) in numpy to show it.\nplt.imshow(np.transpose(np_grid_imgs, (1,2,0)))","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:05:43.840605Z","iopub.execute_input":"2021-12-18T21:05:43.840874Z","iopub.status.idle":"2021-12-18T21:05:44.808609Z","shell.execute_reply.started":"2021-12-18T21:05:43.840845Z","shell.execute_reply":"2021-12-18T21:05:44.807876Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install vit-pytorch","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:38:59.127754Z","iopub.execute_input":"2021-12-18T20:38:59.128535Z","iopub.status.idle":"2021-12-18T20:39:06.039751Z","shell.execute_reply.started":"2021-12-18T20:38:59.128497Z","shell.execute_reply":"2021-12-18T20:39:06.038899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from vit_pytorch import ViT","metadata":{"execution":{"iopub.status.busy":"2021-12-18T20:39:06.043118Z","iopub.execute_input":"2021-12-18T20:39:06.043411Z","iopub.status.idle":"2021-12-18T20:39:06.048657Z","shell.execute_reply.started":"2021-12-18T20:39:06.043368Z","shell.execute_reply":"2021-12-18T20:39:06.047445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ViTModel(nn.Module):\n    \n    def __init__(self):\n        super(ViTModel,self).__init__()\n        self.vit = ViT(\n                    image_size = IMG_SIZE,\n                    patch_size = 16,\n                    num_classes = 2,\n                    dim = 1024,\n                    depth = 6,\n                    heads = 16,\n                    mlp_dim = 512,\n                    dropout = 0.1,\n                    emb_dropout = 0.1\n                )\n    \n    def forward(self,x):\n        \n        x = self.vit(x)\n        x = F.softmax(x,dim=-1)\n        return x","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:05:52.895178Z","iopub.execute_input":"2021-12-18T21:05:52.896076Z","iopub.status.idle":"2021-12-18T21:05:52.904037Z","shell.execute_reply.started":"2021-12-18T21:05:52.896024Z","shell.execute_reply":"2021-12-18T21:05:52.903100Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Shape of each input is (32, 3, 128, 128) -> batch size 32\ndevice = 'cuda'\nmodel = ViTModel()\nmodel = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:05:55.083601Z","iopub.execute_input":"2021-12-18T21:05:55.084228Z","iopub.status.idle":"2021-12-18T21:05:55.365745Z","shell.execute_reply.started":"2021-12-18T21:05:55.084183Z","shell.execute_reply":"2021-12-18T21:05:55.365032Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(),lr=0.00001)","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:06:03.060896Z","iopub.execute_input":"2021-12-18T21:06:03.061444Z","iopub.status.idle":"2021-12-18T21:06:03.068488Z","shell.execute_reply.started":"2021-12-18T21:06:03.061390Z","shell.execute_reply":"2021-12-18T21:06:03.065973Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 50\ndevice = 'cuda'\n\n\n\nmodel.train()\nfor epoch in range(epochs):\n    \n\n    for samples, labels in tqdm(dataloader):\n        samples, labels = samples.to(device), labels.to(device)\n        \n        optimizer.zero_grad()\n        output = model(samples)\n        loss = criterion(output,labels)\n        \n        loss.backward()\n        optimizer.step()\n        \n        \n       \n    #Finding accuracy at the end of an epoch\n    total_loss = 0\n    pred_list = torch.tensor([]).to(device)\n    true_list = torch.tensor([]).to(device)\n    for samples, labels in val_dataloader:\n        samples, labels = samples.to(device), labels.to(device)\n        \n        output = model(samples)\n        total_loss += criterion(output,labels).item()\n        pred = torch.argmax(output, dim=1)\n        pred_list = torch.cat((pred_list,pred),0)\n        true_list = torch.cat((true_list,labels),0)\n    \n    correct = pred_list.eq(true_list)\n    acc = torch.mean(correct.float())\n    print('[Epoch {}/{}] -> Train Loss: {:.4f}, val_accuracy: {:.3f}'.format(epoch+1, epochs, total_loss, acc))\n        ","metadata":{"execution":{"iopub.status.busy":"2021-12-18T21:08:36.095848Z","iopub.execute_input":"2021-12-18T21:08:36.096125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}