{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\n# import numpy as np # linear algebra\n# import 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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 0. Configure Package Dependencies","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil\nimport random\nimport gc\nimport multiprocessing\nimport copy\nimport time\nimport numpy as np\nimport pandas as pd\nfrom zipfile import ZipFile\nfrom PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom tqdm.notebook import tqdm\nimport matplotlib.pyplot as plt\n%matplotlib inline\n\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 1. Import the Dataset ","execution_count":null},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"def unzip(fileName, dirName):\n    \"\"\"\n    Extract all files from a zip file to a certain Directory.\n    \"\"\"\n    with ZipFile(fileName, 'r') as zipObj:\n        zipObj.extractall(dirName)   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define training and test zip file path.\nTRAIN_ZIP = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip'\nTEST_ZIP = '/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip'\n\n# Define training and test directory.\nDIR = '/kaggle/working/'\n\nunzip(TRAIN_ZIP, DIR)\nunzip(TEST_ZIP, DIR)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define training and validation directories.\nTRAIN_DIR = '/kaggle/working/train/'\nTEST_DIR = '/kaggle/working/test/'\n\ntrain_dogs = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'dog' in i]\ntrain_cats = [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cat' in i]\ntest_imgs = [TEST_DIR+i for i in os.listdir(TEST_DIR)]\n\n# Generate training set by sampling a slice of dogs and cats. \n# train_imgs = train_dogs[:2500] + train_cats[:2500] # get 10%\ntrain_imgs = train_dogs + train_cats\nrandom.shuffle(train_imgs)  \n\ndel train_dogs\ndel train_cats\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check file name and file path.\nprint('Total {} train images'.format(len(train_imgs)))\nprint()\nprint(os.listdir(TRAIN_DIR)[:5])\nprint()\nprint(train_imgs[:5])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Check file name and file path.\nprint('Total {} test images'.format(len(test_imgs)))\nprint()\nprint(os.listdir(TEST_DIR)[:5])\nprint()\nprint(test_imgs[:5])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 2. Preview the Dataset ","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"idx = 0\nnrows = 3\nncols = 3\nfigsize = (16,16)\nfig, axs = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)\nfor i in range(nrows):\n    for j in range(ncols):\n        axs[i,j].imshow(Image.open(train_imgs[idx]))\n        idx += 1\n        axs[i,j].axes.get_xaxis().set_visible(False)\n        axs[i,j].axes.get_yaxis().set_visible(False)        \nplt.show()        ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 3. Cross-Validation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_set, valid_set = train_test_split(train_imgs, test_size=0.2, random_state=42)\n\ndel train_imgs\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Print train list and validation list.\nprint('Number of training set: {}'.format(len(train_set)))\nprint('Number of validation set: {}'.format(len(valid_set)))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 4. Load Datasets","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### 4.1 DataLoader","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"class dataset(Dataset):\n    def __init__(self, data, transform=None):\n        self.data = data\n        self.transform = transform\n    \n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, idx):\n        if torch.is_tensor(idx):\n            idx = idx.tolist()\n            \n        img_path = self.data[idx]\n        img = Image.open(img_path)\n        if self.transform:\n            img_aug = self.transform(img)\n            \n        label = img_path.split('/')[-1].split('.')[0]\n        if label == 'dog':\n            label = 1\n        elif label == 'cat':\n            label = 0\n        \n        return img_aug, label      \n        ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 4.2. Image Augumentation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"input_size = 224\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\n\ndata_transforms = {\n    'train':\n    transforms.Compose([\n        transforms.RandomResizedCrop(input_size),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor(),\n        transforms.Normalize(mean, std)\n    ]),\n    'val':\n    transforms.Compose([\n        transforms.Resize(input_size),\n        transforms.CenterCrop(input_size),\n        transforms.ToTensor(),\n        transforms.Normalize(mean, std)\n    ])\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Initializing Datasets and Dataloaders...\")\n\n# Create training and validation datasets.\nimage_datasets = {\n    'train': dataset(train_set, transform=data_transforms['train']),\n    'val': dataset(valid_set, transform=data_transforms['val'])\n}\n\nbatch_size = 32\n# Switch to perform multi-process data loading\nnum_workers = multiprocessing.cpu_count()\nprint('num_workers = {}'.format(num_workers))\n\n# Create training and validation dataloaders.\ndataloaders_dict = {\n    'train': DataLoader(image_datasets['train'], batch_size=batch_size, shuffle=True, num_workers=num_workers),\n    'val': DataLoader(image_datasets['val'], batch_size=batch_size, shuffle=False, num_workers=num_workers)\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('{} train data in total'.format(len(image_datasets['train'])))\nprint('{} iters per epoch for train'.format(len(dataloaders_dict['train'])))\nprint()\nprint('{} val data in total'.format(len(image_datasets['val'])))\nprint('{} iters per epoch for val'.format(len(dataloaders_dict['val'])))\nprint()\nprint('Image shape is {}'.format(image_datasets['train'][0][0].shape))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 5. Build Model","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### 5.1 Transfer Model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Models to choose from [resnet, alexnet, vgg, squeezenet, densenet, inception]\nmodel_name = \"resnet\"\n\n# Number of classes in the dataset\nnum_classes = 2\n\n# Number of epochs to train for \nnum_epochs = 20\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# Detect if we have a GPU available\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Set model parameters, requires_grad attribute\ndef set_parameter_requires_grad(model, feature_extracting):\n    if feature_extracting:\n        for param in model.parameters():\n            param.requires_grad = False \n\ndef initialize_model(model_name, num_classes, feature_extract, use_pretrained=True):\n    if model_name == \"resnet\":\n        model_ft = models.resnet18(pretrained=use_pretrained)  # download pretrained model and parameters\n        set_parameter_requires_grad(model_ft, feature_extract) # don't update gradient form pretrained model\n        num_ftrs = model_ft.fc.in_features                     # get last layer dimension\n        model_ft.fc = nn.Linear(num_ftrs, num_classes)         # create new dense layer\n        input_size = 224                                # resnet18's input should be 224\n    return model_ft, input_size","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_ft, input_size = initialize_model(model_name, num_classes, feature_extract, use_pretrained=True)\nprint(model_ft)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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 = optim.Adam(params_to_update, lr = 1e-4, eps = 1e-6)\n# Setup the loss fxn\ncriterion = nn.CrossEntropyLoss()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def adjust_learning_rate(optimizer, epoch):\n#     \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n#     lr = learning_rate * (0.1**(epoch // 30))\n#     for param_group in optimizer.state_dict()['param_groups']:\n#         param_group['lr'] = lr","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 6. Define Train Model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def train_model(model, dataloaders, optimizer, criterion, num_epochs=5):\n    since = time.time()\n    history = {\n        'train_acc': [],\n        'train_loss': [],\n        'val_acc': [],\n        'val_loss': [] \n    }\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        for phase in [\"train\", \"val\"]:\n            running_loss = 0.0\n            running_acc = 0.0\n            if phase == \"train\":\n                model.train()\n            else:\n                model.eval()\n            \n            for inputs, labels in tqdm(dataloaders[phase]):\n                inputs = inputs.to(device)\n                labels = labels.to(device)\n                optimizer.zero_grad()\n                \n                with torch.autograd.set_grad_enabled(phase==\"train\"):\n                    outputs = model(inputs)\n                    loss = criterion(outputs, labels)\n                    _, preds = torch.max(outputs, 1)\n                \n                    if phase == \"train\":\n                        loss.backward()\n                        optimizer.step()\n                \n                running_loss += loss.item() * inputs.size(0) # \n                #running_acc += torch.sum(preds.view(-1) == labels.view(-1).item())\n                running_acc += torch.sum(preds == labels.data)\n                \n            epoch_loss = running_loss / len(dataloaders[phase].dataset)\n            epoch_acc = running_acc / len(dataloaders[phase].dataset)\n            print(\"{} Loss: {:.4f} Acc: {:.4f}\".format(phase, epoch_loss, epoch_acc))\n            \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 == 'val':\n                history['val_acc'].append(epoch_acc)\n                history['val_loss'].append(epoch_loss)\n            if phase == 'train':\n                history['train_acc'].append(epoch_acc)\n                history['train_loss'].append(epoch_loss)\n        \n        print()\n    \n    time_elapsed = time.time() - since\n    print(\"Training compete 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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 7. Run Model","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"### 7.1 Run Training and Validation Step","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Train and evaluate\nmodel_ft, ohist = train_model(model_ft, dataloaders_dict, optimizer, criterion, num_epochs=num_epochs)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 7.2 Visualize Training Results","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_acc = ohist['train_acc']\nval_acc = ohist['val_acc']\ntrain_loss = ohist['train_loss']\nval_loss = ohist['val_loss']\nepochs_range = range(num_epochs)\n\nplt.figure(figsize=(16, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, train_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, train_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()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### 8.3 Save Model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"save_model = True\nif (save_model):\n    save_path = os.path.join(DIR, 'model_save')\n    if not os.path.exists(save_path):\n        os.mkdir(save_path)\n    torch.save(model_ft.state_dict(), save_path + '/resnet18.pth') ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 9. Prediction","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"test_transform = data_transforms['val']\n\nid_list = []\npred_list = []\n\nwith torch.no_grad():\n    for test_path in tqdm(test_imgs):\n        img = Image.open(test_path)\n        img_id = int(test_path.split('/')[-1].split('.')[0])\n        img = test_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() # predict vale\n        \n        id_list.append(img_id)\n        pred_list.append(preds[0])\n        ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## 10. Submission","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"my_submission = pd.DataFrame({'id': id_list, 'label': pred_list})\n\nmy_submission.sort_values(by='id', inplace=True)\nmy_submission.reset_index(drop=True, inplace=True)\n\nmy_submission.to_csv('submission_pytorch_resnet18.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}