{"id":18268442,"url":"https://github.com/coreyjs/dog-breed-classifier","last_synced_at":"2026-01-27T13:02:32.805Z","repository":{"id":73449848,"uuid":"332240989","full_name":"coreyjs/dog-breed-classifier","owner":"coreyjs","description":"A transfer learning neural network to classify dog breeds.","archived":false,"fork":false,"pushed_at":"2021-01-28T01:14:37.000Z","size":9163,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-05-30T13:03:18.265Z","etag":null,"topics":["classification","deep-learning","deep-neural-networks","machine-learning","ml"],"latest_commit_sha":null,"homepage":"","language":"HTML","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/coreyjs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-01-23T15:21:21.000Z","updated_at":"2021-01-28T01:14:39.000Z","dependencies_parsed_at":"2023-02-24T04:15:32.251Z","dependency_job_id":null,"html_url":"https://github.com/coreyjs/dog-breed-classifier","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/coreyjs/dog-breed-classifier","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fdog-breed-classifier","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fdog-breed-classifier/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fdog-breed-classifier/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fdog-breed-classifier/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/coreyjs","download_url":"https://codeload.github.com/coreyjs/dog-breed-classifier/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/coreyjs%2Fdog-breed-classifier/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28813225,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-27T12:25:15.069Z","status":"ssl_error","status_checked_at":"2026-01-27T12:25:05.297Z","response_time":168,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["classification","deep-learning","deep-neural-networks","machine-learning","ml"],"created_at":"2024-11-05T11:31:35.350Z","updated_at":"2026-01-27T13:02:32.784Z","avatar_url":"https://github.com/coreyjs.png","language":"HTML","funding_links":[],"categories":[],"sub_categories":[],"readme":"[//]: # (Image References)\n\n[image1]: ./images/sample_dog_output.png \"Sample Output\"\n[image2]: ./images/vgg16_model.png \"VGG-16 Model Layers\"\n[image3]: ./images/vgg16_model_draw.png \"VGG16 Model Figure\"\n\n\n## Project Overview\n\nWelcome to the Convolutional Neural Networks (CNN) project in the AI Nanodegree! In this project, you will learn how to build a pipeline that can be used within a web or mobile app to process real-world, user-supplied images.  Given an image of a dog, your algorithm will identify an estimate of the canine’s breed.  If supplied an image of a human, the code will identify the resembling dog breed.  \n\n![Sample Output][image1]\n\nAlong with exploring state-of-the-art CNN models for classification and localization, you will make important design decisions about the user experience for your app.  Our goal is that by completing this lab, you understand the challenges involved in piecing together a series of models designed to perform various tasks in a data processing pipeline.  Each model has its strengths and weaknesses, and engineering a real-world application often involves solving many problems without a perfect answer.  Your imperfect solution will nonetheless create a fun user experience!\n\n\n## Project Instructions\n\n### Instructions\n\n1. Clone the repository and navigate to the downloaded folder.\n\t\n\t```\t\n\t\tgit clone https://github.com/udacity/deep-learning-v2-pytorch.git\n\t\tcd deep-learning-v2-pytorch/project-dog-classification\n\t```\n\t\n__NOTE:__ if you are using the Udacity workspace, you *DO NOT* need to re-download the datasets in steps 2 and 3 - they can be found in the `/data` folder as noted within the workspace Jupyter notebook.\n\n2. Download the [dog dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/dogImages.zip).  Unzip the folder and place it in the repo, at location `path/to/dog-project/dogImages`.  The `dogImages/` folder should contain 133 folders, each corresponding to a different dog breed.\n3. Download the [human dataset](http://vis-www.cs.umass.edu/lfw/lfw.tgz).  Unzip the folder and place it in the repo, at location `path/to/dog-project/lfw`.  If you are using a Windows machine, you are encouraged to use [7zip](http://www.7-zip.org/) to extract the folder. \n4. Make sure you have already installed the necessary Python packages according to the README in the program repository.\n5. Open a terminal window and navigate to the project folder. Open the notebook and follow the instructions.\n\t\n\t```\n\t\tjupyter notebook dog_app.ipynb\n\t```\n\n__NOTE:__ While some code has already been implemented to get you started, you will need to implement additional functionality to successfully answer all of the questions included in the notebook. __Unless requested, do not modify code that has already been included.__\n\n__NOTE:__ In the notebook, you will need to train CNNs in PyTorch.  If your CNN is taking too long to train, feel free to pursue one of the options under the section __Accelerating the Training Process__ below.\n\n\n\n## (Optionally) Accelerating the Training Process \n\nIf your code is taking too long to run, you will need to either reduce the complexity of your chosen CNN architecture or switch to running your code on a GPU.  If you'd like to use a GPU, you can spin up an instance of your own:\n\n#### Amazon Web Services\n\nYou can use Amazon Web Services to launch an EC2 GPU instance. (This costs money, but enrolled students should see a coupon code in their student `resources`.)\n\n## Evaluation\n\nYour project will be reviewed by a Udacity reviewer against the CNN project rubric.  Review this rubric thoroughly and self-evaluate your project before submission.  All criteria found in the rubric must meet specifications for you to pass.\n\n\n## Project Submission\n\nYour submission should consist of the github link to your repository.  Your repository should contain:\n- The `dog_app.ipynb` file with fully functional code, all code cells executed and displaying output, and all questions answered.\n- An HTML or PDF export of the project notebook with the name `report.html` or `report.pdf`.\n\nPlease do __NOT__ include any of the project data sets provided in the `dogImages/` or `lfw/` folders.\n\n### Ready to submit your project?\n\nClick on the \"Submit Project\" button in the classroom and follow the instructions to submit!\n\n\n\n\n\n\n\n# Convolutional Neural Networks\n\n## Project: Write an Algorithm for a Dog Identification App \n\n---\n\nIn this notebook, some template code has already been provided for you, and you will need to implement additional functionality to successfully complete this project. You will not need to modify the included code beyond what is requested. Sections that begin with **'(IMPLEMENTATION)'** in the header indicate that the following block of code will require additional functionality which you must provide. Instructions will be provided for each section, and the specifics of the implementation are marked in the code block with a 'TODO' statement. Please be sure to read the instructions carefully! \n\n\u003e **Note**: Once you have completed all of the code implementations, you need to finalize your work by exporting the Jupyter Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to **File -\u003e Download as -\u003e HTML (.html)**. Include the finished document along with this notebook as your submission.\n\nIn addition to implementing code, there will be questions that you must answer which relate to the project and your implementation. Each section where you will answer a question is preceded by a **'Question X'** header. Carefully read each question and provide thorough answers in the following text boxes that begin with **'Answer:'**. Your project submission will be evaluated based on your answers to each of the questions and the implementation you provide.\n\n\u003e**Note:** Code and Markdown cells can be executed using the **Shift + Enter** keyboard shortcut.  Markdown cells can be edited by double-clicking the cell to enter edit mode.\n\nThe rubric contains _optional_ \"Stand Out Suggestions\" for enhancing the project beyond the minimum requirements. If you decide to pursue the \"Stand Out Suggestions\", you should include the code in this Jupyter notebook.\n\n\n\n---\n### Why We're Here \n\nIn this notebook, you will make the first steps towards developing an algorithm that could be used as part of a mobile or web app.  At the end of this project, your code will accept any user-supplied image as input.  If a dog is detected in the image, it will provide an estimate of the dog's breed.  If a human is detected, it will provide an estimate of the dog breed that is most resembling.  The image below displays potential sample output of your finished project (... but we expect that each student's algorithm will behave differently!). \n\n![Sample Dog Output](images/sample_dog_output.png)\n\nIn this real-world setting, you will need to piece together a series of models to perform different tasks; for instance, the algorithm that detects humans in an image will be different from the CNN that infers dog breed.  There are many points of possible failure, and no perfect algorithm exists.  Your imperfect solution will nonetheless create a fun user experience!\n\n### The Road Ahead\n\nWe break the notebook into separate steps.  Feel free to use the links below to navigate the notebook.\n\n* [Step 0](#step0): Import Datasets\n* [Step 1](#step1): Detect Humans\n* [Step 2](#step2): Detect Dogs\n* [Step 3](#step3): Create a CNN to Classify Dog Breeds (from Scratch)\n* [Step 4](#step4): Create a CNN to Classify Dog Breeds (using Transfer Learning)\n* [Step 5](#step5): Write your Algorithm\n* [Step 6](#step6): Test Your Algorithm\n\n---\n\u003ca id='step0'\u003e\u003c/a\u003e\n## Step 0: Import Datasets\n\nMake sure that you've downloaded the required human and dog datasets:\n* Download the [dog dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/dogImages.zip).  Unzip the folder and place it in this project's home directory, at the location `/dogImages`. \n\n* Download the [human dataset](https://s3-us-west-1.amazonaws.com/udacity-aind/dog-project/lfw.zip).  Unzip the folder and place it in the home directory, at location `/lfw`.  \n\n*Note: If you are using a Windows machine, you are encouraged to use [7zip](http://www.7-zip.org/) to extract the folder.*\n\nIn the code cell below, we save the file paths for both the human (LFW) dataset and dog dataset in the numpy arrays `human_files` and `dog_files`.\n\n\n```python\nfrom collections import OrderedDict\n```\n\n\n```python\nimport numpy as np\nfrom glob import glob\n\n# load filenames for human and dog images\nhuman_files = np.array(glob(\"data/lfw/*/*\"))\ndog_files = np.array(glob(\"data/dogImages/*/*/*\"))\n\n# print number of images in each dataset\nprint('There are %d total human images.' % len(human_files))\nprint('There are %d total dog images.' % len(dog_files))\n```\n\n    There are 13233 total human images.\n    There are 8351 total dog images.\n    \n\n\u003ca id='step1'\u003e\u003c/a\u003e\n## Step 1: Detect Humans\n\nIn this section, we use OpenCV's implementation of [Haar feature-based cascade classifiers](http://docs.opencv.org/trunk/d7/d8b/tutorial_py_face_detection.html) to detect human faces in images.  \n\nOpenCV provides many pre-trained face detectors, stored as XML files on [github](https://github.com/opencv/opencv/tree/master/data/haarcascades).  We have downloaded one of these detectors and stored it in the `haarcascades` directory.  In the next code cell, we demonstrate how to use this detector to find human faces in a sample image.\n\n\n```python\nimport cv2                \nimport matplotlib.pyplot as plt                        \n%matplotlib inline   \n```\n\n\n```python\n                        \n# extract pre-trained face detector\nface_cascade = cv2.CascadeClassifier('haarcascades/haarcascade_frontalface_alt.xml')\n\n# load color (BGR) image\nimg = cv2.imread(human_files[0])\n# convert BGR image to grayscale COLOR_BGR2GRAY\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# find faces in image\nfaces = face_cascade.detectMultiScale(gray)\n\n# print number of faces detected in the image\nprint('Number of faces detected:', len(faces))\n\n# get bounding box for each detected face\nfor (x,y,w,h) in faces:\n    # add bounding box to color image\n    cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)\n    \n# convert BGR image to RGB for plotting\ncv_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n# display the image, along with bounding box\nplt.imshow(cv_rgb)\nplt.show()\n```\n\n    Number of faces detected: 1\n    \n\n\n![png](output_5_1.png)\n\n\nBefore using any of the face detectors, it is standard procedure to convert the images to grayscale.  The `detectMultiScale` function executes the classifier stored in `face_cascade` and takes the grayscale image as a parameter.  \n\nIn the above code, `faces` is a numpy array of detected faces, where each row corresponds to a detected face.  Each detected face is a 1D array with four entries that specifies the bounding box of the detected face.  The first two entries in the array (extracted in the above code as `x` and `y`) specify the horizontal and vertical positions of the top left corner of the bounding box.  The last two entries in the array (extracted here as `w` and `h`) specify the width and height of the box.\n\n### Write a Human Face Detector\n\nWe can use this procedure to write a function that returns `True` if a human face is detected in an image and `False` otherwise.  This function, aptly named `face_detector`, takes a string-valued file path to an image as input and appears in the code block below.\n\n\n```python\n# returns \"True\" if face is detected in image stored at img_path\ndef face_detector(img_path):\n    img = cv2.imread(img_path)\n    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    faces = face_cascade.detectMultiScale(gray)\n    return len(faces) \u003e 0\n```\n\n\n```python\n# Alternate algorithm face detection method\ndef face_detector_2(img_path, scale=1.1, min_n=5, min_s=(30,30)):\n    img = cv2.imread(img_path)\n    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n    faces = face_cascade.detectMultiScale(\n        gray, \n        scaleFactor=scale, \n        minNeighbors=min_n, \n        flags=cv2.CASCADE_SCALE_IMAGE,\n        minSize=min_s\n    )\n    return len(faces) \u003e 0\n```\n\n### (IMPLEMENTATION) Assess the Human Face Detector\n\n__Question 1:__ Use the code cell below to test the performance of the `face_detector` function.  \n- What percentage of the first 100 images in `human_files` have a detected human face?  \n- What percentage of the first 100 images in `dog_files` have a detected human face? \n\nIdeally, we would like 100% of human images with a detected face and 0% of dog images with a detected face.  You will see that our algorithm falls short of this goal, but still gives acceptable performance.  We extract the file paths for the first 100 images from each of the datasets and store them in the numpy arrays `human_files_short` and `dog_files_short`.\n\n__Answer:__ \n(You can print out your results and/or write your percentages in this cell)\n\n\n```python\nfrom tqdm import tqdm\ntest_count = 100\nhuman_files_short = human_files[:test_count]\ndog_files_short = dog_files[:test_count]\n\n#-#-# Do NOT modify the code above this line. #-#-#\nhuman_file_face_count, dog_file_face_count = 0, 0\n\nfor files in zip(human_files_short, dog_files_short):\n    # Test face detection on human file i\n    if face_detector(files[0]):\n        human_file_face_count += 1\n    \n    if face_detector(files[1]):\n        dog_file_face_count += 1\n    \nprint(f'Human Faces in human files: {human_file_face_count}/{test_count} or {human_file_face_count/test_count*100}%')\nprint(f'Human Faces in dog files:   {dog_file_face_count}/{test_count} or {dog_file_face_count/test_count*100}%')\n\n```\n\n    Human Faces in human files: 96/100 or 96.0%\n    Human Faces in dog files:   18/100 or 18.0%\n    \n\nWe suggest the face detector from OpenCV as a potential way to detect human images in your algorithm, but you are free to explore other approaches, especially approaches that make use of deep learning :).  Please use the code cell below to design and test your own face detection algorithm.  If you decide to pursue this _optional_ task, report performance on `human_files_short` and `dog_files_short`.\n\n\n```python\n### (Optional) \n### TODO: Test performance of another face detection algorithm.\n### Feel free to use as many code cells as needed.\nhuman_file_face_count2, dog_file_face_count2 = 0, 0\n\nfor files in zip(human_files_short, dog_files_short):\n    # Test face detection on human file i\n    if face_detector_2(files[0], scale=1.1):\n        human_file_face_count2 += 1\n    \n    if face_detector_2(files[1], scale=1.1):\n        dog_file_face_count2 += 1\n    \nprint(f'Human Faces in human files: {human_file_face_count2}/{test_count} or {human_file_face_count2/test_count*100}%')\nprint(f'Human Faces in dog files:   {dog_file_face_count2}/{test_count} or {dog_file_face_count2/test_count*100}%')\n\n```\n\n    Human Faces in human files: 95/100 or 95.0%\n    Human Faces in dog files:   9/100 or 9.0%\n    \n\n### Optional Review\n\nFor this option portion, I used a similar algorithm but explored using the various parameters that `detectMultiScale` supports to see if we could get better results.  Although we saw better detection results while using the dog photos, we had a reduction in accuracy when finding human faces in human images.  The original algorithm is suffice for now.\n\n---\n\n---\n\u003ca id='step2'\u003e\u003c/a\u003e\n## Step 2: Detect Dogs\n\nIn this section, we use a [pre-trained model](http://pytorch.org/docs/master/torchvision/models.html) to detect dogs in images.  \n\n### Obtain Pre-trained VGG-16 Model\n\nThe code cell below downloads the VGG-16 model, along with weights that have been trained on [ImageNet](http://www.image-net.org/), a very large, very popular dataset used for image classification and other vision tasks.  ImageNet contains over 10 million URLs, each linking to an image containing an object from one of [1000 categories](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a).  \n\n\n```python\nimport torch\nimport torchvision.models as models\n\n# define VGG16 model\nVGG16 = models.vgg16(pretrained=True)\n\n# check if CUDA is available\nuse_cuda = torch.cuda.is_available()\n\n# move model to GPU if CUDA is available\nif use_cuda:\n    VGG16 = VGG16.cuda()\n```\n\n\n```python\nuse_cuda\n```\n\n\n\n\n    True\n\n\n\nGiven an image, this pre-trained VGG-16 model returns a prediction (derived from the 1000 possible categories in ImageNet) for the object that is contained in the image.\n\n### (IMPLEMENTATION) Making Predictions with a Pre-trained Model\n\nIn the next code cell, you will write a function that accepts a path to an image (such as `'dogImages/train/001.Affenpinscher/Affenpinscher_00001.jpg'`) as input and returns the index corresponding to the ImageNet class that is predicted by the pre-trained VGG-16 model.  The output should always be an integer between 0 and 999, inclusive.\n\nBefore writing the function, make sure that you take the time to learn  how to appropriately pre-process tensors for pre-trained models in the [PyTorch documentation](http://pytorch.org/docs/stable/torchvision/models.html).\n\n\n```python\ndef imshow(image, ax=None, title=None):\n    \"\"\"Imshow for Tensor.\"\"\"\n    if ax is None:\n        fig, ax = plt.subplots()\n\n    # PyTorch tensors assume the color channel is the first dimension\n    # but matplotlib assumes is the third dimension\n    image = image.numpy().transpose((1, 2, 0))\n\n    # Undo preprocessing\n    mean = np.array([0.485, 0.456, 0.406])\n    std = np.array([0.229, 0.224, 0.225])\n    image = std * image + mean\n\n    # Image needs to be clipped between 0 and 1 or it looks like noise when displayed\n    image = np.clip(image, 0, 1)\n\n    ax.imshow(image)\n\n    return ax\n```\n\n\n```python\nfrom PIL import Image\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\n\n# Set PIL to be tolerant of image files that are truncated.\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n```\n\n\n```python\n\n\ndef VGG16_predict(img_path, verbose=False):\n    '''\n    Use pre-trained VGG-16 model to obtain index corresponding to \n    predicted ImageNet class for image at specified path\n    \n    Args:\n        img_path: path to an image\n        \n    Returns:\n        Index corresponding to VGG-16 model's prediction\n    '''\n    \n    ## TODO: Complete the function.\n    ## Load and pre-process an image from the given img_path\n    ## Return the *index* of the predicted class for that image\n    VGG16.eval()\n    \n    t = transforms.Compose([\n        transforms.Resize(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406],\n                                     std=[0.229, 0.224, 0.225]),\n        \n    ])\n    \n    img_orig = Image.open(img_path).convert('RGB')\n    \n    # Process image using the transform pipeline\n    img = t(img_orig)   \n    \n    # Show images\n    if verbose:\n        fig = plt.figure()\n        ax = fig.add_subplot(1, 2, 1)\n        imgplot = plt.imshow(img_orig)\n        ax.set_title('Original')\n        ax = fig.add_subplot(1, 2, 2)\n        imgplot = plt.imshow(img.numpy().transpose((1, 2, 0)))\n        ax.set_title('Transformed')\n    \n    # Get Prediction\n    img = Variable(img.unsqueeze(0)).to(\"cuda\")\n    \n    output = VGG16(img)\n    \n    ps = torch.exp(output)\n    top_p, top_class = ps.topk(1, dim=1)\n    \n    if verbose:\n        print(f'Pred: {top_class}')\n    \n    return top_class.cpu().numpy()[0][0] # predicted class index\n```\n\n\n```python\nfile = 'data/dogImages/test/015.Basset_hound/Basset_hound_01034.jpg'\nprint(VGG16_predict(file, verbose=True))\n```\n\n    Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).\n    \n\n    Pred: tensor([[161]], device='cuda:0')\n    161\n    \n\n\n![png](output_23_2.png)\n\n\n### (IMPLEMENTATION) Write a Dog Detector\n\nWhile looking at the [dictionary](https://gist.github.com/yrevar/942d3a0ac09ec9e5eb3a), you will notice that the categories corresponding to dogs appear in an uninterrupted sequence and correspond to dictionary keys 151-268, inclusive, to include all categories from `'Chihuahua'` to `'Mexican hairless'`.  Thus, in order to check to see if an image is predicted to contain a dog by the pre-trained VGG-16 model, we need only check if the pre-trained model predicts an index between 151 and 268 (inclusive).\n\nUse these ideas to complete the `dog_detector` function below, which returns `True` if a dog is detected in an image (and `False` if not).\n\n\n```python\n### returns \"True\" if a dog is detected in the image stored at img_path\ndef dog_detector(img_path):\n    ## TODO: Complete the function.\n    predicted_index = VGG16_predict(img_path)\n    if predicted_index \u003e= 151 and predicted_index \u003c= 268:\n        return True\n    return False # true/false\n```\n\n### (IMPLEMENTATION) Assess the Dog Detector\n\n__Question 2:__ Use the code cell below to test the performance of your `dog_detector` function.  \n- What percentage of the images in `human_files_short` have a detected dog?  \n- What percentage of the images in `dog_files_short` have a detected dog?\n\n__Answer:__ \n\n\n\n```python\n### TODO: Test the performance of the dog_detector function\n### on the images in human_files_short and dog_files_short.\n\nhum_output, dog_output = 0,0\nfor files in zip(human_files_short, dog_files_short):\n    if dog_detector(files[0]):\n        hum_output += 1\n    if dog_detector(files[1]):\n        dog_output += 1\n    \nprint(f'{hum_output/test_count*100}% of images ({hum_output} total) in human_files_short have detected a dog')\nprint(f'{dog_output/test_count*100}% of images ({dog_output} total) in dog_files_short have detected a dog')\n```\n\n    0.0% of images (0 total) in human_files_short have detected a dog\n    94.0% of images (94 total) in dog_files_short have detected a dog\n    \n\nWe suggest VGG-16 as a potential network to detect dog images in your algorithm, but you are free to explore other pre-trained networks (such as [Inception-v3](http://pytorch.org/docs/master/torchvision/models.html#inception-v3), [ResNet-50](http://pytorch.org/docs/master/torchvision/models.html#id3), etc).  Please use the code cell below to test other pre-trained PyTorch models.  If you decide to pursue this _optional_ task, report performance on `human_files_short` and `dog_files_short`.\n\n\n```python\n### (Optional) \n### TODO: Report the performance of another pre-trained network.\n### Feel free to use as many code cells as needed.\n```\n\n---\n\u003ca id='step3'\u003e\u003c/a\u003e\n## Step 3: Create a CNN to Classify Dog Breeds (from Scratch)\n\nNow that we have functions for detecting humans and dogs in images, we need a way to predict breed from images.  In this step, you will create a CNN that classifies dog breeds.  You must create your CNN _from scratch_ (so, you can't use transfer learning _yet_!), and you must attain a test accuracy of at least 10%.  In Step 4 of this notebook, you will have the opportunity to use transfer learning to create a CNN that attains greatly improved accuracy.\n\nWe mention that the task of assigning breed to dogs from images is considered exceptionally challenging.  To see why, consider that *even a human* would have trouble distinguishing between a Brittany and a Welsh Springer Spaniel.  \n\nBrittany | Welsh Springer Spaniel\n- | - \n\u003cimg src=\"images/Brittany_02625.jpg\" width=\"100\"\u003e | \u003cimg src=\"images/Welsh_springer_spaniel_08203.jpg\" width=\"200\"\u003e\n\nIt is not difficult to find other dog breed pairs with minimal inter-class variation (for instance, Curly-Coated Retrievers and American Water Spaniels).  \n\nCurly-Coated Retriever | American Water Spaniel\n- | -\n\u003cimg src=\"images/Curly-coated_retriever_03896.jpg\" width=\"200\"\u003e | \u003cimg src=\"images/American_water_spaniel_00648.jpg\" width=\"200\"\u003e\n\n\nLikewise, recall that labradors come in yellow, chocolate, and black.  Your vision-based algorithm will have to conquer this high intra-class variation to determine how to classify all of these different shades as the same breed.  \n\nYellow Labrador | Chocolate Labrador | Black Labrador\n- | -\n\u003cimg src=\"images/Labrador_retriever_06457.jpg\" width=\"150\"\u003e | \u003cimg src=\"images/Labrador_retriever_06455.jpg\" width=\"240\"\u003e | \u003cimg src=\"images/Labrador_retriever_06449.jpg\" width=\"220\"\u003e\n\nWe also mention that random chance presents an exceptionally low bar: setting aside the fact that the classes are slightly imabalanced, a random guess will provide a correct answer roughly 1 in 133 times, which corresponds to an accuracy of less than 1%.  \n\nRemember that the practice is far ahead of the theory in deep learning.  Experiment with many different architectures, and trust your intuition.  And, of course, have fun!\n\n### (IMPLEMENTATION) Specify Data Loaders for the Dog Dataset\n\nUse the code cell below to write three separate [data loaders](http://pytorch.org/docs/stable/data.html#torch.utils.data.DataLoader) for the training, validation, and test datasets of dog images (located at `dogImages/train`, `dogImages/valid`, and `dogImages/test`, respectively).  You may find [this documentation on custom datasets](http://pytorch.org/docs/stable/torchvision/datasets.html) to be a useful resource.  If you are interested in augmenting your training and/or validation data, check out the wide variety of [transforms](http://pytorch.org/docs/stable/torchvision/transforms.html?highlight=transform)!\n\n\n```python\nimport os\nfrom torchvision import datasets\n\n### TODO: Write data loaders for training, validation, and test sets\n## Specify appropriate transforms, and batch_sizes\ndata_groups = ['train', 'test', 'validation']\ndata_dir = {\n    'train': 'data/dogImages/train',\n    'test': 'data/dogImages/test',\n    'validation': 'data/dogImages/valid'\n}\n\ndata_transforms = {\n    'train': transforms.Compose([\n        transforms.Resize(255),\n        transforms.RandomRotation(20),\n        transforms.RandomResizedCrop(224),\n        transforms.RandomHorizontalFlip(),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])\n    ]),\n    'test': transforms.Compose([\n        transforms.Resize(255),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])\n    ]),\n    'validation': transforms.Compose([\n        transforms.Resize(255),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])\n    ])\n}\n\nworkers = 0\nbatch_size = 20\n\nimage_datasets = {x: datasets.ImageFolder(\n    data_dir[x], \n    transform=data_transforms[x]\n) for x in data_groups}\n\n\ndata_loaders = {x: torch.utils.data.DataLoader(\n    image_datasets[x],\n    batch_size=batch_size, shuffle=True, num_workers=workers\n) for x in data_groups}\n\n```\n\n\n```python\ndata_iter = iter(data_loaders_transfer['test'])\nimages, labels = data_iter.next()\nimages = images.numpy()\n\nfig = plt.figure(figsize=(25, 4))\nr = np.arange(8)\nfor idx in r:\n    ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n    img = np.transpose(images[idx], (1, 2, 0))\n    \n    # reverse the normalization\n    img = img * np.array((0.229, 0.224, 0.225)) + np.array((0.485, 0.456, 0.406))\n    plt.imshow(np.clip(img, 0, 1))\n\nfig = plt.figure(figsize=(25, 4))\nfor idx in r:\n    ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n    img = np.transpose(images[idx], (1, 2, 0))\n    plt.imshow(np.clip(img, 0, 1))\n    \n```\n\n    C:\\Users\\cscha\\anaconda3\\envs\\u-deep-learning\\lib\\site-packages\\ipykernel_launcher.py:8: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.\n      \n    C:\\Users\\cscha\\anaconda3\\envs\\u-deep-learning\\lib\\site-packages\\ipykernel_launcher.py:16: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.\n      app.launch_new_instance()\n    \n\n\n![png](output_33_1.png)\n\n\n\n![png](output_33_2.png)\n\n\n**Question 3:** Describe your chosen procedure for preprocessing the data. \n- How does your code resize the images (by cropping, stretching, etc)?  What size did you pick for the input tensor, and why?\n- Did you decide to augment the dataset?  If so, how (through translations, flips, rotations, etc)?  If not, why not?\n\n\n**Answer**:\n\nFor all 3 datasets I have resized the images to `255`, and then applied a `CenterCrop` to size them down to `224`.  The reasoning behind this was that from my expeirence this seems to be a common size used in this type of situation.  As the network develops the adjustments can be tweaked as needed.\n\nAs for agumentation, for our `train` dataset I first apply a `RandomRotation` of 20 degrees to the image, and a `RandomResizedCrop` to 224px to give use a bit more randomization in the training set.  I have decided on these initial agumentations at first to provide a bit of randomness to the data, but not to go too overboard with the transforms and possible increasing the training time.  This is something I will keep an eye on as training goes, to see if we can increase our prediction score.\n\n\n### (IMPLEMENTATION) Model Architecture\n\nCreate a CNN to classify dog breed.  Use the template in the code cell below.\n\n\n```python\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport gc\n```\n\n\n```python\n gc.collect()\n torch.cuda.empty_cache()\n```\n\n\n```python\n# define the CNN architecture\nclass Net(nn.Module):\n    ### TODO: choose an architecture, and complete the class\n    def __init__(self):\n        super(Net, self).__init__()\n        \n        # Convolutional Layers\n        self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, padding=1)\n        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, padding=1)\n        self.conv3 = nn.Conv2d(in_channels=32, out_channels=64, kernel_size=3, padding=1)\n        \n        # Pooling Layers\n        self.pool = nn.MaxPool2d(2, 2)\n    \n        # Fully Connected Layers, final output of 133 for our # of dog breeds\n        self.fc1 = nn.Linear(64 * 28 * 28, 800)\n        self.fc2 = nn.Linear(800,133)\n        self.dropout = nn.Dropout(0.2)\n    \n    def forward(self, x):\n        ## Define forward behavior\n        x = self.pool(F.relu(self.conv1(x)))\n        x = self.pool(F.relu(self.conv2(x)))\n        x = self.pool(F.relu(self.conv3(x)))\n        \n        # Flatten image into vector, pass to FC layers\n        #print(x.shape)# [32, 64, 28, 28]\n        x = x.view(-1, 64 * 28 * 28)\n        \n        x = self.dropout(x)\n        x = self.fc1(x)\n        x = F.relu(x)\n        x = self.dropout(x)\n        x = self.fc2(x)\n        return x\n\n#-#-# You do NOT have to modify the code below this line. #-#-#\n\n# instantiate the CNN\nmodel_scratch = Net()\nprint(model_scratch)\n# move tensors to GPU if CUDA is available\nif use_cuda:\n    model_scratch.cuda()\n```\n\n    Net(\n      (conv1): Conv2d(3, 16, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (conv2): Conv2d(16, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (conv3): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))\n      (pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)\n      (fc1): Linear(in_features=50176, out_features=800, bias=True)\n      (fc2): Linear(in_features=800, out_features=133, bias=True)\n      (dropout): Dropout(p=0.2, inplace=False)\n    )\n    \n\n__Question 4:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step.  \n\n__Answer:__  For my CNN I decided to go with `3` convolutional layers initially.  I had tested various different layers but found 3 to be suffice for my needs as well as overall training speed.  Each convolutional layer is followed by a max pooling layer.  The CNN is completed with `2` fully connected layers, reducing out output down to `133` to match our dog breeds.  Each FC layer is using a `dropout` layer with a dropout probability of 0.2.  Since this network is not finished with a activation function layer, I am using `nn.CrossEntropyLoss` as our loss function.\n\n### (IMPLEMENTATION) Specify Loss Function and Optimizer\n\nUse the next code cell to specify a [loss function](http://pytorch.org/docs/stable/nn.html#loss-functions) and [optimizer](http://pytorch.org/docs/stable/optim.html).  Save the chosen loss function as `criterion_scratch`, and the optimizer as `optimizer_scratch` below.\n\n\n```python\nimport torch.optim as optim\n\n### TODO: select loss function\ncriterion_scratch = nn.CrossEntropyLoss()\n\n### TODO: select optimizer\noptimizer_scratch = optim.SGD(model_scratch.parameters(), lr=0.01)\n```\n\n### (IMPLEMENTATION) Train and Validate the Model\n\nTrain and validate your model in the code cell below.  [Save the final model parameters](http://pytorch.org/docs/master/notes/serialization.html) at filepath `'model_scratch.pt'`.\n\n\n```python\n# the following import is required for training to be robust to truncated images\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\ndef train(n_epochs, loaders, model, optimizer, criterion, use_cuda, save_path):\n    \"\"\"returns trained model\"\"\"\n    # initialize tracker for minimum validation loss\n    print(f'GPU Status: {use_cuda}')\n    valid_loss_min = np.Inf \n    if use_cuda:\n        model.to(\"cuda\")\n    \n    for epoch in range(1, n_epochs+1):\n       \n        # initialize variables to monitor training and validation loss\n        train_loss = 0.0\n        valid_loss = 0.0\n        \n        ###################\n        # train the model #\n        ###################\n        model.train()\n        for batch_idx, (data, target) in enumerate(loaders['train']):\n            # move to GPU\n            if use_cuda:\n                data, target = data.cuda(), target.cuda()\n                \n            optimizer.zero_grad()\n            \n            output = model(data)\n            \n            loss = criterion(output, target)\n            loss.backward()\n            optimizer.step()\n            ## find the loss and update the model parameters accordingly\n            ## record the average training loss, using something like\n            ## train_loss = train_loss + ((1 / (batch_idx + 1)) * (loss.data - train_loss))\n            train_loss += loss.item() * data.size(0)\n        ######################    \n        # validate the model #\n        ######################\n        model.eval()\n        for batch_idx, (data, target) in enumerate(loaders['validation']):\n            # move to GPU\n            if use_cuda:\n                data, target = data.cuda(), target.cuda()\n            ## update the average validation loss\n            output = model(data)\n            loss = criterion(output, target)\n            valid_loss += loss.item() * data.size(0)\n            \n        # print training/validation statistics \n        train_loss = train_loss/len(loaders['train'].dataset)\n        valid_loss = valid_loss/len(loaders['train'].dataset)\n        print('Epoch: {} \\tTraining Loss: {:.6f} \\tValidation Loss: {:.6f}'.format(\n            epoch, \n            train_loss,\n            valid_loss\n            ))\n    else:\n        ## TODO: save the model if validation loss has decreased\n         if valid_loss \u003c= valid_loss_min:\n            torch.save(model.state_dict(), save_path)\n            valid_loss_min = valid_loss\n            \n    # return trained model\n    return model\n\n```\n\n\n```python\n# train the model\nmodel_scratch = train(20, data_loaders, model_scratch, optimizer_scratch, \n                      criterion_scratch, use_cuda, 'model_scratch.pt')\n\n# load the model that got the best validation accuracy\nmodel_scratch.load_state_dict(torch.load('model_scratch.pt'))\n```\n\n    GPU Status: True\n    Epoch: 1 \tTraining Loss: 4.746669 \tValidation Loss: 0.579934\n    Epoch: 2 \tTraining Loss: 4.687191 \tValidation Loss: 0.568838\n    Epoch: 3 \tTraining Loss: 4.589454 \tValidation Loss: 0.554227\n    Epoch: 4 \tTraining Loss: 4.542090 \tValidation Loss: 0.549874\n    Epoch: 5 \tTraining Loss: 4.538822 \tValidation Loss: 0.545945\n    Epoch: 6 \tTraining Loss: 4.479438 \tValidation Loss: 0.540443\n    Epoch: 7 \tTraining Loss: 4.476710 \tValidation Loss: 0.539977\n    Epoch: 8 \tTraining Loss: 4.430012 \tValidation Loss: 0.536933\n    Epoch: 9 \tTraining Loss: 4.407877 \tValidation Loss: 0.529360\n    Epoch: 10 \tTraining Loss: 4.378547 \tValidation Loss: 0.530847\n    Epoch: 11 \tTraining Loss: 4.340604 \tValidation Loss: 0.522987\n    Epoch: 12 \tTraining Loss: 4.300495 \tValidation Loss: 0.518504\n    Epoch: 13 \tTraining Loss: 4.272557 \tValidation Loss: 0.519089\n    Epoch: 14 \tTraining Loss: 4.232557 \tValidation Loss: 0.507989\n    Epoch: 15 \tTraining Loss: 4.193184 \tValidation Loss: 0.504560\n    Epoch: 16 \tTraining Loss: 4.145647 \tValidation Loss: 0.505856\n    Epoch: 17 \tTraining Loss: 4.134879 \tValidation Loss: 0.498907\n    Epoch: 18 \tTraining Loss: 4.098685 \tValidation Loss: 0.492602\n    Epoch: 19 \tTraining Loss: 4.087686 \tValidation Loss: 0.501339\n    Epoch: 20 \tTraining Loss: 4.052678 \tValidation Loss: 0.491177\n    \n\n\n\n\n    \u003cAll keys matched successfully\u003e\n\n\n\n### (IMPLEMENTATION) Test the Model\n\nTry out your model on the test dataset of dog images.  Use the code cell below to calculate and print the test loss and accuracy.  Ensure that your test accuracy is greater than 10%.\n\n\n```python\ndef test(loaders, model, criterion, use_cuda):\n\n    # monitor test loss and accuracy\n    test_loss = 0.\n    correct = 0.\n    total = 0.\n\n    model.eval()\n    for batch_idx, (data, target) in enumerate(loaders['test']):\n        # move to GPU\n        if use_cuda:\n            data, target = data.cuda(), target.cuda()\n        # forward pass: compute predicted outputs by passing inputs to the model\n        output = model(data)\n        # calculate the loss\n        loss = criterion(output, target)\n        # update average test loss \n        test_loss = test_loss + ((1 / (batch_idx + 1)) * (loss.data - test_loss))\n        # convert output probabilities to predicted class\n        pred = output.data.max(1, keepdim=True)[1]\n        # compare predictions to true label\n        correct += np.sum(np.squeeze(pred.eq(target.data.view_as(pred))).cpu().numpy())\n        total += data.size(0)\n            \n    print('Test Loss: {:.6f}\\n'.format(test_loss))\n\n    print('\\nTest Accuracy: %2d%% (%2d/%2d)' % (\n        100. * correct / total, correct, total))\n\n# call test function    \ntest(data_loaders, model_scratch, criterion_scratch, use_cuda)\n```\n\n    Test Loss: 3.935756\n    \n    \n    Test Accuracy: 10% (88/836)\n    \n\n---\n\u003ca id='step4'\u003e\u003c/a\u003e\n## Step 4: Create a CNN to Classify Dog Breeds (using Transfer Learning)\n\nYou will now use transfer learning to create a CNN that can identify dog breed from images.  Your CNN must attain at least 60% accuracy on the test set.\n\n### (IMPLEMENTATION) Specify Data Loaders for the Dog Dataset\n\nUse the code cell below to write three separate [data loaders](http://pytorch.org/docs/master/data.html#torch.utils.data.DataLoader) for the training, validation, and test datasets of dog images (located at `dogImages/train`, `dogImages/valid`, and `dogImages/test`, respectively). \n\nIf you like, **you are welcome to use the same data loaders from the previous step**, when you created a CNN from scratch.\n\n\n```python\n## TODO: Specify data loaders\ndata_groups = ['train', 'test', 'validation']\ndata_dir = {\n    'train': 'data/dogImages/train',\n    'test': 'data/dogImages/test',\n    'validation': 'data/dogImages/valid'\n}\n\ndata_transforms_transfer = {\n    'train': transforms.Compose([\n        transforms.RandomRotation(30),\n        transforms.Resize(255),\n        transforms.RandomResizedCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])\n    ]),\n    'test': transforms.Compose([\n        transforms.Resize(255),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])\n    ]),\n    'validation': transforms.Compose([\n        transforms.Resize(255),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])\n    ])\n}\n\nimage_datasets_transfer = {x: datasets.ImageFolder(\n    data_dir[x], \n    transform=data_transforms_transfer[x]\n) for x in data_groups}\n\n\ndata_loaders_transfer = {x: torch.utils.data.DataLoader(\n    image_datasets_transfer[x],\n    batch_size=16, shuffle=True\n) for x in data_groups}\n\n```\n\n\n```python\ndata_iter = iter(data_loaders_transfer['test'])\nimages, labels = data_iter.next()\nimages = images.numpy()\n\nfig = plt.figure(figsize=(25, 4))\nfor idx in np.arange(16):\n    ax = fig.add_subplot(2, 20/2, idx+1, xticks=[], yticks=[])\n    plt.imshow(np.transpose(images[idx], (1, 2, 0)).astype(np.uint8))\n    \n```\n\n    C:\\Users\\cscha\\anaconda3\\envs\\u-deep-learning\\lib\\site-packages\\ipykernel_launcher.py:7: MatplotlibDeprecationWarning: Passing non-integers as three-element position specification is deprecated since 3.3 and will be removed two minor releases later.\n      import sys\n    \n\n\n![png](output_51_1.png)\n\n\n### (IMPLEMENTATION) Model Architecture\n\nUse transfer learning to create a CNN to classify dog breed.  Use the code cell below, and save your initialized model as the variable `model_transfer`.\n\n\n```python\nimport torchvision.models as models\nimport torch.nn as nn\n```\n\n\n```python\nmodel_transfer = models.resnet50(pretrained=True)\nfor param in model_transfer.parameters():\n    param.requires_grad = False\n    \nprint(model_transfer)\n```\n\n    Downloading: \"https://download.pytorch.org/models/resnet50-19c8e357.pth\" to C:\\Users\\cscha/.cache\\torch\\hub\\checkpoints\\resnet50-19c8e357.pth\n    \n\n\n      0%|          | 0.00/97.8M [00:00\u003c?, ?B/s]\n\n\n    ResNet(\n      (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n      (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n      (relu): ReLU(inplace=True)\n      (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)\n      (layer1): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n            (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (layer2): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)\n            (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (3): Bottleneck(\n          (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (layer3): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False)\n            (1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (3): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (4): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (5): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (layer4): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False)\n            (1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))\n      (fc): Linear(in_features=2048, out_features=1000, bias=True)\n    )\n    \n\n\n```python\n## TODO: Specify model architecture \n\n# classifier = nn.Sequential(\n#         OrderedDict([\n#             ('fc1',     nn.Linear(25088, 4096)),\n#             ('relu',    nn.ReLU()),\n#             ('dropout', nn.Dropout(p=0.5, inplace=False)),\n#             ('fc2',     nn.Linear(4096, 2048)),\n#             ('relu2',   nn.ReLU()),\n#             ('dropout2',nn.Dropout(p=0.5, inplace=False)),\n#             ('fc3',  nn.Linear(2048, 133))\n#         ]))\n\nmodel_transfer.fc = nn.Linear(2048, 133)\n\nprint(f'GPU Enabled: {use_cuda}')\nif use_cuda:\n    model_transfer = model_transfer.cuda()\n```\n\n    GPU Enabled: True\n    \n\n\n```python\nprint(model_transfer)\n```\n\n    ResNet(\n      (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)\n      (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n      (relu): ReLU(inplace=True)\n      (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False)\n      (layer1): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n            (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (layer2): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False)\n            (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (3): Bottleneck(\n          (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (layer3): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False)\n            (1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (3): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (4): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (5): Bottleneck(\n          (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (layer4): Sequential(\n        (0): Bottleneck(\n          (conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n          (downsample): Sequential(\n            (0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False)\n            (1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          )\n        )\n        (1): Bottleneck(\n          (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n        (2): Bottleneck(\n          (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False)\n          (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False)\n          (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)\n          (relu): ReLU(inplace=True)\n        )\n      )\n      (avgpool): AdaptiveAvgPool2d(output_size=(1, 1))\n      (fc): Linear(in_features=2048, out_features=133, bias=True)\n    )\n    \n\n__Question 5:__ Outline the steps you took to get to your final CNN architecture and your reasoning at each step.  Describe why you think the architecture is suitable for the current problem.\n\n__Answer:__  For the final CNN architecture, I tested out a few different models.  Initially I was still using the `vgg16` model, but I was consistently getting poor training and validation scores, despite how many epochs I was running.  This was also taking a very long time on my 1080Ti card.  When exporing new CNN models, I ran into `resnet50` and got excellent results on our training and validation data.  I replaced the final layer of the CNN with a linear fc layer that outputed `133` outputs to match our different dog breeds. As you will see below, I was able to achieve 83% test accuracy using transfer learning on `resnet50`.\n\n\n### (IMPLEMENTATION) Specify Loss Function and Optimizer\n\nUse the next code cell to specify a [loss function](http://pytorch.org/docs/master/nn.html#loss-functions) and [optimizer](http://pytorch.org/docs/master/optim.html).  Save the chosen loss function as `criterion_transfer`, and the optimizer as `optimizer_transfer` below.\n\n\n```python\ncriterion_transfer = nn.CrossEntropyLoss()\noptimizer_transfer = optim.Adam(model_transfer.fc.parameters(), lr=0.001)\n```\n\n### (IMPLEMENTATION) Train and Validate the Model\n\nTrain and validate your model in the code cell below.  [Save the final model parameters](http://pytorch.org/docs/master/notes/serialization.html) at filepath `'model_transfer.pt'`.\n\n\n```python\n# train the model\ntransfer_epochs = 20\nmodel_transfer = train(transfer_epochs, data_loaders_transfer, model_transfer, optimizer_transfer, criterion_transfer, use_cuda, 'model_transfer.pt')\n\n# load the model that got the best validation accuracy (uncomment the line below)\nmodel_transfer.load_state_dict(torch.load('model_transfer.pt'))\n```\n\n    GPU Status: True\n    Epoch: 1 \tTraining Loss: 2.736801 \tValidation Loss: 0.120457\n    Epoch: 2 \tTraining Loss: 1.468269 \tValidation Loss: 0.083567\n    Epoch: 3 \tTraining Loss: 1.334539 \tValidation Loss: 0.091082\n    Epoch: 4 \tTraining Loss: 1.239917 \tValidation Loss: 0.076652\n    Epoch: 5 \tTraining Loss: 1.170877 \tValidation Loss: 0.070043\n    Epoch: 6 \tTraining Loss: 1.169875 \tValidation Loss: 0.077313\n    Epoch: 7 \tTraining Loss: 1.169159 \tValidation Loss: 0.074955\n    Epoch: 8 \tTraining Loss: 1.093655 \tValidation Loss: 0.079648\n    Epoch: 9 \tTraining Loss: 1.109043 \tValidation Loss: 0.081856\n    Epoch: 10 \tTraining Loss: 1.075384 \tValidation Loss: 0.085381\n    Epoch: 11 \tTraining Loss: 1.072731 \tValidation Loss: 0.071427\n    Epoch: 12 \tTraining Loss: 1.080146 \tValidation Loss: 0.074082\n    Epoch: 13 \tTraining Loss: 1.067245 \tValidation Loss: 0.071290\n    Epoch: 14 \tTraining Loss: 1.062381 \tValidation Loss: 0.083486\n    Epoch: 15 \tTraining Loss: 1.030111 \tValidation Loss: 0.080445\n    Epoch: 16 \tTraining Loss: 1.031068 \tValidation Loss: 0.077852\n    Epoch: 17 \tTraining Loss: 1.044750 \tValidation Loss: 0.081257\n    Epoch: 18 \tTraining Loss: 1.050826 \tValidation Loss: 0.078854\n    Epoch: 19 \tTraining Loss: 1.045438 \tValidation Loss: 0.079536\n    Epoch: 20 \tTraining Loss: 1.039488 \tValidation Loss: 0.076715\n    \n\n\n\n\n    \u003cAll keys matched successfully\u003e\n\n\n\n### (IMPLEMENTATION) Test the Model\n\nTry out your model on the test dataset of dog images. Use the code cell below to calculate and print the test loss and accuracy.  Ensure that your test accuracy is greater than 60%.\n\n\n```python\ntest(data_loaders_transfer, model_transfer, criterion_transfer, use_cuda)\n```\n\n    Test Loss: 0.598627\n    \n    \n    Test Accuracy: 83% (700/836)\n    \n\n### (IMPLEMENTATION) Predict Dog Breed with the Model\n\nWrite a function that takes an image path as input and returns the dog breed (`Affenpinscher`, `Afghan hound`, etc) that is predicted by your model.  \n\n\n```python\n# list of class names by index, i.e. a name can be accessed like class_names[0]\nclass_names = [item[4:].replace(\"_\", \" \") for item in image_datasets_transfer['train'].classes]\n```\n\n\n```python\nclass_names\n```\n\n\n\n\n    ['Affenpinscher',\n     'Afghan hound',\n     'Airedale terrier',\n     'Akita',\n     'Alaskan malamute',\n     'American eskimo dog',\n     'American foxhound',\n     'American staffordshire terrier',\n     'American water spaniel',\n     'Anatolian shepherd dog',\n     'Australian cattle dog',\n     'Australian shepherd',\n     'Australian terrier',\n     'Basenji',\n     'Basset hound',\n     'Beagle',\n     'Bearded collie',\n     'Beauceron',\n     'Bedlington terrier',\n     'Belgian malinois',\n     'Belgian sheepdog',\n     'Belgian tervuren',\n     'Bernese mountain dog',\n     'Bichon frise',\n     'Black and tan coonhound',\n     'Black russian terrier',\n     'Bloodhound',\n     'Bluetick coonhound',\n     'Border collie',\n     'Border terrier',\n     'Borzoi',\n     'Boston terrier',\n     'Bouvier des flandres',\n     'Boxer',\n     'Boykin spaniel',\n     'Briard',\n     'Brittany',\n     'Brussels griffon',\n     'Bull terrier',\n     'Bulldog',\n     'Bullmastiff',\n     'Cairn terrier',\n     'Canaan dog',\n     'Cane corso',\n     'Cardigan welsh corgi',\n     'Cavalier king charles spaniel',\n     'Chesapeake bay retriever',\n     'Chihuahua',\n     'Chinese crested',\n     'Chinese shar-pei',\n     'Chow chow',\n     'Clumber spaniel',\n     'Cocker spaniel',\n     'Collie',\n     'Curly-coated retriever',\n     'Dachshund',\n     'Dalmatian',\n     'Dandie dinmont terrier',\n     'Doberman pinscher',\n     'Dogue de bordeaux',\n     'English cocker spaniel',\n     'English setter',\n     'English springer spaniel',\n     'English toy spaniel',\n     'Entlebucher mountain dog',\n     'Field spaniel',\n     'Finnish spitz',\n     'Flat-coated retriever',\n     'French bulldog',\n     'German pinscher',\n     'German shepherd dog',\n     'German shorthaired pointer',\n     'German wirehaired pointer',\n     'Giant schnauzer',\n     'Glen of imaal terrier',\n     'Golden retriever',\n     'Gordon setter',\n     'Great dane',\n     'Great pyrenees',\n     'Greater swiss mountain dog',\n     'Greyhound',\n     'Havanese',\n     'Ibizan hound',\n     'Icelandic sheepdog',\n     'Irish red and white setter',\n     'Irish setter',\n     'Irish terrier',\n     'Irish water spaniel',\n     'Irish wolfhound',\n     'Italian greyhound',\n     'Japanese chin',\n     'Keeshond',\n     'Kerry blue terrier',\n     'Komondor',\n     'Kuvasz',\n     'Labrador retriever',\n     'Lakeland terrier',\n     'Leonberger',\n     'Lhasa apso',\n     'Lowchen',\n     'Maltese',\n     'Manchester terrier',\n     'Mastiff',\n     'Miniature schnauzer',\n     'Neapolitan mastiff',\n     'Newfoundland',\n     'Norfolk terrier',\n     'Norwegian buhund',\n     'Norwegian elkhound',\n     'Norwegian lundehund',\n     'Norwich terrier',\n     'Nova scotia duck tolling retriever',\n     'Old english sheepdog',\n     'Otterhound',\n     'Papillon',\n     'Parson russell terrier',\n     'Pekingese',\n     'Pembroke welsh corgi',\n     'Petit basset griffon vendeen',\n     'Pharaoh hound',\n     'Plott',\n     'Pointer',\n     'Pomeranian',\n     'Poodle',\n     'Portuguese water dog',\n     'Saint bernard',\n     'Silky terrier',\n     'Smooth fox terrier',\n     'Tibetan mastiff',\n     'Welsh springer spaniel',\n     'Wirehaired pointing griffon',\n     'Xoloitzcuintli',\n     'Yorkshire terrier']\n\n\n\n\n```python\n### TODO: Write a function that takes a path to an image as input\n### and returns the dog breed that is predicted by the model.\n\n\ndef predict_breed_transfer(img_path, verbose=False):\n    # load the image and return the predicted breed\n    model_transfer.eval()\n    t = transforms.Compose([\n        transforms.Resize(255),\n        transforms.CenterCrop(224),\n        transforms.ToTensor(),\n        transforms.Normalize(mean=[0.485, 0.456, 0.406], \n                             std=[0.229, 0.224, 0.225])])\n        \n    img_orig = Image.open(img_path).convert('RGB')\n    \n    # Process image using the transform pipeline\n    img = t(img_orig)   \n    # Show images\n    if verbose:\n        fig = plt.figure()\n        ax = fig.add_subplot(1, 2, 1)\n        imgplot = plt.imshow(img_orig)\n        ax.set_title('Original')\n        plt.show()\n    \n    # Get Prediction\n    img = Variable(img.unsqueeze(0)).to(\"cuda\")\n    output = model_transfer(img)\n    \n    ps, pred = torch.max(output, 1)\n\n    if verbose:\n        print(f'Pred: {pred}')\n        print(f'Ps: {ps}')\n    \n    return class_names[pred.cpu().numpy()[0]], pred.cpu().numpy()[0], ps.cpu().detach().numpy()[0] # predicted class index\n```\n\n\n```python\nf = 'data/dogImages/test/014.Basenji/Basenji_00987.jpg'\nc, val, pred = predict_breed_transfer(f, verbose=True)\nprint(f'Predicted Breed: {c}')\nprint(pred)\n\nf = 'data/dogImages/test/071.German_shepherd_dog/German_shepherd_dog_04931.jpg'\nc, val, pred = predict_breed_transfer(f, verbose=True)\nprint(f'Predicted Breed: {c}')\n\nf = 'data/dogImages/test/125.Portuguese_water_dog/Portuguese_water_dog_07984.jpg'\nc, val, pred = predict_breed_transfer(f, verbose=True)\nprint(f'Predicted Breed: {c}')\n```\n\n\n![png](output_69_0.png)\n\n\n    Pred: tensor([13], device='cuda:0')\n    Ps: tensor([5.2752], device='cuda:0', grad_fn=\u003cMaxBackward0\u003e)\n    Predicted Breed: Basenji\n    5.275156\n    \n\n\n![png](output_69_2.png)\n\n\n    Pred: tensor([70], device='cuda:0')\n    Ps: tensor([3.2261], device='cuda:0', grad_fn=\u003cMaxBackward0\u003e)\n    Predicted Breed: German shepherd dog\n    \n\n\n![png](output_69_4.png)\n\n\n    Pred: tensor([124], device='cuda:0')\n    Ps: tensor([-6.5817], device='cuda:0', grad_fn=\u003cMaxBackward0\u003e)\n    Predicted Breed: Portuguese water dog\n    \n\n---\n\u003ca id='step5'\u003e\u003c/a\u003e\n## Step 5: Write your Algorithm\n\nWrite an algorithm that accepts a file path to an image and first determines whether the image contains a human, dog, or neither.  Then,\n- if a __dog__ is detected in the image, return the predicted breed.\n- if a __human__ is detected in the image, return the resembling dog breed.\n- if __neither__ is detected in the image, provide output that indicates an error.\n\nYou are welcome to write your own functions for detecting humans and dogs in images, but feel free to use the `face_detector` and `dog_detector` functions developed above.  You are __required__ to use your CNN from Step 4 to predict dog breed.  \n\nSome sample output for our algorithm is provided below, but feel free to design your own user experience!\n\n![Sample Human Output](images/sample_human_output.png)\n\n\n### (IMPLEMENTATION) Write your Algorithm\n\n\n```python\ndef show_image(img_path):\n    img_orig = Image.open(img_path).convert('RGB')\n    plt.imshow(img_orig)\n    plt.show()\n```\n\n\n```python\n### TODO: Write your algorithm.\n### Feel free to use as many code cells as needed.\n\ndef run_app(img_path):\n    ## handle cases for a human face, dog, and neither\n    print('-------------------------------------------------')\n    print(f'Proccessing: {img_path}')\n    # Determine if we have a human face\n    is_human = face_detector(img_path)\n    is_dog = dog_detector(img_path)\n    \n    show_image(img_path)\n    \n    if not is_human and not is_dog:\n        print('No human nor dog has been detected in the image!')\n        print('-------------------------------------------------')\n        return\n    \n    dog_breed, _, _ = predict_breed_transfer(img_path, verbose=False)\n    \n    if is_human and not is_dog:\n        print(f'This is a human photo. Although there is an uncanny resemblance to a {dog_breed}')\n        print('-------------------------------------------------')\n        return\n    \n    if not is_human and is_dog:\n        print(f'Dog Alert:  This is a {dog_breed}')\n        print('-------------------------------------------------')\n        return\n    \n    if is_human and is_dog:\n        print(f'Human and dog are detected!  Of breed: {dog_breed}')\n        print('-------------------------------------------------')\n        return\n    \n\n```\n\n---\n\u003ca id='step6'\u003e\u003c/a\u003e\n## Step 6: Test Your Algorithm\n\nIn this section, you will take your new algorithm for a spin!  What kind of dog does the algorithm think that _you_ look like?  If you have a dog, does it predict your dog's breed accurately?  If you have a cat, does it mistakenly think that your cat is a dog?\n\n### (IMPLEMENTATION) Test Your Algorithm on Sample Images!\n\nTest your algorithm at least six images on your computer.  Feel free to use any images you like.  Use at least two human and two dog images.  \n\n__Question 6:__ Is the output better than you expected :) ?  Or worse :( ?  Provide at least three possible points of improvement for your algorithm.\n\n__Answer:__ \n\nOverall, once I finally got a network architecture that I was happy with, I am quite pleased with the prediction outcomes of our transfer learning neural net.  When looking back, there a few areas of improvment I could see:\n\n1. Adding probabilty to the final outcome would be helpful in knowing how our network predicted what it did.  Was it a strong 95% or something weaker around 60%.\n\n2. Our human detection logic is limited to human faces.  In a few of the pictures, due to cropping at times, we are only left with human bodies in the background (legs, arms, etc).  These do not register as humans as we are limited to face detection only.\n\n3.  When humans are detected, we are only determining if we have detected \u003e1 face.  This could be updated to determine how many humans we detected, and what each one of their faces can resemble what dog breed.  \n\n\n\n\n```python\n## TODO: Execute your algorithm from Step 6 on\n## at least 6 images on your computer.\n## Feel free to use as many code cells as needed.\n\n## suggested code, below\nnp.random.shuffle(human_files)\nnp.random.shuffle(dog_files)\nfor file in np.hstack((human_files[:8], dog_files[:8])):\n    run_app(file)\n```\n\n    -------------------------------------------------\n    Proccessing: data/lfw\\Samantha_Ledster\\Samantha_Ledster_0001.jpg\n    \n\n\n![png](output_75_1.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Finnish spitz\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Rick_Stansbury\\Rick_Stansbury_0003.jpg\n    \n\n\n![png](output_75_3.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Dogue de bordeaux\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Sylvester_Stallone\\Sylvester_Stallone_0003.jpg\n    \n\n\n![png](output_75_5.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Dachshund\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Nicolas_Escude\\Nicolas_Escude_0002.jpg\n    \n\n\n![png](output_75_7.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a American foxhound\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Jerry_Jones\\Jerry_Jones_0001.jpg\n    \n\n\n![png](output_75_9.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Saint bernard\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Stacy_Dragila\\Stacy_Dragila_0002.jpg\n    \n\n\n![png](output_75_11.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Australian cattle dog\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Magui_Serna\\Magui_Serna_0002.jpg\n    \n\n\n![png](output_75_13.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Komondor\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/lfw\\Romano_Prodi\\Romano_Prodi_0005.jpg\n    \n\n\n![png](output_75_15.png)\n\n\n    This is a human photo. Although there is an uncanny resemblance to a Dogue de bordeaux\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\027.Bloodhound\\Bloodhound_01928.jpg\n    \n\n\n![png](output_75_17.png)\n\n\n    Dog Alert:  This is a Bloodhound\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\054.Collie\\Collie_03832.jpg\n    \n\n\n![png](output_75_19.png)\n\n\n    Dog Alert:  This is a Collie\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\058.Dandie_dinmont_terrier\\Dandie_dinmont_terrier_04118.jpg\n    \n\n\n![png](output_75_21.png)\n\n\n    Human and dog are detected!  Of breed: Dandie dinmont terrier\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\019.Bedlington_terrier\\Bedlington_terrier_01387.jpg\n    \n\n\n![png](output_75_23.png)\n\n\n    Dog Alert:  This is a Bedlington terrier\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\004.Akita\\Akita_00248.jpg\n    \n\n\n![png](output_75_25.png)\n\n\n    Dog Alert:  This is a Akita\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\085.Irish_red_and_white_setter\\Irish_red_and_white_setter_05780.jpg\n    \n\n\n![png](output_75_27.png)\n\n\n    Dog Alert:  This is a Brittany\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\064.English_toy_spaniel\\English_toy_spaniel_04546.jpg\n    \n\n\n![png](output_75_29.png)\n\n\n    Dog Alert:  This is a English toy spaniel\n    -------------------------------------------------\n    -------------------------------------------------\n    Proccessing: data/dogImages\\train\\051.Chow_chow\\Chow_chow_03625.jpg\n    \n\n\n![png](output_75_31.png)\n\n\n    Human and dog are detected!  Of breed: Chow chow\n    -------------------------------------------------\n    \n\n## End Note:  \n\nThe above picture has detected humans, which are actuall gnome lawn ornaments!\n\n\n```python\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyjs%2Fdog-breed-classifier","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcoreyjs%2Fdog-breed-classifier","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcoreyjs%2Fdog-breed-classifier/lists"}