Docsity

Learning TensorFlow: aprenda TensorfFow, do básico ao avançado, Notas de estudo de Inteligência Artificial

Pré-visualização parcial do texto

Baixe Learning TensorFlow: aprenda TensorfFow, do básico ao avançado e outras Notas de estudo em PDF para Inteligência Artificial, somente na Docsity!

Tom Hope, Yehezkel S. Resheff & Itay Lieder

Learning

TensorFlow

A GUIDE TO BUILDING DEEP LEARNING SYSTEMS

www.allitebooks.com

www.allitebooks.com

978-1-491-97851-

[LSI]

Learning TensorFlow by Tom Hope, Yehezkel S. Resheff, and Itay Lieder

Copyright © 2017 Tom Hope, Itay Lieder, and Yehezkel S. Resheff. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com/safari). For more information, contact our corporate/insti‐ tutional sales department: 800-998-9938 or [email protected].

Editor: Nicole Tache Production Editor: Shiny Kalapurakkel Copyeditor: Rachel Head Proofreader: Sharon Wilkey

Indexer: Judith McConville Interior Designer: David Futato Cover Designer: Karen Montgomery Illustrator: Rebecca Demarest

August 2017: First Edition

Revision History for the First Edition 2017-08-04: First Release 2017-09-15: Second Release

The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Learning TensorFlow, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc.

While the publisher and the authors have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the authors disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights.

www.allitebooks.com

Table of Contents

iii

Table of Contents | v

vi | Table of Contents

    1. Introduction. Preface. vii
    • Going Deep
      • Using TensorFlow for AI Systems
    • TensorFlow: What’s in a Name?
    • A High-Level Overview
    • Summary
    1. Go with the Flow: Up and Running with TensorFlow.
    • Installing TensorFlow
    • Hello World
    • MNIST
    • Softmax Regression
    • Summary
    1. Understanding TensorFlow Basics.
    • Computation Graphs
      • What Is a Computation Graph?
      • The Benefits of Graph Computations
    • Graphs, Sessions, and Fetches
      • Creating a Graph
      • Creating a Session and Running It
      • Constructing and Managing Our Graph
      • Fetches
    • Flowing Tensors
      • Nodes Are Operations, Edges Are Tensor Objects
      • Data Types
      • Tensor Arrays and Shapes
      • Names
    • Variables, Placeholders, and Simple Optimization
      • Variables
      • Placeholders
      • Optimization
    • Summary
    1. Convolutional Neural Networks.
    • Introduction to CNNs
    • MNIST: Take II
      • Convolution
      • Pooling
      • Dropout
      • The Model
    • CIFAR10
      • Loading the CIFAR10 Dataset
      • Simple CIFAR10 Models
    • Summary
    1. Text I: Working with Text and Sequences, and TensorBoard Visualization.
    • The Importance of Sequence Data
    • Introduction to Recurrent Neural Networks
      • Vanilla RNN Implementation
      • TensorFlow Built-in RNN Functions
    • RNN for Text Sequences
      • Text Sequences
      • Supervised Word Embeddings
      • LSTM and Using Sequence Length
      • Training Embeddings and the LSTM Classifier
    • Summary
    1. Text II: Word Vectors, Advanced RNN, and Embedding Visualization.
    • Introduction to Word Embeddings
    • Word2vec
      • Skip-Grams
      • Embeddings in TensorFlow
      • The Noise-Contrastive Estimation (NCE) Loss Function
      • Learning Rate Decay
      • Training and Visualizing with TensorBoard
      • Checking Out Our Embeddings
    • Pretrained Embeddings, Advanced RNN
      • Pretrained Word Embeddings
      • Bidirectional RNN and GRU Cells
    • Summary
    1. TensorFlow Abstractions and Simplifications.
    • Chapter Overview
      • High-Level Survey
    • contrib.learn
      • Linear Regression
      • DNN Classifier
      • FeatureColumn
      • Homemade CNN with contrib.learn
    • TFLearn
      • Installation
      • CNN
      • RNN
      • Keras
      • Pretrained models with TF-Slim
    • Summary
    1. Queues, Threads, and Reading Data.
    • The Input Pipeline
    • TFRecords
      • Writing with TFRecordWriter
    • Queues
      • Enqueuing and Dequeuing
      • Multithreading
      • Coordinator and QueueRunner
    • A Full Multithreaded Input Pipeline
      • tf.train.string_input_producer() and tf.TFRecordReader()
      • tf.train.shuffle_batch()
      • tf.train.start_queue_runners() and Wrapping Up
    • Summary
    1. Distributed TensorFlow.
    • Distributed Computing
      • Where Does the Parallelization Take Place?
      • What Is the Goal of Parallelization?
    • TensorFlow Elements
      • tf.app.flags
      • Clusters and Servers
      • Replicating a Computational Graph Across Devices
        • Managed Sessions
        • Device Placement
      • Distributed Example
      • Summary
    1. Exporting and Serving Models with TensorFlow.
      • Saving and Exporting Our Model
        • Assigning Loaded Weights
        • The Saver Class
      • Introduction to TensorFlow Serving
        • Overview
        • Installation
        • Building and Exporting
      • Summary
    • A. Tips on Model Construction and Using TensorFlow Serving.
    • Index.

