{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "! [ -e /content ] && pip install -Uqq fastbook\n",
    "import fastbook\n",
    "fastbook.setup_book()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "from fastbook import *"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Your Deep Learning Journey"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deep Learning Is for Everyone"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Neural Networks: A Brief History"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Who We Are"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## How to Learn Deep Learning"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Your Projects and Your Mindset"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## The Software: PyTorch, fastai, and Jupyter"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Your First Model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Getting a GPU Deep Learning Server"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Running Your First Notebook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# CLICK ME\n",
    "from fastai.vision.all import *\n",
    "path = untar_data(URLs.PETS)/'images'\n",
    "\n",
    "def is_cat(x): return x[0].isupper()\n",
    "dls = ImageDataLoaders.from_name_func(\n",
    "    path, get_image_files(path), valid_pct=0.2, seed=42,\n",
    "    label_func=is_cat, item_tfms=Resize(224))\n",
    "\n",
    "learn = vision_learner(dls, resnet34, metrics=error_rate)\n",
    "learn.fine_tune(1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sidebar: This Book Was Written in Jupyter Notebooks"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "1+1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = PILImage.create(image_cat())\n",
    "img.to_thumb(192)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### End sidebar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "uploader = widgets.FileUpload()\n",
    "uploader"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "#hide\n",
    "# For the book, we can't actually click an upload button, so we fake it\n",
    "uploader = SimpleNamespace(data = ['images/chapter1_cat_example.jpg'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "img = PILImage.create(uploader.data[0])\n",
    "is_cat,_,probs = learn.predict(img)\n",
    "print(f\"Is this a cat?: {is_cat}.\")\n",
    "print(f\"Probability it's a cat: {probs[1].item():.6f}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What Is Machine Learning?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gv('''program[shape=box3d width=1 height=0.7]\n",
    "inputs->program->results''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gv('''model[shape=box3d width=1 height=0.7]\n",
    "inputs->model->results; weights->model''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gv('''ordering=in\n",
    "model[shape=box3d width=1 height=0.7]\n",
    "inputs->model->results; weights->model; results->performance\n",
    "performance->weights[constraint=false label=update]''')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gv('''model[shape=box3d width=1 height=0.7]\n",
    "inputs->model->results''')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What Is a Neural Network?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### A Bit of Deep Learning Jargon"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gv('''ordering=in\n",
    "model[shape=box3d width=1 height=0.7 label=architecture]\n",
    "inputs->model->predictions; parameters->model; labels->loss; predictions->loss\n",
    "loss->parameters[constraint=false label=update]''')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Limitations Inherent To Machine Learning\n",
    "\n",
    "From this picture we can now see some fundamental things about training a deep learning model:\n",
    "\n",
    "- A model cannot be created without data.\n",
    "- A model can only learn to operate on the patterns seen in the input data used to train it.\n",
    "- This learning approach only creates *predictions*, not recommended *actions*.\n",
    "- It's not enough to just have examples of input data; we need *labels* for that data too (e.g., pictures of dogs and cats aren't enough to train a model; we need a label for each one, saying which ones are dogs, and which are cats).\n",
    "\n",
    "Generally speaking, we've seen that most organizations that say they don't have enough data, actually mean they don't have enough *labeled* data. If any organization is interested in doing something in practice with a model, then presumably they have some inputs they plan to run their model against. And presumably they've been doing that some other way for a while (e.g., manually, or with some heuristic program), so they have data from those processes! For instance, a radiology practice will almost certainly have an archive of medical scans (since they need to be able to check how their patients are progressing over time), but those scans may not have structured labels containing a list of diagnoses or interventions (since radiologists generally create free-text natural language reports, not structured data). We'll be discussing labeling approaches a lot in this book, because it's such an important issue in practice.\n",
    "\n",
    "Since these kinds of machine learning models can only make *predictions* (i.e., attempt to replicate labels), this can result in a significant gap between organizational goals and model capabilities. For instance, in this book you'll learn how to create a *recommendation system* that can predict what products a user might purchase. This is often used in e-commerce, such as to customize products shown on a home page by showing the highest-ranked items. But such a model is generally created by looking at a user and their buying history (*inputs*) and what they went on to buy or look at (*labels*), which means that the model is likely to tell you about products the user already has or already knows about, rather than new products that they are most likely to be interested in hearing about. That's very different to what, say, an expert at your local bookseller might do, where they ask questions to figure out your taste, and then tell you about authors or series that you've never heard of before."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### How Our Image Recognizer Works"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### What Our Image Recognizer Learned"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Image Recognizers Can Tackle Non-Image Tasks"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Jargon Recap"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Deep Learning Is Not Just for Image Classification"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "path = untar_data(URLs.CAMVID_TINY)\n",
    "dls = SegmentationDataLoaders.from_label_func(\n",
    "    path, bs=8, fnames = get_image_files(path/\"images\"),\n",
    "    label_func = lambda o: path/'labels'/f'{o.stem}_P{o.suffix}',\n",
    "    codes = np.loadtxt(path/'codes.txt', dtype=str)\n",
    ")\n",
    "\n",
    "learn = unet_learner(dls, resnet34)\n",
    "learn.fine_tune(8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "learn.show_results(max_n=6, figsize=(7,8))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fastai.text.all import *\n",
    "\n",
    "dls = TextDataLoaders.from_folder(untar_data(URLs.IMDB), valid='test')\n",
    "learn = text_classifier_learner(dls, AWD_LSTM, drop_mult=0.5, metrics=accuracy)\n",
    "learn.fine_tune(4, 1e-2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If you hit a \"CUDA out of memory error\" after running this cell, click on the menu Kernel, then restart. Instead of executing the cell above, copy and paste the following code in it:\n",
    "\n",
    "```\n",
    "from fastai.text.all import *\n",
    "\n",
    "dls = TextDataLoaders.from_folder(untar_data(URLs.IMDB), valid='test', bs=32)\n",
    "learn = text_classifier_learner(dls, AWD_LSTM, drop_mult=0.5, metrics=accuracy)\n",
    "learn.fine_tune(4, 1e-2)\n",
    "```\n",
    "\n",
    "This reduces the batch size to 32 (we will explain this later). If you keep hitting the same error, change 32 to 16."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "learn.predict(\"I really liked that movie!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sidebar: The Order Matters"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### End sidebar"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fastai.tabular.all import *\n",
    "path = untar_data(URLs.ADULT_SAMPLE)\n",
    "\n",
    "dls = TabularDataLoaders.from_csv(path/'adult.csv', path=path, y_names=\"salary\",\n",
    "    cat_names = ['workclass', 'education', 'marital-status', 'occupation',\n",
    "                 'relationship', 'race'],\n",
    "    cont_names = ['age', 'fnlwgt', 'education-num'],\n",
    "    procs = [Categorify, FillMissing, Normalize])\n",
    "\n",
    "learn = tabular_learner(dls, metrics=accuracy)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "learn.fit_one_cycle(3)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from fastai.collab import *\n",
    "path = untar_data(URLs.ML_SAMPLE)\n",
    "dls = CollabDataLoaders.from_csv(path/'ratings.csv')\n",
    "learn = collab_learner(dls, y_range=(0.5,5.5))\n",
    "learn.fine_tune(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "learn.show_results()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Sidebar: Datasets: Food for Models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### End sidebar"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Validation Sets and Test Sets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Use Judgment in Defining Test Sets"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## A _Choose Your Own Adventure_ moment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Questionnaire"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It can be hard to know in pages and pages of prose what the key things are that you really need to focus on and remember. So, we've prepared a list of questions and suggested steps to complete at the end of each chapter. All the answers are in the text of the chapter, so if you're not sure about anything here, reread that part of the text and make sure you understand it. Answers to all these questions are also available on the [book's website](https://book.fast.ai). You can also visit [the forums](https://forums.fast.ai) if you get stuck to get help from other folks studying this material.\n",
    "\n",
    "For more questions, including detailed answers and links to the video timeline, have a look at Radek Osmulski's [aiquizzes](http://aiquizzes.com/howto)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Do you need these for deep learning?\n",
    "\n",
    "   - Lots of math T / F\n",
    "   - Lots of data T / F\n",
    "   - Lots of expensive computers T / F\n",
    "   - A PhD T / F\n",
    "   \n",
    "1. Name five areas where deep learning is now the best in the world.\n",
    "1. What was the name of the first device that was based on the principle of the artificial neuron?\n",
    "1. Based on the book of the same name, what are the requirements for parallel distributed processing (PDP)?\n",
    "1. What were the two theoretical misunderstandings that held back the field of neural networks?\n",
    "1. What is a GPU?\n",
    "1. Open a notebook and execute a cell containing: `1+1`. What happens?\n",
    "1. Follow through each cell of the stripped version of the notebook for this chapter. Before executing each cell, guess what will happen.\n",
    "1. Complete the Jupyter Notebook online appendix.\n",
    "1. Why is it hard to use a traditional computer program to recognize images in a photo?\n",
    "1. What did Samuel mean by \"weight assignment\"?\n",
    "1. What term do we normally use in deep learning for what Samuel called \"weights\"?\n",
    "1. Draw a picture that summarizes Samuel's view of a machine learning model.\n",
    "1. Why is it hard to understand why a deep learning model makes a particular prediction?\n",
    "1. What is the name of the theorem that shows that a neural network can solve any mathematical problem to any level of accuracy?\n",
    "1. What do you need in order to train a model?\n",
    "1. How could a feedback loop impact the rollout of a predictive policing model?\n",
    "1. Do we always have to use 224×224-pixel images with the cat recognition model?\n",
    "1. What is the difference between classification and regression?\n",
    "1. What is a validation set? What is a test set? Why do we need them?\n",
    "1. What will fastai do if you don't provide a validation set?\n",
    "1. Can we always use a random sample for a validation set? Why or why not?\n",
    "1. What is overfitting? Provide an example.\n",
    "1. What is a metric? How does it differ from \"loss\"?\n",
    "1. How can pretrained models help?\n",
    "1. What is the \"head\" of a model?\n",
    "1. What kinds of features do the early layers of a CNN find? How about the later layers?\n",
    "1. Are image models only useful for photos?\n",
    "1. What is an \"architecture\"?\n",
    "1. What is segmentation?\n",
    "1. What is `y_range` used for? When do we need it?\n",
    "1. What are \"hyperparameters\"?\n",
    "1. What's the best way to avoid failures when using AI in an organization?"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Further Research"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each chapter also has a \"Further Research\" section that poses questions that aren't fully answered in the text, or gives more advanced assignments. Answers to these questions aren't on the book's website; you'll need to do your own research!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "1. Why is a GPU useful for deep learning? How is a CPU different, and why is it less effective for deep learning?\n",
    "1. Try to think of three areas where feedback loops might impact the use of machine learning. See if you can find documented examples of that happening in practice."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "jupytext": {
   "split_at_heading": true
  },
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
