{"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","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport torch\nimport glob\nimport torch.nn as nn\nfrom torchvision.transforms import transforms\nfrom torch.utils.data import DataLoader\nfrom torch.optim import Adam\nfrom torch.autograd import Variable\nimport torchvision\nimport pathlib","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:55:06.054567Z","iopub.execute_input":"2022-08-19T14:55:06.055272Z","iopub.status.idle":"2022-08-19T14:55:06.061642Z","shell.execute_reply.started":"2022-08-19T14:55:06.055233Z","shell.execute_reply":"2022-08-19T14:55:06.060309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"! unzip -q /kaggle/input/dogs-vs-cats-redux-kernels-edition/train.zip\n! unzip -q /kaggle/input/dogs-vs-cats-redux-kernels-edition/test.zip","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:55:07.876878Z","iopub.execute_input":"2022-08-19T14:55:07.877960Z","iopub.status.idle":"2022-08-19T14:55:26.787312Z","shell.execute_reply.started":"2022-08-19T14:55:07.877912Z","shell.execute_reply":"2022-08-19T14:55:26.785794Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\n\n\nf=[]\nc=[]\nfor s in os.listdir(\"train\"):\n    a=s.split(\".\")[0]\n    if(a=='cat'):\n        c.append(0)\n    else:\n        c.append(1)\n    f.append(s)\n#df=pd.DataFrame({'name':f,\n               #'category':c})","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:55:30.726624Z","iopub.execute_input":"2022-08-19T14:55:30.728236Z","iopub.status.idle":"2022-08-19T14:55:30.766209Z","shell.execute_reply.started":"2022-08-19T14:55:30.728180Z","shell.execute_reply":"2022-08-19T14:55:30.764740Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"c=torch.tensor(c)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:55:35.850981Z","iopub.execute_input":"2022-08-19T14:55:35.851404Z","iopub.status.idle":"2022-08-19T14:55:35.859395Z","shell.execute_reply.started":"2022-08-19T14:55:35.851369Z","shell.execute_reply":"2022-08-19T14:55:35.857963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(type(c))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:56:56.075496Z","iopub.execute_input":"2022-08-19T14:56:56.076397Z","iopub.status.idle":"2022-08-19T14:56:56.085488Z","shell.execute_reply.started":"2022-08-19T14:56:56.076354Z","shell.execute_reply":"2022-08-19T14:56:56.083433Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(c[0])","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:56:58.762954Z","iopub.execute_input":"2022-08-19T14:56:58.763814Z","iopub.status.idle":"2022-08-19T14:56:58.771081Z","shell.execute_reply.started":"2022-08-19T14:56:58.763770Z","shell.execute_reply":"2022-08-19T14:56:58.769560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tqdm.notebook import tqdm\nimport cv2\nimages = []\nfor imagename in tqdm(os.listdir(\"train\")):\n    \n    image = cv2.imread(\"train/\"+ imagename)\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    image=cv2.resize(image,(128,128))\n    images.append(image)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:57:01.370682Z","iopub.execute_input":"2022-08-19T14:57:01.371141Z","iopub.status.idle":"2022-08-19T14:58:26.622692Z","shell.execute_reply.started":"2022-08-19T14:57:01.371105Z","shell.execute_reply":"2022-08-19T14:58:26.621642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(images[0])\nprint(type(images[0]))","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:58:50.861274Z","iopub.execute_input":"2022-08-19T14:58:50.862483Z","iopub.status.idle":"2022-08-19T14:58:50.871375Z","shell.execute_reply.started":"2022-08-19T14:58:50.862439Z","shell.execute_reply":"2022-08-19T14:58:50.870231Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"d=images\nimages=torch.tensor(images)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T14:58:57.214432Z","iopub.execute_input":"2022-08-19T14:58:57.214889Z","iopub.status.idle":"2022-08-19T15:08:01.869537Z","shell.execute_reply.started":"2022-08-19T14:58:57.214839Z","shell.execute_reply":"2022-08-19T15:08:01.868216Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(type(images[0]))\nprint(images[0])","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:13.149383Z","iopub.execute_input":"2022-08-19T15:08:13.149760Z","iopub.status.idle":"2022-08-19T15:08:13.161898Z","shell.execute_reply.started":"2022-08-19T15:08:13.149728Z","shell.execute_reply":"2022-08-19T15:08:13.160554Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:20.858280Z","iopub.execute_input":"2022-08-19T15:08:20.861252Z","iopub.status.idle":"2022-08-19T15:08:20.871223Z","shell.execute_reply.started":"2022-08-19T15:08:20.861184Z","shell.execute_reply":"2022-08-19T15:08:20.869581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images=images.permute(0,3,1,2)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:22.928999Z","iopub.execute_input":"2022-08-19T15:08:22.929833Z","iopub.status.idle":"2022-08-19T15:08:22.936617Z","shell.execute_reply.started":"2022-08-19T15:08:22.929669Z","shell.execute_reply":"2022-08-19T15:08:22.935122Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:26.963918Z","iopub.execute_input":"2022-08-19T15:08:26.964697Z","iopub.status.idle":"2022-08-19T15:08:26.971089Z","shell.execute_reply.started":"2022-08-19T15:08:26.964658Z","shell.execute_reply":"2022-08-19T15:08:26.970093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nx_train,x_test,y_train,y_test=train_test_split(images,c,test_size=0.3)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:30.084116Z","iopub.execute_input":"2022-08-19T15:08:30.084969Z","iopub.status.idle":"2022-08-19T15:08:34.524761Z","shell.execute_reply.started":"2022-08-19T15:08:30.084929Z","shell.execute_reply":"2022-08-19T15:08:34.523377Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ConvNet(nn.Module):\n    def __init__(self,num_classes=2):\n        super(ConvNet,self).__init__()\n        \n        #Output size after convolution filter\n        #((w-f+2P)/s) +1\n        \n        \n        self.conv1=nn.Conv2d(in_channels=3,out_channels=12,kernel_size=3,stride=1,padding=1)\n        #Shape= (12,128,128)\n        self.bn1=nn.BatchNorm2d(num_features=12)\n      \n        self.relu1=nn.ReLU()\n       \n        self.pool=nn.MaxPool2d(kernel_size=2)\n        #Reduce the image size be factor 2\n        #Shape= (12,64,64)\n        \n        \n        self.conv2=nn.Conv2d(in_channels=12,out_channels=20,kernel_size=3,stride=1,padding=1)\n        #Shape= (,20,64,64)\n        self.relu2=nn.ReLU()\n        \n        \n        \n        \n        self.conv3=nn.Conv2d(in_channels=20,out_channels=32,kernel_size=3,stride=1,padding=1)\n        \n        self.bn3=nn.BatchNorm2d(num_features=32)\n        \n        self.relu3=nn.ReLU()\n        \n        \n        \n        self.fc=nn.Linear(in_features=64* 64 * 32,out_features=num_classes)\n        \n    def forward(self,input):\n        output=self.conv1(input)\n        output=self.bn1(output)\n        output=self.relu1(output)\n            \n        output=self.pool(output)\n            \n        output=self.conv2(output)\n        output=self.relu2(output)\n            \n        output=self.conv3(output)\n        output=self.bn3(output)\n        output=self.relu3(output)\n            \n            \n           \n            \n        output=output.view(-1,32*64*64)\n            \n            \n        output=self.fc(output)\n            \n        return output\n            ","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:38.229456Z","iopub.execute_input":"2022-08-19T15:08:38.230254Z","iopub.status.idle":"2022-08-19T15:08:38.243568Z","shell.execute_reply.started":"2022-08-19T15:08:38.230208Z","shell.execute_reply":"2022-08-19T15:08:38.242225Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model=ConvNet(num_classes=2)","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:08:45.081070Z","iopub.execute_input":"2022-08-19T15:08:45.081519Z","iopub.status.idle":"2022-08-19T15:08:45.094868Z","shell.execute_reply.started":"2022-08-19T15:08:45.081483Z","shell.execute_reply":"2022-08-19T15:08:45.093830Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"optimizer=Adam(model.parameters(),lr=0.001,weight_decay=0.0001)\nloss_function=nn.CrossEntropyLoss()","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:09:24.543365Z","iopub.execute_input":"2022-08-19T15:09:24.544440Z","iopub.status.idle":"2022-08-19T15:09:24.550167Z","shell.execute_reply.started":"2022-08-19T15:09:24.544402Z","shell.execute_reply":"2022-08-19T15:09:24.549028Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_epochs=10","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:09:26.915406Z","iopub.execute_input":"2022-08-19T15:09:26.916420Z","iopub.status.idle":"2022-08-19T15:09:26.925176Z","shell.execute_reply.started":"2022-08-19T15:09:26.916371Z","shell.execute_reply":"2022-08-19T15:09:26.923814Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:09:29.991449Z","iopub.execute_input":"2022-08-19T15:09:29.992089Z","iopub.status.idle":"2022-08-19T15:09:29.999231Z","shell.execute_reply.started":"2022-08-19T15:09:29.992054Z","shell.execute_reply":"2022-08-19T15:09:29.997840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x_train","metadata":{"execution":{"iopub.status.busy":"2022-08-19T15:09:34.020273Z","iopub.execute_input":"2022-08-19T15:09:34.021882Z","iopub.status.idle":"2022-08-19T15:09:34.038305Z","shell.execute_reply.started":"2022-08-19T15:09:34.021794Z","shell.execute_reply":"2022-08-19T15:09:34.037037Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_accuracy=0.0\n\nfor epoch in range(num_epochs):\n    \n    #Evaluation and training on training dataset\n    model.train()\n    train_accuracy=0.0\n    train_loss=0.0\n    \n    for i, (images,labels) in enumerate(zip(x_train,y_train)):\n\n            \n        optimizer.zero_grad()\n        f=images.float()\n        f=f.unsqueeze(0)\n        outputs=model(f)\n        labels=labels.unsqueeze(0)\n        loss=loss_function(outputs,labels)\n        loss.backward()\n        optimizer.step()\n        \n        \n        train_loss+= loss.cpu().data*images.size(0)\n        _,prediction=torch.max(outputs.data,1)\n        \n        train_accuracy+=int(torch.sum(prediction==labels.data))\n        \n    train_accuracy=train_accuracy/len(x_train)\n    train_loss=train_loss/len(x_train)\n    \n    \n    # Evaluation on testing dataset\n    model.eval()\n    test_accuracy=0.0\n    for i, (images,labels) in enumerate(zip(x_test,y_test)):\n\n        f=images.float()\n        f=f.unsqueeze(0)    \n        outputs=model(f)\n        _,prediction=torch.max(outputs.data,1)\n        test_accuracy+=int(torch.sum(prediction==labels.data))\n    \n    test_accuracy=test_accuracy/len(x_test)\n    \n    \n    print('Epoch: '+str(epoch)+' Train Loss: '+str(train_loss)+' Train Accuracy: '+str(train_accuracy)+' Test Accuracy: '+str(test_accuracy))\n    \n    #Save the best model\n    if test_accuracy>best_accuracy:\n        torch.save(model.state_dict(),'best_checkpoint.model')\n        best_accuracy=test_accuracy\n    \n       ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}