{"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":"2022-01-25T17:43:48.436669Z","iopub.execute_input":"2022-01-25T17:43:48.436977Z","iopub.status.idle":"2022-01-25T17:43:48.451090Z","shell.execute_reply.started":"2022-01-25T17:43:48.436947Z","shell.execute_reply":"2022-01-25T17:43:48.450201Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# In this notebook, I'm going to use pytorch\nimport torch\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\nimport torchvision\nfrom torchvision import transforms\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset, DataLoader, ConcatDataset\nimport zipfile\nfrom PIL import Image\nfrom torch.utils.data import Subset\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\n\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:43:48.453027Z","iopub.execute_input":"2022-01-25T17:43:48.453914Z","iopub.status.idle":"2022-01-25T17:43:48.465134Z","shell.execute_reply.started":"2022-01-25T17:43:48.453873Z","shell.execute_reply":"2022-01-25T17:43:48.464119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = './train'\ntest_dir = './test1'","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:43:48.466439Z","iopub.execute_input":"2022-01-25T17:43:48.466685Z","iopub.status.idle":"2022-01-25T17:43:48.478468Z","shell.execute_reply.started":"2022-01-25T17:43:48.466658Z","shell.execute_reply":"2022-01-25T17:43:48.477424Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# reading input files\ntrain_files = zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip')\ntrain_files.extractall()\ntest_files = zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip')\ntest_files.extractall()","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:43:48.479653Z","iopub.execute_input":"2022-01-25T17:43:48.480022Z","iopub.status.idle":"2022-01-25T17:44:08.604525Z","shell.execute_reply.started":"2022-01-25T17:43:48.479988Z","shell.execute_reply":"2022-01-25T17:44:08.603785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_files = os.listdir(train_dir)\ntest_files = os.listdir('./test1')\n\nprint(f\"train data len {len(os.listdir(train_dir))}\")\nprint(f\"test data len {len(os.listdir('./test1'))}\")","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.606778Z","iopub.execute_input":"2022-01-25T17:44:08.607230Z","iopub.status.idle":"2022-01-25T17:44:08.676999Z","shell.execute_reply.started":"2022-01-25T17:44:08.607196Z","shell.execute_reply":"2022-01-25T17:44:08.676082Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lets create a dataset class\nclass MyDogCatDataset(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        \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        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]","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.678357Z","iopub.execute_input":"2022-01-25T17:44:08.678942Z","iopub.status.idle":"2022-01-25T17:44:08.689826Z","shell.execute_reply.started":"2022-01-25T17:44:08.678891Z","shell.execute_reply":"2022-01-25T17:44:08.688851Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_transform = transforms.Compose([\n    transforms.Resize(256),\n    transforms.ColorJitter(),\n    transforms.RandomCrop(224),\n    transforms.RandomHorizontalFlip(),\n    transforms.Resize(128),\n    transforms.ToTensor()\n])","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.691052Z","iopub.execute_input":"2022-01-25T17:44:08.691316Z","iopub.status.idle":"2022-01-25T17:44:08.702496Z","shell.execute_reply.started":"2022-01-25T17:44:08.691287Z","shell.execute_reply":"2022-01-25T17:44:08.701580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat_files = [tf for tf in train_files if 'cat' in tf]\nprint(len(cat_files))\ndog_files = [tf for tf in train_files if 'dog' in tf]\nprint(len(dog_files))","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.703891Z","iopub.execute_input":"2022-01-25T17:44:08.704215Z","iopub.status.idle":"2022-01-25T17:44:08.721672Z","shell.execute_reply.started":"2022-01-25T17:44:08.704176Z","shell.execute_reply":"2022-01-25T17:44:08.720768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# our dataset is balanced. let's load with our dataloader class\ncats = MyDogCatDataset(cat_files, train_dir, transform=data_transform)\ndogs = MyDogCatDataset(dog_files, train_dir, transform=data_transform)","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.722964Z","iopub.execute_input":"2022-01-25T17:44:08.723984Z","iopub.status.idle":"2022-01-25T17:44:08.732462Z","shell.execute_reply.started":"2022-01-25T17:44:08.723942Z","shell.execute_reply":"2022-01-25T17:44:08.731645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_data = MyDogCatDataset(test_files, test_dir, transform=data_transform)\ntest_data","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.734150Z","iopub.execute_input":"2022-01-25T17:44:08.734503Z","iopub.status.idle":"2022-01-25T17:44:08.746991Z","shell.execute_reply.started":"2022-01-25T17:44:08.734463Z","shell.execute_reply":"2022-01-25T17:44:08.746021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# concatenate two datasets\ncatdogs = ConcatDataset([cats, dogs])\ncatdogs","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.748366Z","iopub.execute_input":"2022-01-25T17:44:08.748806Z","iopub.status.idle":"2022-01-25T17:44:08.761585Z","shell.execute_reply.started":"2022-01-25T17:44:08.748764Z","shell.execute_reply":"2022-01-25T17:44:08.760625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load data in DataLoader class -> this is used to make the whole dataset into batch wise data\ntrain_loader = DataLoader(catdogs, batch_size=100, shuffle=True, num_workers=4)\nprint(f\"input data len: {len(catdogs)}\")\nprint(len(train_loader))\ntrain_loader\n","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.763046Z","iopub.execute_input":"2022-01-25T17:44:08.763349Z","iopub.status.idle":"2022-01-25T17:44:08.778583Z","shell.execute_reply.started":"2022-01-25T17:44:08.763322Z","shell.execute_reply":"2022-01-25T17:44:08.777668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_loader = DataLoader(test_data, batch_size=100, shuffle=True, num_workers=4)\ntest_loader","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.781326Z","iopub.execute_input":"2022-01-25T17:44:08.781838Z","iopub.status.idle":"2022-01-25T17:44:08.791242Z","shell.execute_reply.started":"2022-01-25T17:44:08.781790Z","shell.execute_reply":"2022-01-25T17:44:08.790147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def image_convert(img):\n    img = img.clone().cpu().numpy()\n    img = img.transpose(1,2,0)\n    std = [0.5,0.5,0.5]\n    mean = [0.5,0.5,0.5]\n    img = img*std + mean\n    return img","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.794169Z","iopub.execute_input":"2022-01-25T17:44:08.794586Z","iopub.status.idle":"2022-01-25T17:44:08.801052Z","shell.execute_reply.started":"2022-01-25T17:44:08.794525Z","shell.execute_reply":"2022-01-25T17:44:08.800392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_10():\n    iter_ = iter(test_loader)\n    images,labels = next(iter_)\n    an_ = {'0':'cat','1':'dog'}\n\n    plt.figure(figsize=(20,10))\n    for idx in range(10):\n        plt.subplot(2,5,idx+1)\n        img = image_convert(images[idx])\n        label = labels[idx]\n        plt.imshow(img)\n        print(f'shape of the image is : {img.shape}')\n        plt.title(an_[str(label.numpy())])\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.802238Z","iopub.execute_input":"2022-01-25T17:44:08.802628Z","iopub.status.idle":"2022-01-25T17:44:08.815769Z","shell.execute_reply.started":"2022-01-25T17:44:08.802590Z","shell.execute_reply":"2022-01-25T17:44:08.815084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plot_10()\n","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:08.817013Z","iopub.execute_input":"2022-01-25T17:44:08.817429Z","iopub.status.idle":"2022-01-25T17:44:12.297908Z","shell.execute_reply.started":"2022-01-25T17:44:08.817389Z","shell.execute_reply":"2022-01-25T17:44:12.296918Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda\") if torch.cuda.is_available() else torch.device(\"cpu\")\ndevice","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.299388Z","iopub.execute_input":"2022-01-25T17:44:12.299669Z","iopub.status.idle":"2022-01-25T17:44:12.306740Z","shell.execute_reply.started":"2022-01-25T17:44:12.299635Z","shell.execute_reply":"2022-01-25T17:44:12.306122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# now we are going to create a model with training dataset\nclass ConvolutionalNetwork(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.conv1 = nn.Conv2d(3, 6, 3, 1)\n        self.conv2 = nn.Conv2d(6, 16, 3, 1)\n        self.fc1 = nn.Linear(30*30*16, 120)\n        self.fc2 = nn.Linear(120, 84)\n        self.fc3 = nn.Linear(84,10)\n\n    def forward(self, X):\n        X = F.relu(self.conv1(X))\n        X = F.max_pool2d(X, 2, 2)\n        X = F.relu(self.conv2(X))\n        X = F.max_pool2d(X, 2, 2)\n        X = X.view(-1, 30*30*16)\n        X = F.relu(self.fc1(X))\n        X = F.relu(self.fc2(X))\n        X = self.fc3(X)\n        return F.log_softmax(X, dim=1)\n\n","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.307920Z","iopub.execute_input":"2022-01-25T17:44:12.308309Z","iopub.status.idle":"2022-01-25T17:44:12.319107Z","shell.execute_reply.started":"2022-01-25T17:44:12.308276Z","shell.execute_reply":"2022-01-25T17:44:12.318116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# now our CNN is ready\ntorch.manual_seed(42)\nmodel = ConvolutionalNetwork()\nif torch.cuda.is_available():\n    model.cuda()\nmodel","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.320812Z","iopub.execute_input":"2022-01-25T17:44:12.321810Z","iopub.status.idle":"2022-01-25T17:44:12.349710Z","shell.execute_reply.started":"2022-01-25T17:44:12.321762Z","shell.execute_reply":"2022-01-25T17:44:12.348679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_parameters(model):\n    params = [p.numel() for p in model.parameters() if p.requires_grad]\n    for item in params:\n        print(f'{item:>6}')\n    print(f'______\\n{sum(params):>6}')","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.351124Z","iopub.execute_input":"2022-01-25T17:44:12.351431Z","iopub.status.idle":"2022-01-25T17:44:12.356721Z","shell.execute_reply.started":"2022-01-25T17:44:12.351392Z","shell.execute_reply":"2022-01-25T17:44:12.356015Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"count_parameters(model)","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.357906Z","iopub.execute_input":"2022-01-25T17:44:12.358140Z","iopub.status.idle":"2022-01-25T17:44:12.376182Z","shell.execute_reply.started":"2022-01-25T17:44:12.358112Z","shell.execute_reply":"2022-01-25T17:44:12.375236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# let's define lossfunction and optimizer\ncriterion = nn.CrossEntropyLoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=0.001)","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.377345Z","iopub.execute_input":"2022-01-25T17:44:12.378092Z","iopub.status.idle":"2022-01-25T17:44:12.384446Z","shell.execute_reply.started":"2022-01-25T17:44:12.378058Z","shell.execute_reply":"2022-01-25T17:44:12.383493Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(train_loader)","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:44:12.385898Z","iopub.execute_input":"2022-01-25T17:44:12.386792Z","iopub.status.idle":"2022-01-25T17:44:12.397750Z","shell.execute_reply.started":"2022-01-25T17:44:12.386748Z","shell.execute_reply":"2022-01-25T17:44:12.396731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time\nstart_time = time.time()\n\nepochs = 3\ntrain_losses = []\ntest_losses = []\ntrain_correct = []\ntest_correct = []\n\nfor i in range(epochs):\n    trn_corr = 0\n    tst_corr = 0\n    \n    # Run the training batches\n    for b, (X_train, y_train) in enumerate(train_loader):\n        b+=1\n        X_train, y_train = X_train.to(device), y_train.to(device)\n        print(f\" {b} shape of X_train : {X_train.shape}\")\n        # Apply the model\n        y_pred = model(X_train)  # we don't flatten X-train here\n        loss = criterion(y_pred, y_train)\n \n        # Tally the number of correct predictions\n        predicted = torch.max(y_pred.data, 1)[1]\n        batch_corr = (predicted == y_train).sum()\n        trn_corr += batch_corr\n        \n        # Update parameters\n        optimizer.zero_grad()\n        loss.backward()\n        optimizer.step()\n        \n        # Print interim results\n        if b%100 == 0:\n            print(f'epoch: {i:2}  batch: {b:4} [{10*b:6}/60000]  loss: {loss.item():10.8f}  \\\naccuracy: {trn_corr.item()*100/(10*b):7.3f}%')\n        \n    train_losses.append(loss.item())\n    train_correct.append(trn_corr.item())\n        \n    # Run the testing batches\n    with torch.no_grad():\n        for b, (X_test, y_test) in enumerate(test_loader):\n            X_test, y_test = X_test.to(device), y_test.to(device)\n\n            # Apply the model\n            y_val = model(X_test)\n\n            # Tally the number of correct predictions\n            predicted = torch.max(y_val.data, 1)[1] \n            tst_corr += (predicted == y_test).sum()\n            \n    loss = criterion(y_val, y_test)\n    test_losses.append(loss)\n    test_correct.append(tst_corr)\n        \nprint(f'\\nDuration: {time.time() - start_time:.0f} seconds') # print the time elapsed            ","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2022-01-25T17:44:12.399989Z","iopub.execute_input":"2022-01-25T17:44:12.400296Z","iopub.status.idle":"2022-01-25T17:52:03.693509Z","shell.execute_reply.started":"2022-01-25T17:44:12.400259Z","shell.execute_reply":"2022-01-25T17:52:03.689423Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Plotting the Loss and Accuracy\nplt.plot(train_losses, label='training loss')\nplt.plot(test_losses, label='validation loss')\nplt.title('Loss at the end of each epoch')\nplt.legend();","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:52:03.698111Z","iopub.execute_input":"2022-01-25T17:52:03.699919Z","iopub.status.idle":"2022-01-25T17:52:04.346874Z","shell.execute_reply.started":"2022-01-25T17:52:03.699778Z","shell.execute_reply":"2022-01-25T17:52:04.345570Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot([t/600 for t in train_correct], label='training accuracy')\nplt.plot([t/100 for t in test_correct], label='validation accuracy')\nplt.title('Accuracy at the end of each epoch')\nplt.legend();","metadata":{"execution":{"iopub.status.busy":"2022-01-25T17:52:04.348336Z","iopub.execute_input":"2022-01-25T17:52:04.348657Z","iopub.status.idle":"2022-01-25T17:52:04.713994Z","shell.execute_reply.started":"2022-01-25T17:52:04.348628Z","shell.execute_reply":"2022-01-25T17:52:04.709927Z"},"trusted":true},"execution_count":null,"outputs":[]}]}