Prerequisites

This book assumes some basic Python programming know-how, including basic familiarity with the scientific library NumPy.

Machine learning concepts are touched upon and intuitively explained throughout the book. For readers who want to gain a deeper understanding, a reasonable level of knowledge in machine learning, linear algebra, calculus, probability, and statistics is recommended.

Conventions Used in This Book

The following typographical conventions are used in this book:

Italic Indicates new terms, URLs, email addresses, filenames, and file extensions.

Constant width Used for program listings, as well as within paragraphs to refer to program ele‐ ments such as variable or function names, databases, data types, environment variables, statements, and keywords.

Constant width bold Shows commands or other text that should be typed literally by the user.

Constant width italic Shows text that should be replaced with user-supplied values or by values deter‐ mined by context.

Using Code Examples

Supplemental material (code examples, exercises, etc.) is available for download at https://github.com/Hezi-Resheff/Oreilly-Learning-TensorFlow.

This book is here to help you get your job done. In general, if example code is offered with this book, you may use it in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a signifi‐ cant amount of example code from this book into your product’s documentation does require permission.

We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN. For example: “Learning TensorFlow by Tom Hope,

viii | Preface

www.allitebooks.com

Yehezkel S. Resheff, and Itay Lieder (O’Reilly). Copyright 2017 Tom Hope, Itay Lieder, and Yehezkel S. Resheff, 978-1-491-97851-1.”

If you feel your use of code examples falls outside fair use or the permission given above, feel free to contact us at [email protected].

O’Reilly Safari

Safari (formerly Safari Books Online) is a membership-based training and reference platform for enterprise, government, educators, and individuals.

Members have access to thousands of books, training videos, Learning Paths, interac‐ tive tutorials, and curated playlists from over 250 publishers, including O’Reilly Media, Harvard Business Review, Prentice Hall Professional, Addison-Wesley Profes‐ sional, Microsoft Press, Sams, Que, Peachpit Press, Adobe, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, and Course Technology, among others.

For more information, please visit http://oreilly.com/safari.

How to Contact Us

Please address comments and questions concerning this book to the publisher:

O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax)

We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://bit.ly/learning-tensorflow.

To comment or ask technical questions about this book, send email to bookques‐ [email protected].

For more information about our books, courses, conferences, and news, see our web‐ site at http://www.oreilly.com.

Find us on Facebook: http://facebook.com/oreilly

Follow us on Twitter: http://twitter.com/oreillymedia

Preface | ix

CHAPTER 1

Introduction

This chapter provides a high-level overview of TensorFlow and its primary use: implementing and deploying deep learning systems. We begin with a very brief intro‐ ductory look at deep learning. We then present TensorFlow, showcasing some of its exciting uses for building machine intelligence, and then lay out its key features and properties.

Going Deep

From large corporations to budding startups, engineers and data scientists are col‐ lecting huge amounts of data and using machine learning algorithms to answer com‐ plex questions and build intelligent systems. Wherever one looks in this landscape, the class of algorithms associated with deep learning have recently seen great success, often leaving traditional methods in the dust. Deep learning is used today to under‐ stand the content of images, natural language, and speech, in systems ranging from mobile apps to autonomous vehicles. Developments in this field are taking place at breakneck speed, with deep learning being extended to other domains and types of data, like complex chemical and genetic structures for drug discovery and high- dimensional medical records in public healthcare.

Deep learning methods—which also go by the name of deep neural networks—were originally roughly inspired by the human brain’s vast network of interconnected neu‐ rons. In deep learning, we feed millions of data instances into a network of neurons, teaching them to recognize patterns from raw inputs. The deep neural networks take raw inputs (such as pixel values in an image) and transform them into useful repre‐ sentations, extracting higher-level features (such as shapes and edges in images) that capture complex concepts by combining smaller and smaller pieces of information to solve challenging tasks such as image classification (Figure 1-1). The networks auto‐ matically learn to build abstract representations by adapting and correcting them‐

1

selves, fitting patterns observed in the data. The ability to automatically construct data representations is a key advantage of deep neural nets over conventional machine learning, which typically requires domain expertise and manual feature engineering before any “learning” can occur.

Figure 1-1. An illustration of image classification with deep neural networks. The net‐ work takes raw inputs (pixel values in an image) and learns to transform them into use‐ ful representations, in order to obtain an accurate image classification.

This book is about Google’s framework for deep learning, TensorFlow. Deep learning algorithms have been used for several years across many products and areas at Goo‐ gle, such as search, translation, advertising, computer vision, and speech recognition. TensorFlow is, in fact, a second-generation system for implementing and deploying deep neural networks at Google, succeeding the DistBelief project that started in

TensorFlow was released to the public as an open source framework with an Apache 2.0 license in November 2015 and has already taken the industry by storm, with adoption going far beyond internal Google projects. Its scalability and flexibility, combined with the formidable force of Google engineers who continue to maintain and develop it, have made TensorFlow the leading system for doing deep learning.

