{"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        \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-02-02T07:14:21.467386Z","iopub.execute_input":"2022-02-02T07:14:21.468200Z","iopub.status.idle":"2022-02-02T07:14:21.503144Z","shell.execute_reply.started":"2022-02-02T07:14:21.468102Z","shell.execute_reply":"2022-02-02T07:14:21.502417Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nimport glob\nfrom PIL import Image\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader, Dataset\nfrom torchvision import datasets, transforms\nnp.random.seed(0)\ntorch.manual_seed(0)\ntorch.cuda.manual_seed(0)\n\nimport wandb\nfrom kaggle_secrets import UserSecretsClient\nuser_secrets = UserSecretsClient()\nsecret_value_0 = user_secrets.get_secret(\"CatsVsDogs\")\n\nwandb.login(key=secret_value_0)\nwandb.init(project='DogsVsCatsCNN', save_code=True)","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:21.504914Z","iopub.execute_input":"2022-02-02T07:14:21.505507Z","iopub.status.idle":"2022-02-02T07:14:33.332859Z","shell.execute_reply.started":"2022-02-02T07:14:21.505463Z","shell.execute_reply":"2022-02-02T07:14:33.332079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = 'train'\ntest_dir = 'test'\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip') as train_zip:\n    train_zip.extractall('')\n    \nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip') as test_zip:\n    test_zip.extractall('')\ntrain_list = glob.glob(os.path.join(train_dir,'*.jpg'))\ntest_list = glob.glob(os.path.join(test_dir, '*.jpg'))\nprint(f\"Train Data: {len(train_list)}\")\nprint(f\"Test Data: {len(test_list)}\")","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:33.334744Z","iopub.execute_input":"2022-02-02T07:14:33.335016Z","iopub.status.idle":"2022-02-02T07:14:53.946606Z","shell.execute_reply.started":"2022-02-02T07:14:33.334980Z","shell.execute_reply":"2022-02-02T07:14:53.945642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = [path.split('/')[-1].split('.')[0] for path in train_list]","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:53.951909Z","iopub.execute_input":"2022-02-02T07:14:53.953826Z","iopub.status.idle":"2022-02-02T07:14:54.662516Z","shell.execute_reply.started":"2022-02-02T07:14:53.953757Z","shell.execute_reply":"2022-02-02T07:14:54.661776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"random_idx = np.random.randint(1, len(train_list), size=9)\nfig, axes = plt.subplots(3, 3, figsize=(16, 12))\n\nfor idx, ax in enumerate(axes.ravel()):\n    img = Image.open(train_list[idx])\n    ax.set_title(labels[idx])\n    ax.imshow(img)","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:54.663761Z","iopub.execute_input":"2022-02-02T07:14:54.664012Z","iopub.status.idle":"2022-02-02T07:14:57.780301Z","shell.execute_reply.started":"2022-02-02T07:14:54.663980Z","shell.execute_reply":"2022-02-02T07:14:57.779416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_list, valid_list = train_test_split(train_list, \n                                          test_size=0.2,\n                                          stratify=labels,\n                                          random_state=0)\nprint(f\"Train Data: {len(train_list)}\")\nprint(f\"Validation Data: {len(valid_list)}\")\nprint(f\"Test Data: {len(test_list)}\")","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:57.782152Z","iopub.execute_input":"2022-02-02T07:14:57.782433Z","iopub.status.idle":"2022-02-02T07:14:58.457418Z","shell.execute_reply.started":"2022-02-02T07:14:57.782381Z","shell.execute_reply":"2022-02-02T07:14:58.456508Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_transforms = transforms.Compose([\n        transforms.Resize(128), # makes it easier for the GPU\n        transforms.RandomResizedCrop(112),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor()])\n\nval_transforms = transforms.Compose([\n        transforms.Resize(128),\n        transforms.CenterCrop(112),\n        transforms.ToTensor()])\n\n\ntest_transforms = transforms.Compose([\n        transforms.Resize(128),\n        transforms.CenterCrop(112),\n        transforms.ToTensor()])","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:58.461822Z","iopub.execute_input":"2022-02-02T07:14:58.469621Z","iopub.status.idle":"2022-02-02T07:14:59.035697Z","shell.execute_reply.started":"2022-02-02T07:14:58.469574Z","shell.execute_reply":"2022-02-02T07:14:59.034604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CatsDogsDataset(Dataset):\n    def __init__(self, file_list, transform=None):\n        self.file_list = file_list\n        self.transform = transform\n        self.filelength = len(file_list)\n\n    def __len__(self):\n        return self.filelength\n\n    def __getitem__(self, idx):\n        img_path = self.file_list[idx]\n        img = Image.open(img_path)\n        img_transformed = self.transform(img)\n        label = img_path.split(\"/\")[-1].split(\".\")[0]\n        label = 1 if label == \"dog\" else 0\n        return img_transformed, label","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:59.037073Z","iopub.execute_input":"2022-02-02T07:14:59.037329Z","iopub.status.idle":"2022-02-02T07:14:59.679395Z","shell.execute_reply.started":"2022-02-02T07:14:59.037294Z","shell.execute_reply":"2022-02-02T07:14:59.678669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_data = CatsDogsDataset(train_list, transform=train_transforms)\nvalid_data = CatsDogsDataset(valid_list, transform=test_transforms)\ntest_data = CatsDogsDataset(test_list, transform=test_transforms)","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:14:59.682000Z","iopub.execute_input":"2022-02-02T07:14:59.682240Z","iopub.status.idle":"2022-02-02T07:15:00.257056Z","shell.execute_reply.started":"2022-02-02T07:14:59.682206Z","shell.execute_reply":"2022-02-02T07:15:00.256385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batch_size = 32\ntrain_loader = DataLoader(dataset=train_data, batch_size=batch_size, shuffle=True)\nvalid_loader = DataLoader(dataset=valid_data, batch_size=batch_size, shuffle=False)\ntest_loader = DataLoader(dataset=test_data, batch_size=batch_size, shuffle=False)","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:15:00.258303Z","iopub.execute_input":"2022-02-02T07:15:00.258579Z","iopub.status.idle":"2022-02-02T07:15:00.887037Z","shell.execute_reply.started":"2022-02-02T07:15:00.258541Z","shell.execute_reply":"2022-02-02T07:15:00.886311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def init_weights(m):\n    if isinstance(m, nn.Linear):\n        torch.nn.init.xavier_normal_(m.weight, nn.init.calculate_gain('relu'))\n        torch.nn.init.constant_(m.bias, 0)","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:15:00.890256Z","iopub.execute_input":"2022-02-02T07:15:00.890511Z","iopub.status.idle":"2022-02-02T07:15:01.412737Z","shell.execute_reply.started":"2022-02-02T07:15:00.890481Z","shell.execute_reply":"2022-02-02T07:15:01.412036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class AlexNet(nn.Module):\n    \n    def __init__(self, num_classes: int):\n        super(AlexNet, self).__init__()\n        \n        self.feature_extr = nn.Sequential(\n        #First convolutional layer\n            nn.Conv2d(in_channels=3, out_channels= 96, kernel_size= 11, stride=4, padding = 2, bias = False),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=3, stride=2, padding = 0),\n        \n        #Second convolutional layer\n            nn.Conv2d(in_channels=96, out_channels=256, kernel_size=5, stride= 1, padding= 2, bias = False),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=3, stride=2, padding = 0),\n        \n        #Third convolutional layer\n            nn.Conv2d(in_channels=256, out_channels=384, kernel_size=3, stride= 1, padding= 1, bias = False),\n            nn.ReLU(inplace=True),\n            \n        #Forth convolutional layer\n            nn.Conv2d(in_channels=384, out_channels=384, kernel_size=3, stride=1, padding=1, bias = False),\n            nn.ReLU(inplace=True),\n            \n        #Fifth convolutional layer\n            nn.Conv2d(in_channels=384, out_channels=256, kernel_size=3, stride=1, padding=1, bias = False),\n            nn.ReLU(inplace=True),\n            nn.MaxPool2d(kernel_size=3, stride=2, padding = 0),\n        )\n        \n        \n        self.linear = nn.Sequential(\n        #First fully connected layer\n            nn.Linear(in_features = 1024, out_features = 4096),\n            nn.ReLU(inplace = True),\n            nn.Dropout(p = 0.5),\n            \n        #Second\n            nn.Linear(in_features = 4096, out_features = 4096),\n            nn.ReLU(inplace = True),\n            nn.Dropout(p = 0.5),\n        \n        #Third\n            nn.Linear(in_features = 4096 , out_features = 2),\n        )\n    \n    def forward(self, x) -> torch.Tensor:\n        x = self.feature_extr(x)\n        \n        x = x.reshape(x.shape[0], -1)\n        \n        x = self.linear(x)\n        return x","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:15:01.414172Z","iopub.execute_input":"2022-02-02T07:15:01.414454Z","iopub.status.idle":"2022-02-02T07:15:01.963798Z","shell.execute_reply.started":"2022-02-02T07:15:01.414416Z","shell.execute_reply":"2022-02-02T07:15:01.963103Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = AlexNet(2)\n\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-3)\ncriterion = nn.CrossEntropyLoss()","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:15:01.964975Z","iopub.execute_input":"2022-02-02T07:15:01.965211Z","iopub.status.idle":"2022-02-02T07:15:02.701121Z","shell.execute_reply.started":"2022-02-02T07:15:01.965178Z","shell.execute_reply":"2022-02-02T07:15:02.700302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)","metadata":{"execution":{"iopub.status.busy":"2022-02-02T07:15:02.702489Z","iopub.execute_input":"2022-02-02T07:15:02.702748Z","iopub.status.idle":"2022-02-02T07:15:06.579794Z","shell.execute_reply.started":"2022-02-02T07:15:02.702713Z","shell.execute_reply":"2022-02-02T07:15:06.579067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_epochs = 50\n\nfor epoch in range(num_epochs):\n    \n    training_loss = 0\n    total = 0\n    model.train()\n    for X, y in train_loader:\n        X = X.to(device)\n        y = y.to(device)\n        optimizer.zero_grad()\n\n        y_pred = model(X)\n        loss = criterion(y_pred, y)\n\n        loss.backward()\n        optimizer.step()\n\n        training_loss += loss.item()\n        _, predicted = torch.max(y_pred, 1)\n        total += int(predicted.eq(y).sum().item())\n\n    wandb.log({\n            'training_loss': training_loss,\n            'training_accuracy': total / len(train_list)\n    })\n    \n    with torch.no_grad():\n        validation_loss = 0\n        total = 0\n        for X, y in valid_loader:\n            X = X.to(device)\n            y = y.to(device)\n\n            y_pred = model(X)\n            _, predicted = torch.max(y_pred, 1)\n            loss = criterion(y_pred, y)\n            validation_loss += loss.item()\n            \n            total += int(predicted.eq(y).sum().item())\n\n\n        wandb.log({\n                'validation_loss': validation_loss,\n                'validation_accuracy': total / len(valid_list)\n        })\n    ","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-02-02T07:15:06.581239Z","iopub.execute_input":"2022-02-02T07:15:06.581670Z","iopub.status.idle":"2022-02-02T08:39:23.793948Z","shell.execute_reply.started":"2022-02-02T07:15:06.581633Z","shell.execute_reply":"2022-02-02T08:39:23.793085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torch.save(model.state_dict(), 'my_model.pt')","metadata":{"execution":{"iopub.status.busy":"2022-02-02T12:11:35.238542Z","iopub.status.idle":"2022-02-02T12:11:35.239541Z","shell.execute_reply.started":"2022-02-02T12:11:35.239218Z","shell.execute_reply":"2022-02-02T12:11:35.239249Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}