{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\n\n%matplotlib inline\n%config InlineBackend.figure_format = 'retina'\n\nimport matplotlib.pyplot as plt\n\nimport torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# import module we'll need to import our custom module\nfrom shutil import copyfile\n\n# copy our file into the working directory (make sure it has .py suffix)\ncopyfile(src = \"../input/view-class/view_helper.py\", dst = \"../working/view_helper.py\")\n\n# import all our functions\nimport view_helper as helper\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"data_dir = '../input/dogs-vs-cats-for-pytorch/cat_dog_data/Cat_Dog_data'\n\n# TODO: Define transforms for the training data and testing data\ntrain_transforms = transforms.Compose([transforms.RandomRotation(30),\n                                       transforms.RandomResizedCrop(224),\n                                       transforms.RandomHorizontalFlip(),\n                                       transforms.ToTensor(),\n                                       transforms.Normalize([0.485, 0.456, 0.406],\n                                                            [0.229, 0.224, 0.225])])\n\ntest_transforms = transforms.Compose([transforms.Resize(255),\n                                      transforms.CenterCrop(224),\n                                      transforms.ToTensor(),\n                                      transforms.Normalize([0.485, 0.456, 0.406],\n                                                           [0.229, 0.224, 0.225])])\n\n# Pass transforms in here, then run the next cell to see how the transforms look\ntrain_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)\ntest_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)\n\ntrainloader = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)\ntestloader = torch.utils.data.DataLoader(test_data, batch_size=64)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"203d37086a4b0490b5e49702ee74eb19fdc07e4c"},"cell_type":"code","source":"# change this to the trainloader or testloader \ndata_iter = iter(trainloader)\n\nimages, labels = next(data_iter)\nfig, axes = plt.subplots(figsize=(10,10), ncols=4)\nfor ii in range(4):\n    ax = axes[ii]\n    helper.imshow(images[ii], ax=ax, normalize=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3d3e4841382ae90e7dfb166c5d869c879411c84c"},"cell_type":"code","source":"model = models.densenet121(pretrained=True)\n\n# Freeze parameters so we don't backprop through them\nfor param in model.parameters():\n    param.requires_grad = False\n    \nmodel.classifier = nn.Sequential(nn.Linear(1024, 256),\n                                 nn.ReLU(),\n                                 nn.Dropout(0.2),\n                                 nn.Linear(256, 2),\n                                 nn.LogSoftmax(dim=1))\n\ncriterion = nn.NLLLoss()\n\n# Only train the classifier parameters, feature parameters are frozen\noptimizer = optim.Adam(model.classifier.parameters(), lr=0.003)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"38de568fe1b521d132888fd4a7922a047daf0a9e"},"cell_type":"code","source":"print(\"Our model: \\n\\n\", model, '\\n')\nprint(\"The state dict keys: \\n\\n\", model.state_dict().keys())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"50554cb363cd2af121050f73ad1950cef37ecbaa"},"cell_type":"code","source":"state_dict = torch.load('../input/cat-dog-dense121-local/cat_dog_dense121_local.pth')\nprint(state_dict.keys())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0f564798632d808a960449136270d01f50a9f240"},"cell_type":"code","source":"model.load_state_dict(state_dict)\nmodel","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"28f98c0e1ab2da6f5294f105fb6b26906d5b0007"},"cell_type":"code","source":"# change this to the trainloader or testloader \ndata_iter = iter(testloader)\n\nimages, labels = next(data_iter)\nfig, axes = plt.subplots(figsize=(10,10), ncols=4)\nfor ii in range(4):\n    ax = axes[ii]\n    helper.imshow(images[ii], ax=ax, normalize=False)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"fb1a31390976e073afc40d74443040d3a148db29"},"cell_type":"markdown","source":"## Test the Network"},{"metadata":{"trusted":true,"_uuid":"dbab1f1e1447efef2c03272a2164fa9a3158e802"},"cell_type":"code","source":"model.to('cpu')\nmodel.eval()\n\ndata_iter = iter(testloader)\n\nimages, labels = next(data_iter)\nfig, axes = plt.subplots(figsize=(10,10), ncols=4)\n\nfor ii in range(4):\n    ax = axes[ii]\n    helper.imshow(images[ii], ax=ax, normalize=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4166fd15c093c3fe0c765b8be329d0d6394209ad"},"cell_type":"code","source":"with torch.no_grad():\n    output = model.forward(images)\n\nps = torch.exp(output)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ec0306346d9e625faf760ed0607f5d1b7d89aedc"},"cell_type":"code","source":"random_img = np.random.randint(64, size=1)[0]\nrandom_img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"d1185e667c77b5d6215bb3c230db6e5730fc5b46"},"cell_type":"code","source":"# get the probability\nprobability = ps[random_img].data.numpy().squeeze()\nprobability","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7a2c69429d8f05311c4d5f00c220752553c939c0"},"cell_type":"code","source":"helper.imshow(images[random_img], normalize=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5b1864ae370475c7774bbf1ee8068f2f35f83c70"},"cell_type":"code","source":"ind = np.arange(2)\nlabels = ['Cat', 'Dog',]\nwidth = 0.35\nlocations = ind\n\nclass_probability = plt.barh(ind, probability, width, alpha=.7, label='Cats vs Dogs')\n\nplt.yticks(np.arange(10))\nplt.title('Class Probability')\nplt.yticks(locations, labels)\n\n#legend\nplt.legend()\nplt.ylim(top=3)\nplt.ylim(bottom=-2)\nplt.show();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"89ec685ad5402b32a3dfc6751f43daebd6ac3fbf"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}