Using TensorFlow for AI Systems

Before going into more depth about what TensorFlow is and its key features, we will briefly give some exciting examples of how TensorFlow is used in some cutting-edge real-world applications, at Google and beyond.

2 | Chapter 1: Introduction

Figure 1-3. Going from images to text with image captioning (illustrative example).

Text summarization

Natural language understanding (NLU) is a key capability for building AI systems. Tremendous amounts of text are generated every day: web content, social media, news, emails, internal corporate correspondences, and many more. One of the most sought-after abilities is to summarize text, taking long documents and generating succinct and coherent sentences that extract the key information from the original texts (Figure 1-4). As we will see later in this book, TensorFlow comes with powerful features for training deep NLU networks, which can also be used for automatic text summarization.

4 | Chapter 1: Introduction

Figure 1-4. An illustration of smart text summarization.

TensorFlow: What’s in a Name?

Deep neural networks, as the term and the illustrations we’ve shown imply, are all about networks of neurons, with each neuron learning to do its own operation as part of a larger picture. Data such as images enters this network as input, and flows through the network as it adapts itself at training time or predicts outputs in a deployed system.

Tensors are the standard way of representing data in deep learning. Simply put, ten‐ sors are just multidimensional arrays, an extension of two-dimensional tables (matri‐ ces) to data with higher dimensionality. Just as a black-and-white (grayscale) images are represented as “tables” of pixel values, RGB images are represented as tensors (three-dimensional arrays), with each pixel having three values corresponding to red, green, and blue components.

In TensorFlow, computation is approached as a dataflow graph (Figure 1-5). Broadly speaking, in this graph, nodes represent operations (such as addition or multiplica‐ tion), and edges represent data (tensors) flowing around the system. In the next chap‐ ters, we will dive deeper into these concepts and learn to understand them with many examples.

TensorFlow: What’s in a Name? | 5

a feedback process called backpropagation based on gradient descent optimization. TensorFlow flexibly supports many optimization algorithms, all with automatic dif‐ ferentiation—the user does not need to specify any gradients in advance, since Ten‐ sorFlow derives them automatically based on the computation graph and loss function provided by the user. To monitor, debug, and visualize the training process, and to streamline experiments, TensorFlow comes with TensorBoard (Figure 1-6), a simple visualization tool that runs in the browser, which we will use throughout this book.

Figure 1-6. TensorFlow’s visualization tool, TensorBoard, for monitoring, debugging, and analyzing the training process and experiments.

Key enablers of TensorFlow’s flexibility for data scientists and researchers are high- level abstraction libraries. In state-of-the-art deep neural nets for computer vision or NLU, writing TensorFlow code can take a toll—it can become a complex, lengthy, and cumbersome endeavor. Abstraction libraries such as Keras and TF-Slim offer simpli‐ fied high-level access to the “LEGO bricks” in the lower-level library, helping to streamline the construction of the dataflow graphs, training them, and running infer‐ ence. Another key enabler for data scientists and engineers is the pretrained models that come with TF-Slim and TensorFlow. These models were trained on massive amounts of data with great computational resources, which are often hard to come by and in any case require much effort to acquire and set up. Using Keras or TF-Slim, for example, with just a few lines of code it is possible to use these advanced models for inference on incoming data, and also to fine-tune the models to adapt to new data.

The flexibility and portability of TensorFlow help make the flow from research to production smooth, cutting the time and effort it takes for data scientists to push their models to deployment in products and for engineers to translate algorithmic ideas into robust code.

A High-Level Overview | 7

TensorFlow abstractions TensorFlow comes with abstraction libraries such as Keras and TF- Slim, offering simplified high-level access to TensorFlow. These abstractions, which we will see later in this book, help streamline the construction of the dataflow graphs and enable us to train them and run inference with many fewer lines of code.

But beyond flexibility and portability, TensorFlow has a suite of properties and tools that make it attractive for engineers who build real-world AI systems. It has natural support for distributed training—indeed, it is used at Google and other large industry players to train massive networks on huge amounts of data, over clusters of many machines. In local implementations, training on multiple hardware devices requires few changes to code used for single devices. Code also remains relatively unchanged when going from local to distributed, which makes using TensorFlow in the cloud, on Amazon Web Services (AWS) or Google Cloud, particularly attractive. Additionally, as we will see further along in this book, TensorFlow comes with many more features aimed at boosting scalability. These include support for asynchronous computation with threading and queues, efficient I/O and data formats, and much more.

Deep learning continues to rapidly evolve, and so does TensorFlow, with frequent new and exciting additions, bringing better usability, performance, and value.

Summary

With the set of tools and features described in this chapter, it becomes clear why Ten‐ sorFlow has attracted so much attention in little more than a year. This book aims at first rapidly getting you acquainted with the basics and ready to work, and then we will dive deeper into the world of TensorFlow with exciting and practical examples.

8 | Chapter 1: Introduction