aboutsummaryrefslogtreecommitdiffhomepage
path: root/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb
diff options
context:
space:
mode:
Diffstat (limited to 'tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb')
-rw-r--r--tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb491
1 files changed, 491 insertions, 0 deletions
diff --git a/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb b/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb
new file mode 100644
index 0000000000..f1e13de5de
--- /dev/null
+++ b/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb
@@ -0,0 +1,491 @@
+{
+ "nbformat": 4,
+ "nbformat_minor": 0,
+ "metadata": {
+ "colab": {
+ "name": "eager_basics.ipynb",
+ "version": "0.3.2",
+ "views": {},
+ "default_view": {},
+ "provenance": [],
+ "private_outputs": true,
+ "collapsed_sections": [],
+ "toc_visible": true
+ },
+ "kernelspec": {
+ "name": "python3",
+ "display_name": "Python 3"
+ }
+ },
+ "cells": [
+ {
+ "metadata": {
+ "id": "iPpI7RaYoZuE",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "##### Copyright 2018 The TensorFlow Authors."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "hro2InpHobKk",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "form"
+ },
+ "cell_type": "code",
+ "source": [
+ "#@title 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": "U9i2Dsh-ziXr",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "# Eager execution basics"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "Hndw-YcxoOJK",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "<table class=\"tfo-notebook-buttons\" align=\"left\"><td>\n",
+ "<a target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb\">\n",
+ " <img src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" />Run in Google Colab</a>\n",
+ "</td><td>\n",
+ "<a target=\"_blank\" href=\"https://github.com/tensorflow/tensorflow/blob/master/tensorflow/contrib/eager/python/examples/notebooks/eager_basics.ipynb\"><img width=32px src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" />View source on GitHub</a></td></table>"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "6sILUVbHoSgH",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "This is an introductory tutorial for using TensorFlow. It will cover:\n",
+ "\n",
+ "* Importing required packages\n",
+ "* Creating and using Tensors\n",
+ "* Using GPU acceleration\n",
+ "* Datasets"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "z1JcS5iBXMRO",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "## Import TensorFlow\n",
+ "\n",
+ "To get started, import the `tensorflow` module and enable eager execution.\n",
+ "Eager execution enables a more interactive frontend to TensorFlow, the details of which we will discuss much later."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "RlIWhyeLoYnG",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "code"
+ },
+ "cell_type": "code",
+ "source": [
+ "import tensorflow as tf\n",
+ "\n",
+ "tf.enable_eager_execution()"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "H9UySOPLXdaw",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "## Tensors\n",
+ "\n",
+ "A Tensor is a multi-dimensional array. Similar to NumPy `ndarray` objects, `Tensor` objects have a data type and a shape. Additionally, Tensors can reside in accelerator (like GPU) memory. TensorFlow offers a rich library of operations ([tf.add](https://www.tensorflow.org/api_docs/python/tf/add), [tf.matmul](https://www.tensorflow.org/api_docs/python/tf/matmul), [tf.linalg.inv](https://www.tensorflow.org/api_docs/python/tf/linalg/inv) etc.) that consume and produce Tensors. These operations automatically convert native Python types. For example:\n"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "ngUe237Wt48W",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "code"
+ },
+ "cell_type": "code",
+ "source": [
+ "print(tf.add(1, 2))\n",
+ "print(tf.add([1, 2], [3, 4]))\n",
+ "print(tf.square(5))\n",
+ "print(tf.reduce_sum([1, 2, 3]))\n",
+ "print(tf.encode_base64(\"hello world\"))\n",
+ "\n",
+ "# Operator overloading is also supported\n",
+ "print(tf.square(2) + tf.square(3))"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "IDY4WsYRhP81",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "Each Tensor has a shape and a datatype"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "srYWH1MdJNG7",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ }
+ },
+ "cell_type": "code",
+ "source": [
+ "x = tf.matmul([[1]], [[2, 3]])\n",
+ "print(x.shape)\n",
+ "print(x.dtype)"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "eBPw8e8vrsom",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "The most obvious differences between NumPy arrays and TensorFlow Tensors are:\n",
+ "\n",
+ "1. Tensors can be backed by accelerator memory (like GPU, TPU).\n",
+ "2. Tensors are immutable."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "Dwi1tdW3JBw6",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "### NumPy Compatibility\n",
+ "\n",
+ "Conversion between TensorFlow Tensors and NumPy ndarrays is quite simple as:\n",
+ "* TensorFlow operations automatically convert NumPy ndarrays to Tensors.\n",
+ "* NumPy operations automatically convert Tensors to NumPy ndarrays.\n",
+ "\n",
+ "Tensors can be explicitly converted to NumPy ndarrays by invoking the `.numpy()` method on them.\n",
+ "These conversions are typically cheap as the array and Tensor share the underlying memory representation if possible. However, sharing the underlying representation isn't always possible since the Tensor may be hosted in GPU memory while NumPy arrays are always backed by host memory, and the conversion will thus involve a copy from GPU to host memory."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "lCUWzso6mbqR",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ }
+ },
+ "cell_type": "code",
+ "source": [
+ "import numpy as np\n",
+ "\n",
+ "ndarray = np.ones([3, 3])\n",
+ "\n",
+ "print(\"TensorFlow operations convert numpy arrays to Tensors automatically\")\n",
+ "tensor = tf.multiply(ndarray, 42)\n",
+ "print(tensor)\n",
+ "\n",
+ "\n",
+ "print(\"And NumPy operations convert Tensors to numpy arrays automatically\")\n",
+ "print(np.add(tensor, 1))\n",
+ "\n",
+ "print(\"The .numpy() method explicitly converts a Tensor to a numpy array\")\n",
+ "print(tensor.numpy())"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "PBNP8yTRfu_X",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "## GPU acceleration\n",
+ "\n",
+ "Many TensorFlow operations can be accelerated by using the GPU for computation. Without any annotations, TensorFlow automatically decides whether to use the GPU or CPU for an operation (and copies the tensor between CPU and GPU memory if necessary). Tensors produced by an operation are typically backed by the memory of the device on which the operation executed. For example:"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "3Twf_Rw-gQFM",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ },
+ "cellView": "code"
+ },
+ "cell_type": "code",
+ "source": [
+ "x = tf.random_uniform([3, 3])\n",
+ "\n",
+ "print(\"Is there a GPU available: \"),\n",
+ "print(tf.test.is_gpu_available())\n",
+ "\n",
+ "print(\"Is the Tensor on GPU #0: \"),\n",
+ "print(x.device.endswith('GPU:0'))"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "vpgYzgVXW2Ud",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "### Device Names\n",
+ "\n",
+ "The `Tensor.device` property provides a fully qualified string name of the device hosting the contents of the Tensor. This name encodes a bunch of details, such as an identifier of the network address of the host on which this program is executing and the device within that host. This is required for distributed execution of TensorFlow programs, but we'll skip that for now. The string will end with `GPU:<N>` if the tensor is placed on the `N`-th tensor on the host."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "ZWZQCimzuqyP",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "\n",
+ "\n",
+ "### Explicit Device Placement\n",
+ "\n",
+ "The term \"placement\" in TensorFlow refers to how individual operations are assigned (placed on) a device for execution. As mentioned above, when there is no explicit guidance provided, TensorFlow automatically decides which device to execute an operation, and copies Tensors to that device if needed. However, TensorFlow operations can be explicitly placed on specific devices using the `tf.device` context manager. For example:"
+ ]
+ },
+ {
+ "metadata": {
+ "id": "RjkNZTuauy-Q",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ }
+ },
+ "cell_type": "code",
+ "source": [
+ "def time_matmul(x):\n",
+ " %timeit tf.matmul(x, x)\n",
+ "\n",
+ "# Force execution on CPU\n",
+ "print(\"On CPU:\")\n",
+ "with tf.device(\"CPU:0\"):\n",
+ " x = tf.random_uniform([1000, 1000])\n",
+ " assert x.device.endswith(\"CPU:0\")\n",
+ " time_matmul(x)\n",
+ "\n",
+ "# Force execution on GPU #0 if available\n",
+ "if tf.test.is_gpu_available():\n",
+ " with tf.device(\"GPU:0\"): # Or GPU:1 for the 2nd GPU, GPU:2 for the 3rd etc.\n",
+ " x = tf.random_uniform([1000, 1000])\n",
+ " assert x.device.endswith(\"GPU:0\")\n",
+ " time_matmul(x)"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "o1K4dlhhHtQj",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "## Datasets\n",
+ "\n",
+ "This section demonstrates the use of the [`tf.data.Dataset` API](https://www.tensorflow.org/guide/datasets) to build pipelines to feed data to your model. It covers:\n",
+ "\n",
+ "* Creating a `Dataset`.\n",
+ "* Iteration over a `Dataset` with eager execution enabled.\n",
+ "\n",
+ "We recommend using the `Dataset`s API for building performant, complex input pipelines from simple, re-usable pieces that will feed your model's training or evaluation loops.\n",
+ "\n",
+ "If you're familiar with TensorFlow graphs, the API for constructing the `Dataset` object remains exactly the same when eager execution is enabled, but the process of iterating over elements of the dataset is slightly simpler.\n",
+ "You can use Python iteration over the `tf.data.Dataset` object and do not need to explicitly create an `tf.data.Iterator` object.\n",
+ "As a result, the discussion on iterators in the [TensorFlow Guide](https://www.tensorflow.org/guide/datasets) is not relevant when eager execution is enabled."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "zI0fmOynH-Ne",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "### Create a source `Dataset`\n",
+ "\n",
+ "Create a _source_ dataset using one of the factory functions like [`Dataset.from_tensors`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensors), [`Dataset.from_tensor_slices`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#from_tensor_slices) or using objects that read from files like [`TextLineDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TextLineDataset) or [`TFRecordDataset`](https://www.tensorflow.org/api_docs/python/tf/data/TFRecordDataset). See the [TensorFlow Guide](https://www.tensorflow.org/guide/datasets#reading_input_data) for more information."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "F04fVOHQIBiG",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ }
+ },
+ "cell_type": "code",
+ "source": [
+ "ds_tensors = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5, 6])\n",
+ "\n",
+ "# Create a CSV file\n",
+ "import tempfile\n",
+ "_, filename = tempfile.mkstemp()\n",
+ "\n",
+ "with open(filename, 'w') as f:\n",
+ " f.write(\"\"\"Line 1\n",
+ "Line 2\n",
+ "Line 3\n",
+ " \"\"\")\n",
+ "\n",
+ "ds_file = tf.data.TextLineDataset(filename)"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "vbxIhC-5IPdf",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "### Apply transformations\n",
+ "\n",
+ "Use the transformations functions like [`map`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#map), [`batch`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#batch), [`shuffle`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset#shuffle) etc. to apply transformations to the records of the dataset. See the [API documentation for `tf.data.Dataset`](https://www.tensorflow.org/api_docs/python/tf/data/Dataset) for details."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "uXSDZWE-ISsd",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ }
+ },
+ "cell_type": "code",
+ "source": [
+ "ds_tensors = ds_tensors.map(tf.square).shuffle(2).batch(2)\n",
+ "\n",
+ "ds_file = ds_file.batch(2)"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ },
+ {
+ "metadata": {
+ "id": "A8X1GNfoIZKJ",
+ "colab_type": "text"
+ },
+ "cell_type": "markdown",
+ "source": [
+ "### Iterate\n",
+ "\n",
+ "When eager execution is enabled `Dataset` objects support iteration.\n",
+ "If you're familiar with the use of `Dataset`s in TensorFlow graphs, note that there is no need for calls to `Dataset.make_one_shot_iterator()` or `get_next()` calls."
+ ]
+ },
+ {
+ "metadata": {
+ "id": "ws-WKRk5Ic6-",
+ "colab_type": "code",
+ "colab": {
+ "autoexec": {
+ "startup": false,
+ "wait_interval": 0
+ }
+ }
+ },
+ "cell_type": "code",
+ "source": [
+ "print('Elements of ds_tensors:')\n",
+ "for x in ds_tensors:\n",
+ " print(x)\n",
+ "\n",
+ "print('\\nElements in ds_file:')\n",
+ "for x in ds_file:\n",
+ " print(x)"
+ ],
+ "execution_count": 0,
+ "outputs": []
+ }
+ ]
+} \ No newline at end of file