{"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":"# Standard library\nimport copy\nimport glob\nimport multiprocessing\nimport os\nimport time\nimport zipfile\n\n# Pytorch\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models, transforms\n\n# Related third party\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom PIL import Image\nfrom skimage import io, transform\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.notebook import tqdm","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:08.522835Z","iopub.execute_input":"2022-01-09T18:06:08.523138Z","iopub.status.idle":"2022-01-09T18:06:11.755894Z","shell.execute_reply.started":"2022-01-09T18:06:08.523096Z","shell.execute_reply":"2022-01-09T18:06:11.755152Z"},"jupyter":{"source_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_dir = '../input/dogs-vs-cats-redux-kernels-edition'\nwith zipfile.ZipFile(os.path.join(base_dir, 'train.zip')) as train_zip:\n    train_zip.extractall('../data')\nwith zipfile.ZipFile(os.path.join(base_dir, 'test.zip')) as test_zip:\n    test_zip.extractall('../data')\n\ntrain_dir = '../data/train'\ntest_dir = '../data/test'","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:11.758023Z","iopub.execute_input":"2022-01-09T18:06:11.758279Z","iopub.status.idle":"2022-01-09T18:06:23.135745Z","shell.execute_reply.started":"2022-01-09T18:06:11.758245Z","shell.execute_reply":"2022-01-09T18:06:23.134972Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_size = 224\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\n\n# Number of classes in the dataset\nnum_classes = 2 # dog, cat\n\n# Batch size for training (change depending on how much memory you have)\nbatch_size = 32\n\n# Number of epochs to train for\nnum_epochs = 2\n\n# Flag for feature extracting. When False, we finetune the whole model,\n#   when True we only update the reshaped layer params\nfeature_extract = True\n\n# Switch to perform multi-process data loading\nnum_workers = multiprocessing.cpu_count()","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:23.139877Z","iopub.execute_input":"2022-01-09T18:06:23.142154Z","iopub.status.idle":"2022-01-09T18:06:23.147857Z","shell.execute_reply.started":"2022-01-09T18:06:23.142114Z","shell.execute_reply":"2022-01-09T18:06:23.147297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_class_from(path):\n    file = path.split('/')[-1]\n    return file.split('.')[0]","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:23.148958Z","iopub.execute_input":"2022-01-09T18:06:23.149472Z","iopub.status.idle":"2022-01-09T18:06:23.166297Z","shell.execute_reply.started":"2022-01-09T18:06:23.149433Z","shell.execute_reply":"2022-01-09T18:06:23.165569Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train_model(model, dataloaders, criterion, optimizer, num_epochs=25):\n    since = time.time()\n\n    history = {'accuracy': [],\n               'val_accuracy': [],\n               'loss': [],\n               'val_loss': []}\n\n    best_model_wts = copy.deepcopy(model.state_dict())\n    best_acc = 0.0\n\n    for epoch in range(num_epochs):\n        print('Epoch {}/{}'.format(epoch, num_epochs - 1))\n        print('-' * 10)\n\n        # Each epoch has a training and validation phase\n        for phase in ['train', 'val']:\n            if phase == 'train':\n                model.train()  # Set model to training mode\n            else:\n                model.eval()   # Set model to evaluate mode\n\n            running_loss = 0.0\n            running_corrects = 0\n\n            # Iterate over data.\n            for inputs, labels in tqdm(dataloaders[phase]):\n                inputs = inputs.to(device)\n                labels = labels.to(device)\n\n                # zero the parameter gradients\n                optimizer.zero_grad()\n\n                # forward\n                # track history if only in train\n                with torch.set_grad_enabled(phase == 'train'):\n                    outputs = model(inputs)\n                    loss = criterion(outputs, labels)\n\n                    _, preds = torch.max(outputs, 1)\n\n                    # backward + optimize only if in training phase\n                    if phase == 'train':\n                        loss.backward()\n                        optimizer.step()\n\n                # statistics\n                running_loss += loss.item() * inputs.size(0)\n                running_corrects += torch.sum(preds == labels.data)\n\n            epoch_loss = running_loss / len(dataloaders[phase].dataset)\n            epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)\n\n            print('{} Loss: {:.4f} Acc: {:.4f}'.format(phase, epoch_loss, epoch_acc))\n\n            # deep copy the model\n            if phase == 'val' and epoch_acc > best_acc:\n                best_acc = epoch_acc\n                best_model_wts = copy.deepcopy(model.state_dict())\n\n            if phase == 'train':\n                history['accuracy'].append(epoch_acc.item())\n                history['loss'].append(epoch_loss)\n            else:\n                history['val_accuracy'].append(epoch_acc.item())\n                history['val_loss'].append(epoch_loss) \n\n        print()\n\n    time_elapsed = time.time() - since\n    print('Training complete in {:.0f}m {:.0f}s'.format(time_elapsed // 60, time_elapsed % 60))\n    print('Best val Acc: {:4f}'.format(best_acc))\n\n    # load best model weights\n    model.load_state_dict(best_model_wts)\n    return model, history","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:23.167517Z","iopub.execute_input":"2022-01-09T18:06:23.167776Z","iopub.status.idle":"2022-01-09T18:06:23.188585Z","shell.execute_reply.started":"2022-01-09T18:06:23.167739Z","shell.execute_reply":"2022-01-09T18:06:23.187979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"all_train_files = glob.glob(os.path.join(train_dir, '*.jpg'))\ntrain_list, val_list = train_test_split(all_train_files, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:23.189913Z","iopub.execute_input":"2022-01-09T18:06:23.190508Z","iopub.status.idle":"2022-01-09T18:06:23.345120Z","shell.execute_reply.started":"2022-01-09T18:06:23.190355Z","shell.execute_reply":"2022-01-09T18:06:23.344372Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_list))\nprint(len(val_list))","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:23.346450Z","iopub.execute_input":"2022-01-09T18:06:23.346934Z","iopub.status.idle":"2022-01-09T18:06:23.355273Z","shell.execute_reply.started":"2022-01-09T18:06:23.346899Z","shell.execute_reply":"2022-01-09T18:06:23.352112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fig, axes = plt.subplots(nrows=2,\n                         ncols=3,\n                         figsize=(18, 12))\nfor img_path, ax in zip(train_list, axes.ravel()):\n    ax.set_title(img_path)\n    ax.imshow(Image.open(img_path))","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:23.360324Z","iopub.execute_input":"2022-01-09T18:06:23.361035Z","iopub.status.idle":"2022-01-09T18:06:24.674181Z","shell.execute_reply.started":"2022-01-09T18:06:23.360996Z","shell.execute_reply":"2022-01-09T18:06:24.673367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DogVsCatDataset(Dataset):\n  \n    def __init__(self, file_list, transform=None):\n        self.file_list = file_list\n        self.transform = transform\n    \n    def __len__(self):\n        return len(self.file_list)\n  \n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n       \n        img_name = self.file_list[idx]\n        image = Image.open(img_name)\n        if self.transform:\n            image = self.transform(image)\n    \n        label_category = extract_class_from(img_name)\n        label = 1 if label_category == 'dog' else 0\n    \n        return image, label","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:24.675299Z","iopub.execute_input":"2022-01-09T18:06:24.675570Z","iopub.status.idle":"2022-01-09T18:06:24.684416Z","shell.execute_reply.started":"2022-01-09T18:06:24.675530Z","shell.execute_reply":"2022-01-09T18:06:24.683722Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_transforms = {\n    'train': transforms.Compose([\n        transforms.RandomResizedCrop(input_size, scale=(0.5, 1.0)),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor(),\n        transforms.Normalize(mean, std)\n    ]),\n    'val': transforms.Compose([\n        transforms.Resize(input_size),\n        transforms.CenterCrop(input_size),\n        transforms.ToTensor(),\n        transforms.Normalize(mean, std)\n    ])\n}","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:24.685840Z","iopub.execute_input":"2022-01-09T18:06:24.686284Z","iopub.status.idle":"2022-01-09T18:06:24.694126Z","shell.execute_reply.started":"2022-01-09T18:06:24.686247Z","shell.execute_reply":"2022-01-09T18:06:24.693462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create training and validation datasets\nimage_datasets = {\n    'train': DogVsCatDataset(train_list,\n                             transform=data_transforms['train']),\n    'val': DogVsCatDataset(val_list,\n                           transform=data_transforms['val'])\n}\n\n# Create training and validation dataloaders\ndataloaders_dict = {x: DataLoader(image_datasets[x],\n                                  batch_size=batch_size,\n                                  shuffle=True,\n                                  num_workers=num_workers) for x in ['train', 'val']}\n\n# Detect if we have a GPU available\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:06:24.695461Z","iopub.execute_input":"2022-01-09T18:06:24.696535Z","iopub.status.idle":"2022-01-09T18:06:24.745494Z","shell.execute_reply.started":"2022-01-09T18:06:24.696473Z","shell.execute_reply":"2022-01-09T18:06:24.744602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_ft = models.mobilenet_v2(pretrained=True)\nmodel_ft.classifier[1] = nn.Linear(1280, num_classes)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:07:58.746386Z","iopub.execute_input":"2022-01-09T18:07:58.746813Z","iopub.status.idle":"2022-01-09T18:08:00.174728Z","shell.execute_reply.started":"2022-01-09T18:07:58.746769Z","shell.execute_reply":"2022-01-09T18:08:00.174008Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Send the model to GPU\nmodel_ft = model_ft.to(device)\n\n# Gather the parameters to be optimized/updated in this run. If we are\n#  finetuning we will be updating all parameters. However, if we are\n#  doing feature extract method, we will only update the parameters\n#  that we have just initialized, i.e. the parameters with requires_grad\n#  is True.\nparams_to_update = model_ft.parameters()\nprint(\"Params to learn:\")\nif feature_extract:\n    params_to_update = []\n    for name,param in model_ft.named_parameters():\n        if param.requires_grad == True:\n            params_to_update.append(param)\n            print(\"\\t\",name)\nelse:\n    for name,param in model_ft.named_parameters():\n        if param.requires_grad == True:\n            print(\"\\t\",name)\n\n# Observe that all parameters are being optimized\noptimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:08:06.331108Z","iopub.execute_input":"2022-01-09T18:08:06.331368Z","iopub.status.idle":"2022-01-09T18:08:09.266781Z","shell.execute_reply.started":"2022-01-09T18:08:06.331339Z","shell.execute_reply":"2022-01-09T18:08:09.261032Z"},"collapsed":true,"jupyter":{"outputs_hidden":true},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"criterion = nn.CrossEntropyLoss()\n\n# Train and evaluate\nmodel_ft, hist = train_model(model_ft, dataloaders_dict, criterion, optimizer_ft, num_epochs=num_epochs)","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:09:13.326168Z","iopub.execute_input":"2022-01-09T18:09:13.326431Z","iopub.status.idle":"2022-01-09T18:13:21.257295Z","shell.execute_reply.started":"2022-01-09T18:09:13.326402Z","shell.execute_reply":"2022-01-09T18:13:21.256419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = hist['accuracy']\nval_acc = hist['val_accuracy']\nloss = hist['loss']\nval_loss = hist['val_loss']\nepochs_range = range(num_epochs)\n\nplt.figure(figsize=(24, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:13:36.700760Z","iopub.execute_input":"2022-01-09T18:13:36.701061Z","iopub.status.idle":"2022-01-09T18:13:37.047217Z","shell.execute_reply.started":"2022-01-09T18:13:36.701028Z","shell.execute_reply":"2022-01-09T18:13:37.046544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_list = glob.glob(os.path.join(test_dir, '*.jpg'))\ntest_data_transform = data_transforms['val']\n\nids = []\nlabels = []\n\nwith torch.no_grad():\n    for test_path in tqdm(test_list):\n        img = Image.open(test_path)\n        img = test_data_transform(img)\n        img = img.unsqueeze(0)\n        img = img.to(device)\n\n        model_ft.eval()\n        outputs = model_ft(img)\n        preds = F.softmax(outputs, dim=1)[:, 1].tolist()\n\n        test_id = extract_class_from(test_path)\n        ids.append(int(test_id))\n        labels.append(preds[0])","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:13:48.221305Z","iopub.execute_input":"2022-01-09T18:13:48.221573Z","iopub.status.idle":"2022-01-09T18:16:08.647237Z","shell.execute_reply.started":"2022-01-09T18:13:48.221543Z","shell.execute_reply":"2022-01-09T18:16:08.646496Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"template = '\"{}\" with {:.2%} confidence'\ndef pred_result_message(pred):\n    if pred > 0.5:\n        return template.format('dog', pred)\n    else:\n        return template.format('cat', 1 - pred)\n\nfig, axes = plt.subplots(nrows=2,\n                         ncols=3,\n                         figsize=(18, 12))\nfor img_path, label, ax in zip(test_list, labels, axes.ravel()):\n    ax.set_title(pred_result_message(label))\n    ax.imshow(Image.open(img_path))","metadata":{"execution":{"iopub.status.busy":"2022-01-09T18:16:29.311296Z","iopub.execute_input":"2022-01-09T18:16:29.311574Z","iopub.status.idle":"2022-01-09T18:16:30.478699Z","shell.execute_reply.started":"2022-01-09T18:16:29.311543Z","shell.execute_reply":"2022-01-09T18:16:30.477963Z"},"trusted":true},"execution_count":null,"outputs":[]}]}