Commit 3381b321 authored by Billy Lamberta's avatar Billy Lamberta
Browse files

Docs: Add eager notebook to Getting Started section.

parent eb73a850
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "eager.ipynb",
"version": "0.3.2",
"views": {},
"default_view": {},
"provenance": []
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
}
},
"cells": [
{
"metadata": {
"id": "rwxGnsA92emp",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"**Copyright 2018 The TensorFlow Authors.**\n",
"\n",
"Licensed under the Apache License, Version 2.0 (the \"License\");"
]
},
{
"metadata": {
"id": "CPII1rGR2rF9",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
},
"cellView": "form"
},
"cell_type": "code",
"source": [
"#@title\n",
"# Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "JtEZ1pCPn--z",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"# Getting started using eager execution\n",
"\n",
"Note: you can run [this notebook, live in Google Colab](https://colab.research.google.com/github/tensorflow/models/blob/master/samples/core/get_started/eager.ipynb) with zero setup.\n",
"\n",
"This tutorial describes how to use machine learning to *categorize* Iris flowers by species. It uses [TensorFlow](https://www.tensorflow.org)'s eager execution to 1. build a *model*, 2. *train* the model on example data, and 3. use the model to make *predictions* on unknown data. Machine Learning experience isn't required to follow this guide, but you'll need to read some Python code.\n",
"\n",
"## TensorFlow programming\n",
"\n",
"There many [TensorFlow APIs](https://www.tensorflow.org/api_docs/python/) available, but we recommend starting with these high-level TensorFlow concepts:\n",
"\n",
"* Enable an [eager execution](https://www.tensorflow.org/programmers_guide/eager) development environment,\n",
"* Import data with the [Datasets API](https://www.tensorflow.org/programmers_guide/datasets),\n",
"* Build models and layers with TensorFlow's [Keras API](https://keras.io/getting-started/sequential-model-guide/).\n",
"\n",
"This tutorial shows these APIs and is structured like many other TensorFlow programs:\n",
"\n",
"1. Import and parse the data sets.\n",
"2. Select the type of model.\n",
"3. Train the model.\n",
"4. Evaluate the model's effectiveness.\n",
"5. Use the trained model to make predictions.\n",
"\n",
"To learn more about using TensorFlow, see the [Getting Started guide](https://www.tensorflow.org/get_started/) and the [example tutorials](https://www.tensorflow.org/tutorials/). If you'd like to learn about the basics of machine learning, consider taking the [Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course/).\n",
"\n",
"## Run the notebook\n",
"\n",
"This tutorial is available as an interactive [Colab notebook](https://colab.research.google.com) for you to run and change the Python code directly in the browser. The notebook handles setup and dependencies while you \"play\" cells to execute the code blocks. This is a fun way to explore the program and test ideas. If you are unfamiliar with Python notebook environments, there are a couple of things to keep in mind:\n",
"\n",
"1. Executing code requires connecting to a runtime environment. In the Colab notebook menu, select *Runtime > Connect to runtime...*\n",
"2. Notebook cells are arranged sequentially to gradually build the program. Typically, later code cells depend on prior code cells, though you can always rerun a code block. To execute the entire notebook in order, select *Runtime > Run all*. To rerun a code cell, select the cell and click the *play icon* on the left."
]
},
{
"metadata": {
"id": "yNr7H-AIoLOR",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Setup program"
]
},
{
"metadata": {
"id": "6qoYFqQ89aV3",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Install the latest version of TensorFlow\n",
"\n",
"This tutorial uses eager execution features available in [TensorFlow 1.7](https://www.tensorflow.org/install/). (You may need to restart the runtime after upgrading.)"
]
},
{
"metadata": {
"id": "jBmKxLVy9Uhg",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"!pip install --upgrade tensorflow"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "1J3AuPBT9gyR",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Configure imports and eager execution\n",
"\n",
"Import the required Python modules, including TensorFlow, and enable eager execution for this program. Eager execution makes TensorFlow evaluate operations immediately, returning concrete values instead of creating a [computational graph](https://www.tensorflow.org/programmers_guide/graphs) that is executed later. If you are used to a REPL or the `python` interactive console, you'll feel at home.\n",
"\n",
"Once eager execution is enabled, it *cannot* be disabled within the same program. See the [eager execution guide](https://www.tensorflow.org/programmers_guide/eager) for more details."
]
},
{
"metadata": {
"id": "g4Wzg69bnwK2",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"from __future__ import absolute_import, division, print_function\n",
"\n",
"import os\n",
"import matplotlib.pyplot as plt\n",
"\n",
"import tensorflow as tf\n",
"import tensorflow.contrib.eager as tfe\n",
"\n",
"tf.enable_eager_execution()\n",
"\n",
"print(\"TensorFlow version: {}\".format(tf.VERSION))\n",
"print(\"Eager execution: {}\".format(tf.executing_eagerly()))"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "Zx7wc0LuuxaJ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## The Iris classification problem\n",
"\n",
"Imagine you are a botanist seeking an automated way to categorize each Iris flower you find. Machine learning provides many algorithms to statistically classify flowers. For instance, a sophisticated machine learning program could classify flowers based on photographs. Our ambitions are more modest—we're going to classify Iris flowers based on the length and width measurements of their [sepals](https://en.wikipedia.org/wiki/Sepal) and [petals](https://en.wikipedia.org/wiki/Petal).\n",
"\n",
"The Iris genus entails about 300 species, but our program will classify only the following three:\n",
"\n",
"* Iris setosa\n",
"* Iris virginica\n",
"* Iris versicolor\n",
"\n",
"<figure>\n",
" <img src=\"https://www.tensorflow.org/images/iris_three_species.jpg\"\n",
" alt=\"Petal geometry compared for three iris species: Iris setosa, Iris virginica, and Iris versicolor\">\n",
" <figcaption>\n",
" **Figure 1.** [Iris setosa](https://commons.wikimedia.org/w/index.php?curid=170298) (by [Radomil](https://commons.wikimedia.org/wiki/User:Radomil), CC BY-SA 3.0), [Iris versicolor](https://commons.wikimedia.org/w/index.php?curid=248095) (by [Dlanglois](https://commons.wikimedia.org/wiki/User:Dlanglois), CC BY-SA 3.0), and [Iris virginica](https://www.flickr.com/photos/33397993@N05/3352169862) (by [Frank Mayfield](https://www.flickr.com/photos/33397993@N05), CC BY-SA 2.0).\n",
" </figcaption>\n",
"</figure>\n",
"\n",
"Fortunately, someone has already created a [data set of 120 Iris flowers](https://en.wikipedia.org/wiki/Iris_flower_data_set) with the sepal and petal measurements. This is a classic dataset that is popular for beginner machine learning classification problems."
]
},
{
"metadata": {
"id": "3Px6KAg0Jowz",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Import and parse the training dataset\n",
"\n",
"We need to download the dataset file and convert it to a structure that can be used by this Python program.\n",
"\n",
"### Download the dataset\n",
"\n",
"Download the training dataset file using the [`tf.keras.utils.get_file`](https://www.tensorflow.org/api_docs/python/tf/keras/utils/get_file) function. This returns the file path of the downloaded file."
]
},
{
"metadata": {
"id": "J6c7uEU9rjRM",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"train_dataset_url = \"http://download.tensorflow.org/data/iris_training.csv\"\n",
"\n",
"train_dataset_fp = tf.keras.utils.get_file(fname=os.path.basename(train_dataset_url),\n",
" origin=train_dataset_url)\n",
"\n",
"print(\"Local copy of the dataset file: {}\".format(train_dataset_fp))"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "qnX1-aLors4S",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Inspect the data\n",
"\n",
"This dataset, `iris_training.csv`, is a plain text file that stores tabular data formatted as comma-separated values (CSV). Use the `head -n5` command to take a peak at the first five entries:"
]
},
{
"metadata": {
"id": "FQvb_JYdrpPm",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"!head -n5 {train_dataset_fp}"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "kQhzD6P-uBoq",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"From this view of the dataset, we see the following:\n",
"\n",
"1. The first line is a header containing information about the dataset:\n",
" * There are 120 total examples. Each example has four features and one of three possible label names. \n",
"2. Subsequent rows are data records, one [*example*](https://developers.google.com/machine-learning/glossary/#example) per line, where:\n",
" * The first four fields are [*features*](https://developers.google.com/machine-learning/glossary/#feature): these are characteristics of an example. Here, the fields hold float numbers representing flower measurements.\n",
" * The last column is the [*label*](https://developers.google.com/machine-learning/glossary/#label): this is the value we want to predict. For this dataset, it's an integer value of 0, 1, or 2 that corresponds to a flower name.\n",
"\n",
"Each label is associated with string name (for example, \"setosa\"), but machine learning typically relies on numeric values. The label numbers are mapped to a named representation, such as:\n",
"\n",
"* `0`: Iris setosa\n",
"* `1`: Iris versicolor\n",
"* `2`: Iris virginica\n",
"\n",
"For more information about features and labels, see the [ML Terminology section of the Machine Learning Crash Course](https://developers.google.com/machine-learning/crash-course/framing/ml-terminology)."
]
},
{
"metadata": {
"id": "dqPkQExM2Pwt",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Parse the dataset\n",
"\n",
"Since our dataset is a CSV-formatted text file, we'll parse the feature and label values into a format our Python model can use. Each line—or row—in the file is passed to the `parse_csv` function which grabs the first four feature fields and combines them into a single tensor. Then, the last field is parsed as the label. The function returns *both* the `features` and `label` tensors:"
]
},
{
"metadata": {
"id": "2y4OgiIz2CVb",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"def parse_csv(line):\n",
" example_defaults = [[0.], [0.], [0.], [0.], [0]] # sets field types\n",
" parsed_line = tf.decode_csv(line, example_defaults)\n",
" # First 4 fields are features, combine into single tensor\n",
" features = tf.reshape(parsed_line[:-1], shape=(4,))\n",
" # Last field is the label\n",
" label = tf.reshape(parsed_line[-1], shape=())\n",
" return features, label"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "hBGYOBS7zfdQ",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Create the training tf.data.Dataset\n",
"\n",
"TensorFlow's [Dataset API](https://www.tensorflow.org/programmers_guide/datasets) handles many common cases for feeding data into a model. This is a high-level API for reading data and transforming it into a form used for training. See the [Datasets Quick Start guide](https://www.tensorflow.org/get_started/datasets_quickstart) for more information.\n",
"\n",
"This program uses [`tf.data.TextLineDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) to load a CSV-formatted text file and is parsed with our `parse_csv` function. A [`tf.data.Dataset`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset) represents an input pipeline as a collection of elements and a series of transformations that act on those elements. Transformation methods are chained together or called sequentially—just make sure to keep a reference to the returned `Dataset` object.\n",
"\n",
"Training works best if the examples are in random order. Use `tf.data.Dataset.shuffle` to randomize entries, setting `buffer_size` to a value larger than the number of examples (120 in this case). To train the model faster, the dataset's [*batch size*](https://developers.google.com/machine-learning/glossary/#batch_size) is set to `32` examples to train at once."
]
},
{
"metadata": {
"id": "7YYQUa1Hz2pP",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"train_dataset = tf.data.TextLineDataset(train_dataset_fp)\n",
"train_dataset = train_dataset.skip(1) # skip the first header row\n",
"train_dataset = train_dataset.map(parse_csv) # parse each row\n",
"train_dataset = train_dataset.shuffle(buffer_size=1000) # randomize\n",
"train_dataset = train_dataset.batch(32)\n",
"\n",
"# View a single example entry from a batch\n",
"features, label = tfe.Iterator(train_dataset).next()\n",
"print(\"example features:\", features[0])\n",
"print(\"example label:\", label[0])"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "LsaVrtNM3Tx5",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Select the type of model\n",
"\n",
"### Why model?\n",
"\n",
"A [*model*](https://developers.google.com/machine-learning/crash-course/glossary#model) is the relationship between features and the label. For the Iris classification problem, the model defines the relationship between the sepal and petal measurements and the predicted Iris species. Some simple models can be described with a few lines of algebra, but complex machine learning models have a large number of parameters that are difficult to summarize.\n",
"\n",
"Could you determine the relationship between the four features and the Iris species *without* using machine learning? That is, could you use traditional programming techniques (for example, a lot of conditional statements) to create a model? Perhaps—if you analyzed the dataset long enough to determine the relationships between petal and sepal measurements to a particular species. And this becomes difficult—maybe impossible—on more complicated datasets. A good machine learning approach *determines the model for you*. If you feed enough representative examples into the right machine learning model type, the program will figure out the relationships for you.\n",
"\n",
"### Select the model\n",
"\n",
"We need to select the kind of model to train. There are many types of models and picking a good one takes experience. This tutorial uses a neural network to solve the Iris classification problem. [*Neural networks*](https://developers.google.com/machine-learning/glossary/#neural_network) can find complex relationships between features and the label. It is a highly-structured graph, organized into one or more [*hidden layers*](https://developers.google.com/machine-learning/glossary/#hidden_layer). Each hidden layer consists of one or more [*neurons*](https://developers.google.com/machine-learning/glossary/#neuron). There are several categories of neural networks and this program uses a dense, or [*fully-connected neural network*](https://developers.google.com/machine-learning/glossary/#fully_connected_layer): the neurons in one layer receive input connections from *every* neuron in the previous layer. For example, Figure 2 illustrates a dense neural network consisting of an input layer, two hidden layers, and an output layer:\n",
"\n",
"<figure>\n",
" <img src=\"https://www.tensorflow.org/images/custom_estimators/full_network.png\"\n",
" alt=\"A diagram of the network architecture: Inputs, 2 hidden layers, and outputs\">\n",
" <figcaption>\n",
" **Figure 2.** A neural network with features, hidden layers, and predictions.\n",
" </figcaption>\n",
"</figure>\n",
"\n",
"When the model from Figure 2 is trained and fed an unlabeled example, it yields three predictions: the likelihood that this flower is the given Iris species. This prediction is called [*inference*](https://developers.google.com/machine-learning/crash-course/glossary#inference). For this example, the sum of the output predictions are 1.0. In Figure 2, this prediction breaks down as: `0.03` for *Iris setosa*, `0.95` for *Iris versicolor*, and `0.02` for *Iris virginica*. This means that the model predicts—with 95% probability—that an unlabeled example flower is an *Iris versicolor*."
]
},
{
"metadata": {
"id": "W23DIMVPQEBt",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Create a model using Keras\n",
"\n",
"The TensorFlow [`tf.keras`](https://www.tensorflow.org/api_docs/python/tf/keras) API is the preferred way to create models and layers. This makes it easy to build models and experiment while Keras handles the complexity of connecting everything together. See the [Keras documentation](https://keras.io/) for details.\n",
"\n",
"The [`tf.keras.Sequential`](https://www.tensorflow.org/api_docs/python/tf/keras/Sequential) model is a linear stack of layers. Its constructor takes a list of layer instances, in this case, two [`Dense`](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense) layers with 10 nodes each, and an output layer with 3 nodes representing our label predictions. The first layer's `input_shape` parameter corresponds to the amount of features from the dataset, and is required."
]
},
{
"metadata": {
"id": "2fZ6oL2ig3ZK",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"model = tf.keras.Sequential([\n",
" tf.keras.layers.Dense(10, activation=\"relu\", input_shape=(4,)), # input shape required\n",
" tf.keras.layers.Dense(10, activation=\"relu\"),\n",
" tf.keras.layers.Dense(3)\n",
"])"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "FHcbEzMpxbHL",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"The [*activation function*](https://developers.google.com/machine-learning/crash-course/glossary#activation_function) determines the output of a single neuron to the next layer. This is loosely based on how brain neurons are connected. There are many [available activations](https://www.tensorflow.org/api_docs/python/tf/keras/activations), but [ReLU](https://developers.google.com/machine-learning/crash-course/glossary#ReLU) is common for hidden layers.\n",
"\n",
"The ideal number of hidden layers and neurons depends on the problem and the dataset. Like many aspects of machine learning, picking the best shape of the neural network requires a mixture of knowledge and experimentation. As a rule of thumb, increasing the number of hidden layers and neurons typically creates a more powerful model, which requires more data to train effectively."
]
},
{
"metadata": {
"id": "Vzq2E5J2QMtw",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Train the model\n",
"\n",
"[*Training*](https://developers.google.com/machine-learning/crash-course/glossary#training) is the stage of machine learning when the model is gradually optimized, or the model *learns* the dataset. The goal is to learn enough about the structure of the training dataset to make predictions about unseen data. If you learn *too much* about the training dataset, then the predictions only work for the data it has seen and will not be generalizable. This problem is called [*overfitting*](https://developers.google.com/machine-learning/crash-course/glossary#overfitting)—it's like memorizing the answers instead of understanding how to solve a problem.\n",
"\n",
"The Iris classification problem is an example of [*supervised machine learning*](https://developers.google.com/machine-learning/glossary/#supervised_machine_learning): the model is trained from examples that contain labels. In [*unsupervised machine learning*](https://developers.google.com/machine-learning/glossary/#unsupervised_machine_learning), the examples don't contain labels. Instead, the model typically finds patterns among the features."
]
},
{
"metadata": {
"id": "RaKp8aEjKX6B",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Define the loss and gradient function\n",
"\n",
"Both training and evaluation stages need to calculate the model's [*loss*](https://developers.google.com/machine-learning/crash-course/glossary#loss). This measures how off a model's predictions are from the desired label, in other words, how bad the model is performing. We want to minimize, or optimize, this value.\n",
"\n",
"Our model will calculate its loss using the [`tf.losses.sparse_softmax_cross_entropy`](https://www.tensorflow.org/api_docs/python/tf/losses/sparse_softmax_cross_entropy) function which takes the model's prediction and the desired label. The returned loss value is progressively larger as the prediction gets worse."
]
},
{
"metadata": {
"id": "x57HcKWhKkei",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"def loss(model, x, y):\n",
" y_ = model(x)\n",
" return tf.losses.sparse_softmax_cross_entropy(labels=y, logits=y_)\n",
"\n",
"\n",
"def grad(model, inputs, targets):\n",
" with tfe.GradientTape() as tape:\n",
" loss_value = loss(model, inputs, targets)\n",
" return tape.gradient(loss_value, model.variables)"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "RtVOFpb21Krp",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"The `grad` function uses the `loss` function and the [`tfe.GradientTape`](https://www.tensorflow.org/api_docs/python/tf/contrib/eager/GradientTape) to record operations that compute the [*gradients*](https://developers.google.com/machine-learning/crash-course/glossary#gradient) used to optimize our model. For more examples of this, see the [eager execution guide](https://www.tensorflow.org/programmers_guide/eager)."
]
},
{
"metadata": {
"id": "lOxFimtlKruu",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Create an optimizer\n",
"\n",
"An [*optimizer*](https://developers.google.com/machine-learning/crash-course/glossary#optimizer) applies the computed gradients to the model's variables to minimize the `loss` function. You can think of a curved surface (see Figure 3) and we want to find its lowest point by walking around. The gradients point in the direction of steepest the ascent—so we'll travel the opposite way and move down the hill. By iteratively calculating the loss and gradients for each *step* (or [*learning rate*](https://developers.google.com/machine-learning/crash-course/glossary#learning_rate)), we'll adjust the model during training. Gradually, the model will find the best combination of weights and bias to minimize loss. And the lower the loss, the better the model's predictions.\n",
"\n",
"<figure>\n",
" <img src=\"http://cs231n.github.io/assets/nn3/opt1.gif\" alt=\"\" width=\"45%\">\n",
" <figcaption>\n",
" **Figure 3.** Optimization algorthims visualized over time in 3D space. (Source: [Stanford class CS231n](http://cs231n.github.io/neural-networks-3/), MIT License)\n",
" </figcaption>\n",
"</figure>\n",
"\n",
"TensorFlow has many [optimization algorithms](https://www.tensorflow.org/api_guides/python/train) available for training. This model uses the [`tf.train.GradientDescentOptimizer`](https://www.tensorflow.org/versions/r1.0/api_docs/python/tf/train/GradientDescentOptimizer) that implements the [*standard gradient descent*](https://developers.google.com/machine-learning/crash-course/glossary#gradient_descent) (SGD) algorithm. The `learning_rate` sets the step size to take for each iteration down the hill. This is a *hyperparameter* that you'll commonly adjust to achieve better results."
]
},
{
"metadata": {
"id": "8xxi2NNGKwG_",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "7Y2VSELvwAvW",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Training loop\n",
"\n",
"With all the pieces in place, the model is ready for training! A training loop feeds the dataset examples into the model to help it make better predictions. The following code block sets up these training steps:\n",
"\n",
"1. Iterate each epoch. An epoch is one pass through the dataset.\n",
"2. Within an epoch, iterate over each example in the training `Dataset` grabbing its *features* (`x`) and *label* (`y`).\n",
"3. Using the example's features, make a prediction and compare it with the label. Measure the inaccuracy of the prediction and use that to calculate the model's loss and gradients.\n",
"4. Use an `optimizer` to update the model's variables.\n",
"5. Keep track of some stats for visualization.\n",
"6. Repeat for each epoch.\n",
"\n",
"The `num_epochs` variable is the amount of times to loop over the dataset collection. Counter-intuitively, training a model longer does not guarantee a better model. `num_epochs` is a [*hyperparameter*](https://developers.google.com/machine-learning/glossary/#hyperparameter) that you can tune. Choosing the right number usually requires both experience and experimentation."
]
},
{
"metadata": {
"id": "AIgulGRUhpto",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"## Note: Rerunning this cell uses the same model variables\n",
"\n",
"# keep results for plotting\n",
"train_loss_results = []\n",
"train_accuracy_results = []\n",
"\n",
"num_epochs = 201\n",
"\n",
"for epoch in range(num_epochs):\n",
" epoch_loss_avg = tfe.metrics.Mean()\n",
" epoch_accuracy = tfe.metrics.Accuracy()\n",
"\n",
" # Training loop - using batches of 32\n",
" for x, y in tfe.Iterator(train_dataset):\n",
" # Optimize the model\n",
" grads = grad(model, x, y)\n",
" optimizer.apply_gradients(zip(grads, model.variables),\n",
" global_step=tf.train.get_or_create_global_step())\n",
"\n",
" # Track progress\n",
" epoch_loss_avg(loss(model, x, y)) # add current batch loss\n",
" # compare predicted label to actual label\n",
" epoch_accuracy(tf.argmax(model(x), axis=1, output_type=tf.int32), y)\n",
"\n",
" # end epoch\n",
" train_loss_results.append(epoch_loss_avg.result())\n",
" train_accuracy_results.append(epoch_accuracy.result())\n",
" \n",
" if epoch % 50 == 0:\n",
" print(\"Epoch {:03d}: Loss: {:.3f}, Accuracy: {:.3%}\".format(epoch,\n",
" epoch_loss_avg.result(),\n",
" epoch_accuracy.result()))"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "2FQHVUnm_rjw",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Visualize the loss function over time"
]
},
{
"metadata": {
"id": "j3wdbmtLVTyr",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"While it's helpful to print out the model's training progress, it's often *more helpful* to see this progress. [TensorBoard](https://www.tensorflow.org/programmers_guide/summaries_and_tensorboard) is a nice visualization tool that is packaged with TensorFlow, but we can create basic charts using the `mathplotlib` module.\n",
"\n",
"Interpreting these charts takes some experience, but you really want to see the *loss* go down and the *accuracy* go up."
]
},
{
"metadata": {
"id": "agjvNd2iUGFn",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"fig, axes = plt.subplots(2, sharex=True, figsize=(12, 8))\n",
"fig.suptitle('Training Metrics')\n",
"\n",
"axes[0].set_ylabel(\"Loss\", fontsize=14)\n",
"axes[0].plot(train_loss_results)\n",
"\n",
"axes[1].set_ylabel(\"Accuracy\", fontsize=14)\n",
"axes[1].set_xlabel(\"Epoch\", fontsize=14)\n",
"axes[1].plot(train_accuracy_results)\n",
"\n",
"plt.show()"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "Zg8GoMZhLpGH",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Evaluate the model's effectiveness\n",
"\n",
"Now that the model is trained, we can get some statistics on its performance.\n",
"\n",
"*Evaluating* means determining how effectively the model makes predictions. To determine the model's effectiveness at Iris classification, pass some sepal and petal measurements to the model and ask the model to predict what Iris species they represent. Then compare the model's prediction against the actual label. For example, a model that picked the correct species on half the input examples has an [*accuracy*](https://developers.google.com/machine-learning/glossary/#accuracy) of `0.5`. Figure 4 shows a slightly more effective model, getting 4 out of 5 predictions correct at 80% accuracy:\n",
"\n",
"<figure>\n",
" <table cellpadding=\"8\" border=\"0\">\n",
" <colgroup>\n",
" <col span=\"4\" >\n",
" <col span=\"1\" bgcolor=\"lightblue\">\n",
" <col span=\"1\" bgcolor=\"lightgreen\">\n",
" </colgroup>\n",
" <tr bgcolor=\"lightgray\">\n",
" <th colspan=\"4\">Example features</th>\n",
" <th colspan=\"1\">Label</th>\n",
" <th colspan=\"1\" >Model prediction</th>\n",
" </tr>\n",
" <tr>\n",
" <td>5.9</td><td>3.0</td><td>4.3</td><td>1.5</td><td align=\"center\">1</td><td align=\"center\">1</td>\n",
" </tr>\n",
" <tr>\n",
" <td>6.9</td><td>3.1</td><td>5.4</td><td>2.1</td><td align=\"center\">2</td><td align=\"center\">2</td>\n",
" </tr>\n",
" <tr>\n",
" <td>5.1</td><td>3.3</td><td>1.7</td><td>0.5</td><td align=\"center\">0</td><td align=\"center\">0</td>\n",
" </tr>\n",
" <tr>\n",
" <td>6.0</td> <td>3.4</td> <td>4.5</td> <td>1.6</td> <td align=\"center\">1</td><td align=\"center\" bgcolor=\"red\">2</td>\n",
" </tr>\n",
" <tr>\n",
" <td>5.5</td><td>2.5</td><td>4.0</td><td>1.3</td><td align=\"center\">1</td><td align=\"center\">1</td>\n",
" </tr>\n",
" </table>\n",
" <figcaption>**Figure 4.** An Iris classifier that is 80% accurate.</figcaption>\n",
"</figure>"
]
},
{
"metadata": {
"id": "z-EvK7hGL0d8",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Setup the test dataset\n",
"\n",
"Evaluating the model is similiar to training the model. The biggest difference is the examples come from a separate [*test set*](https://developers.google.com/machine-learning/crash-course/glossary#test_set) rather than the training set. To fairly assess a model's effectiveness, the examples used to evaluate a model must be different from the examples used to train the model.\n",
"\n",
"The setup for the test `Dataset` is similiar to the setup for training `Dataset`. Download the CSV text file and parse that values, then give it a little shuffle:"
]
},
{
"metadata": {
"id": "Ps3_9dJ3Lodk",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"test_url = \"http://download.tensorflow.org/data/iris_test.csv\"\n",
"\n",
"test_fp = tf.keras.utils.get_file(fname=os.path.basename(test_url),\n",
" origin=test_url)\n",
"\n",
"test_dataset = tf.data.TextLineDataset(test_fp)\n",
"test_dataset = test_dataset.skip(1) # skip header row\n",
"test_dataset = test_dataset.map(parse_csv) # parse each row with the funcition created earlier\n",
"test_dataset = test_dataset.shuffle(1000) # randomize\n",
"test_dataset = test_dataset.batch(32) # use the same batch size as the training set"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "HFuOKXJdMAdm",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"### Evaluate the model on the test dataset\n",
"\n",
"Unlike the training stage, the model only evaluates a single [epoch](https://developers.google.com/machine-learning/glossary/#epoch) of the test data. In the following code cell, we iterate over each example in the test set and compare the model's prediction against the actual label. This is used to measure the model's accuracy across the entire test set."
]
},
{
"metadata": {
"id": "Tw03-MK1cYId",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"test_accuracy = tfe.metrics.Accuracy()\n",
"\n",
"for (x, y) in tfe.Iterator(test_dataset):\n",
" prediction = tf.argmax(model(x), axis=1, output_type=tf.int32)\n",
" test_accuracy(prediction, y)\n",
"\n",
"print(\"Test set accuracy: {:.3%}\".format(test_accuracy.result()))"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "7Li2r1tYvW7S",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"## Use the trained model to make predictions\n",
"\n",
"We've trained a model and \"proven\" that it's good—but not perfect—at classifying Iris species. Now let's use the trained model to make some predictions on [unlabeled examples](https://developers.google.com/machine-learning/glossary/#unlabeled_example); that is, on examples that contain features but not a label.\n",
"\n",
"In real-life, the unlabeled examples could come from lots of different sources including apps, CSV files, and data feeds. For now, we're going to manually provide three unlabeled examples to predict their labels. Recall, the label numbers are mapped to a named representation as:\n",
"\n",
"* `0`: Iris setosa\n",
"* `1`: Iris versicolor\n",
"* `2`: Iris virginica"
]
},
{
"metadata": {
"id": "kesTS5Lzv-M2",
"colab_type": "code",
"colab": {
"autoexec": {
"startup": false,
"wait_interval": 0
}
}
},
"cell_type": "code",
"source": [
"class_ids = [\"Iris setosa\", \"Iris versicolor\", \"Iris virginica\"]\n",
"\n",
"predict_dataset = tf.convert_to_tensor([\n",
" [5.1, 3.3, 1.7, 0.5,],\n",
" [5.9, 3.0, 4.2, 1.5,],\n",
" [6.9, 3.1, 5.4, 2.1]\n",
"])\n",
"\n",
"predictions = model(predict_dataset)\n",
"\n",
"for i, logits in enumerate(predictions):\n",
" class_idx = tf.argmax(logits).numpy()\n",
" name = class_ids[class_idx]\n",
" print(\"Example {} prediction: {}\".format(i, name))"
],
"execution_count": 0,
"outputs": []
},
{
"metadata": {
"id": "HUZEWdD9zupu",
"colab_type": "text"
},
"cell_type": "markdown",
"source": [
"These predictions look good!\n",
"\n",
"To dig deeper into machine learning models, take a look at the TensorFlow [Programmer's Guide](https://www.tensorflow.org/programmers_guide/) and check out the [community](https://www.tensorflow.org/community/)."
]
}
]
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment