{"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-10-02T16:51:19.272119Z","iopub.execute_input":"2021-10-02T16:51:19.272802Z","iopub.status.idle":"2021-10-02T16:51:19.282750Z","shell.execute_reply.started":"2021-10-02T16:51:19.272766Z","shell.execute_reply":"2021-10-02T16:51:19.281696Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%bash\nmkdir -p /kaggel/temp\ncp -r /kaggle/input/dogs-vs-cats /kaggle/temp\nls /kaggle/temp\ncd /kaggle/temp\nunzip -qq test1.zip\nunzip -qq train.zip","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:50:33.886714Z","iopub.execute_input":"2021-10-02T16:50:33.887324Z","iopub.status.idle":"2021-10-02T16:50:55.872522Z","shell.execute_reply.started":"2021-10-02T16:50:33.887210Z","shell.execute_reply":"2021-10-02T16:50:55.871568Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!rm -rf /kaggle/working/dogs-vs-cats","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:21.677016Z","iopub.execute_input":"2021-10-02T16:51:21.677315Z","iopub.status.idle":"2021-10-02T16:51:22.356089Z","shell.execute_reply.started":"2021-10-02T16:51:21.677284Z","shell.execute_reply":"2021-10-02T16:51:22.355167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import copy\nimport logging\nimport os\nimport random\nimport time\nfrom collections import defaultdict\nfrom typing import Dict, Iterable, List, Tuple\nfrom tqdm import tqdm\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import DataLoader\nfrom torchvision import models\nfrom torch.utils.data import Dataset\nfrom torchvision.io import read_image\n","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:22.391677Z","iopub.execute_input":"2021-10-02T16:51:22.391909Z","iopub.status.idle":"2021-10-02T16:51:26.815734Z","shell.execute_reply.started":"2021-10-02T16:51:22.391882Z","shell.execute_reply":"2021-10-02T16:51:26.814944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_device() -> torch.device:\n    return torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:26.817409Z","iopub.execute_input":"2021-10-02T16:51:26.817669Z","iopub.status.idle":"2021-10-02T16:51:26.823811Z","shell.execute_reply.started":"2021-10-02T16:51:26.817636Z","shell.execute_reply":"2021-10-02T16:51:26.821797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class DogCatDataset(Dataset):\n    \"\"\" Dataset for the dogs-vs-cats training images. \"\"\"\n    def __init__(self, img_dir, images, transform=None):\n        self.img_dir = img_dir\n        self.images = list(images)\n        self.transform = transform\n\n        self.images.sort()\n\n    def __len__(self):\n        return len(self.images)\n\n    def __getitem__(self, idx):\n        image = read_image(os.path.join(self.img_dir, self.images[idx]))\n        label = int('dog' in os.path.basename(self.images[idx]))\n        if self.transform:\n            image = self.transform(image)\n        return image, torch.tensor(label)\n","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:26.825252Z","iopub.execute_input":"2021-10-02T16:51:26.825534Z","iopub.status.idle":"2021-10-02T16:51:26.834083Z","shell.execute_reply.started":"2021-10-02T16:51:26.825501Z","shell.execute_reply":"2021-10-02T16:51:26.833390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_random_seed(seed: int):\n    random.seed(seed)\n    torch.manual_seed(seed)\n    np.random.seed(seed)\n\n\ndef get_num_images_per_class(images: Iterable[str]) -> Dict[str, int]:\n    count = defaultdict(lambda: 0)\n    for img in images:\n        count[img.split('.')[0]] += 1\n    return dict(count)\n\n\ndef get_dataloaders(dataset_dir: str,\n                    val_split: float = 0.1) -> Dict[str, DataLoader]:\n    # List all the images and shuffle them.\n    images = os.listdir(os.path.join(dataset_dir, 'train'))\n    random.shuffle(images)\n\n    N = len(images)\n    test_images = images[:int(N * val_split)]\n    train_images = images[int(N * val_split):]\n\n    logging.info(f'Classes in train: {get_num_images_per_class(train_images)}')\n    logging.info(\n        f'Classes in validation: {get_num_images_per_class(test_images)}')\n\n    assert set(test_images).isdisjoint(train_images)\n\n    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                                     std=[0.229, 0.224, 0.225])\n\n    train_data = DogCatDataset(\n        os.path.join(dataset_dir, 'train'), train_images,\n        transforms.Compose([\n            transforms.RandomResizedCrop(224),\n            transforms.RandomHorizontalFlip(),\n            transforms.ConvertImageDtype(torch.float32),\n            normalize,\n        ]))\n\n    test_data = DogCatDataset(\n        os.path.join(dataset_dir, 'train'), test_images,\n        transforms.Compose([\n            transforms.Resize(256),\n            transforms.CenterCrop(224),\n            transforms.ConvertImageDtype(torch.float32),\n            normalize,\n        ]))\n\n    train_dataloader = DataLoader(train_data,\n                                  batch_size=32,\n                                  shuffle=True,\n                                  num_workers=8)\n    test_dataloader = DataLoader(test_data,\n                                 batch_size=32,\n                                 shuffle=True,\n                                 num_workers=8,\n                                 pin_memory=True)\n\n    return {'train': train_dataloader, 'val': test_dataloader}\n\n\ndef train_model(model: nn.Module,\n                dataloaders: Dict[str, DataLoader],\n                criterion: nn.Module,\n                optimizer: optim.Optimizer,\n                num_epochs: int = 25) -> Tuple[nn.Module, List[float]]:\n    \"\"\" Train the provided model. \"\"\"\n    since = time.time()\n\n    val_acc_history = []\n\n    best_model_wts = copy.deepcopy(model.state_dict())\n    best_acc = 0.0\n\n    device = get_device()\n\n    for epoch in range(num_epochs):\n        print('Epoch {}/{}'.format(epoch, num_epochs - 1))\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                    _, 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(\n                dataloaders[phase].dataset)\n\n            print('{} Loss: {:.4f} Acc: {:.4f}'.format(\n                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            if phase == 'val':\n                val_acc_history.append(epoch_acc)\n\n        print()\n\n    time_elapsed = time.time() - since\n    logging.info('Training complete in {:.0f}m {:.0f}s'.format(\n        time_elapsed // 60, time_elapsed % 60))\n    logging.info('Best val Acc: {:4f}'.format(best_acc))\n\n    # load best model weights\n    model.load_state_dict(best_model_wts)\n    return model, val_acc_history\n\n\ndef set_parameter_requires_grad(model: nn.Module, feature_extracting: bool):\n    if feature_extracting:\n        for param in model.parameters():\n            param.requires_grad = False\n\n\ndef initialize_model(feature_extracting: bool) -> nn.Module:\n    model = models.resnet50(pretrained=True)\n    set_parameter_requires_grad(model, feature_extracting)\n    model.fc = nn.Linear(model.fc.in_features, 2)\n\n    model.to(get_device())\n\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:26.836388Z","iopub.execute_input":"2021-10-02T16:51:26.836930Z","iopub.status.idle":"2021-10-02T16:51:26.865211Z","shell.execute_reply.started":"2021-10-02T16:51:26.836894Z","shell.execute_reply":"2021-10-02T16:51:26.864391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"set_random_seed(42)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:26.866480Z","iopub.execute_input":"2021-10-02T16:51:26.866830Z","iopub.status.idle":"2021-10-02T16:51:26.880788Z","shell.execute_reply.started":"2021-10-02T16:51:26.866793Z","shell.execute_reply":"2021-10-02T16:51:26.880084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataloaders = get_dataloaders('/kaggle/temp')\nmodel = initialize_model(False)\n\nparams_to_update = model.parameters()\nprint(\"Params to learn:\")\nparams_to_update = []\nfor name, param in model.named_parameters():\n    if param.requires_grad:\n        params_to_update.append(param)\n        print(\"\\t\", name)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:26.882312Z","iopub.execute_input":"2021-10-02T16:51:26.882611Z","iopub.status.idle":"2021-10-02T16:51:38.964307Z","shell.execute_reply.started":"2021-10-02T16:51:26.882553Z","shell.execute_reply":"2021-10-02T16:51:38.963671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fmt = \"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s: %(message)s\"\nlogging.basicConfig(format=fmt, level=logging.DEBUG)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:38.967494Z","iopub.execute_input":"2021-10-02T16:51:38.967728Z","iopub.status.idle":"2021-10-02T16:51:38.973978Z","shell.execute_reply.started":"2021-10-02T16:51:38.967703Z","shell.execute_reply":"2021-10-02T16:51:38.973194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Setup the loss fxn\ncriterion = nn.CrossEntropyLoss()\n\n# Observe that all parameters are being optimized\noptimizer_ft = optim.SGD(params_to_update, lr=0.001, momentum=0.9)\n\n# Train and evaluate\nmodel, hist = train_model(model,\n                          dataloaders,\n                          criterion,\n                          optimizer_ft,\n                          num_epochs=1)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:51:38.975188Z","iopub.execute_input":"2021-10-02T16:51:38.975485Z","iopub.status.idle":"2021-10-02T16:54:30.153310Z","shell.execute_reply.started":"2021-10-02T16:51:38.975448Z","shell.execute_reply":"2021-10-02T16:54:30.152518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_dataloader(dataset_dir: str) -> DataLoader:\n    path = os.path.join(dataset_dir, 'test1')\n    images = os.listdir(path)\n\n    normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                                     std=[0.229, 0.224, 0.225])\n\n    dataset = DogCatDataset(\n        path, images,\n        transforms.Compose([\n            transforms.Resize(256),\n            transforms.CenterCrop(224),\n            transforms.ConvertImageDtype(torch.float32),\n            normalize,\n        ]))\n\n    return DataLoader(dataset, batch_size=32, shuffle=False, num_workers=8)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:54:30.155020Z","iopub.execute_input":"2021-10-02T16:54:30.155864Z","iopub.status.idle":"2021-10-02T16:54:30.163121Z","shell.execute_reply.started":"2021-10-02T16:54:30.155823Z","shell.execute_reply":"2021-10-02T16:54:30.162259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndataloader = get_dataloader('/kaggle/temp')\n\ndevice = get_device()\nresults = []\n\nfor inputs, _ in tqdm(dataloader):\n    inputs = inputs.to(device)\n    outputs = model(inputs)\n    _, preds = torch.max(outputs, 1)\n    results.append(preds)\n\nlabels = torch.cat(results).reshape(-1).cpu().numpy()\nids = np.arange(1, labels.shape[0] + 1)\n\ndata = {\n    'id': ids,\n    'label': labels,\n}\n\ndf = pd.DataFrame(data)\ndf","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:54:30.166032Z","iopub.execute_input":"2021-10-02T16:54:30.166902Z","iopub.status.idle":"2021-10-02T16:55:37.167938Z","shell.execute_reply.started":"2021-10-02T16:54:30.166866Z","shell.execute_reply":"2021-10-02T16:55:37.167200Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.to_csv('/kaggle/working/submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-10-02T16:55:37.169221Z","iopub.execute_input":"2021-10-02T16:55:37.169513Z","iopub.status.idle":"2021-10-02T16:55:37.198147Z","shell.execute_reply.started":"2021-10-02T16:55:37.169478Z","shell.execute_reply":"2021-10-02T16:55:37.197459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}