Dzone Rc251 Gettingstartedwithtensorflow
Dzone Rc251 Gettingstartedwithtensorflow
CONTENTS
GETTING STARTED WITH
TensorFlow
Introduction to TensorFlow
Three Layers of TensorFlow Architecture
Quick Python Example
Use Cases
BY TIMOTHY SPANN Setup and Installation...and more!
INTRODUCTION TO TENSORFLOW programs are usually structured into a construction phase, which
assembles a data graph, and an execution phase, which uses a
TensorFlow is a deep learning library from Google that is open-
session to execute operations in the graph.
source and available on GitHub. TensorFlow excels at numerical
computing, which is critical for deep learning. It has a rich set of Questioning whether TensorFlow is ready for production
application programming interfaces in most major languages and environments belies the fact that TensorFlow has been in the
environments needed for deep learning projects: Python, C, C++, open-source community for almost two years and has been
Rust, Haskell, Go, Java, Android, IoS, Mac OS, Windows, Linux, and used by many companies. TensorFlow excels in production
Raspberry Pi. The primary unit in TensorFlow is a tensor. A tensor environments due to its distributed and parallel design and its
consists of a set of primitive values shaped into an array of any ability to access data from Hadoop HDFS. Another key feature of
number of dimensions. These massive numbers of large arrays are TensorFlow is TensorFlow Serving, which is a high-performance
the reason that GPUs and other processors designed to do floating production server for deploy and serve machine learning models
point mathematics excel at speeding up these algorithms. using gRPC as its network protocol.
Neural networks have been around for a long time, but now they
The APIs are well-documented and well-designed, so it was easy,
can be run in a reasonable amount of time due to more powerful
for example, for me to port the LabelImage Java example to work
computers, GPUs, and elastic cloud computing. Google has made
as a processor for Apache NiFi. Some people prefer a higher-level
neural networks mainstream through the public availability of
interface for neural network programming, such as Keras. Keras is
TensorFlow on all major clouds and platforms to be used by
available for Python and works not only for TensorFlow but also
researchers, data scientists, data engineers, cloud developers,
for CNTK and Theano. I recommend using Python 3.7 and starting
mobile developers, and web application users.
with plain TensorFlow before you investigate Keras. TensorFlow
An example implementation of a neural network would be to environment, but I like with keep it simple to Python 3.6 and
define an architecture, load data to the model, break up data into pip3. For some environments, you may need to be root or
batches to preprocess, convert it, and use it for training. As the have sudo access.
model gets trained in increments, the model is saved for reuse.
apt-get install python3-pip python3-dev
Future runs test the model on new data to check performance.
pip3 install tensorflow
After that, you continue to train over many iterations and as much pip3 install grpcio==1.4.0
training data as you can obtain. This is helped by fast networks,
fast CPUs, fast GPUs, large RAM, large hard drives, and generally
For GPU
fast computers.
pip3 install tensorflow-gpu
USE CASES
• Speech recognition: Recognize what people are saying and Sometimes, that doesn’t work. Look at GitHub or try:
convert it to text.
sudo pip3 install --upgrade latesturlforyourarchitecture
• Image recognition: Describe, in text, what an image is. from github.
with this, you must know Python and some basics on running • tf.Variable
shell programs in your environment. Creates a variable from a tensor.
<dependency> • tf.to_int32
<groupId>org.tensorflow</groupId> Converts tensor primitives to int32.
<artifactId>tensorflow</artifactId>
<version>1.3.0</version> • tf.multiply
</dependency>
Multiplies two tensors of the same type together, for numbers.
In the Java version, you start with a graph, import a graph • tf.div
definition, create a session, and return a tensor. I highly Divides numerator by denominator of real numeric types and
recommend looking at the Java and Android examples provided return quotient.
in the TensorFlow GitHub repository.
• tf.abs
The absolute value of the tensor.
EXAMPLE RUN
• tf.negative
import tensorflow as tf Returns negative value of numeric tensor.
firstnumber = tf.constant([10, 20, 30, 35, 40, 50])
secondnumber = tf.Variable(firstnumber + 50)
• tf.maximum
Returns the maximum of two tensors for a subset of numeric types.
with tf.Session() as session:
session.run(tf.global_variables_initializer()) • tf.minimum
print(session.run(secondnumber))
Returns the minimum of two tensor for a subset of numeric types.
python3 testtf2.py
2017-10-02 14:40:33.009719: W tensorflow/core/platform/ • tf.string_to_number
cpu_feature_guard.cc:45] The TensorFlow library wasn’t Converts a string tensor to a specified numeric type; specify
compiled to use SSE4.2 instructions, but these are out_type=tf.DType, where DType is a subset of numeric types.
available on your machine and could speed up CPU
computations.
2017-10-02 14:40:33.009742: W tensorflow/core/platform/
• tf.concat
cpu_feature_guard.cc:45] The TensorFlow library wasn’t Concatenates a tensor, along one specified dimension.
compiled to use AVX instructions, but these are available
on your machine and could speed up CPU computations. • tf.fill
2017-10-02 14:40:33.009747: W tensorflow/core/platform/
Creates a tensor filled with a specified scalar value.
cpu_feature_guard.cc:45] The TensorFlow library
wasn’t compiled to use AVX2 instructions, but these
are available on your machine and could speed up CPU • tf.tuple
computations. Groups tensors together.
2017-10-02 14:40:33.009751: W tensorflow/core/platform/
cpu_feature_guard.cc:45] The TensorFlow library wasn’t • tf.zeros
compiled to use FMA instructions, but these are available
on your machine and could speed up CPU computations.
Creates a tensor populated with zeros of a certain numeric
[ 60 70 80 85 90 100] type shape.
• tf. convert_to_tensor
COMMON TENSORFLOW OPERATIONS Converts the value to a tensor of specified type.
• tf.rank • tf.while_loop
Returns the rank of a tensor.
The while loop.
• tf.constant
• tf.case
Creates a constant from a value, type, and shape. The case operations on bools.
• tf.count_up_to • tf.image.resize_images
Increments a mutable tensor of int32 or int64 to an int limit. Resizes images to sizes using one of four predefined methods.
• tf.Print • tf.image.rot90
Prints out a debug message of tensors and messages. Rotates an image counter-clockwise 90 degrees.
• tf.is_nan • tf.image.transpose_image
Returns elements of tensors that are not a number. Transposes an image by swapping first two dimensions.
• tf.is_finite • tf.image.adjust_brightness
Returns elements of tensors that are finite, for half, float32, Adjusts image brightness.
and float64. • tf.image.adjust_contrast
Adjusts contrast of images.
• tf.logical_and
Returns truth value of each boolean element of two tensors. • tf.image.adjust_hue
Adjusts hue of images.
• tf.logical_not
Returns truth value of not each boolean element of a tensor. • tf.image.adjust_gamma
Runs gamma correction on input image.
• tf.logical_or
Returns truth value of each boolean element of two tensors. • tf.image.adjust_saturation
Adjusts saturation channel in image.
• tf.logical_xor
Returns truth value of each of boolean elements, exclusive or. • tf.image.flip_left_right
Flips an image horizontally.
• tf.equal
Returns truth value of first tensor == second tensor, element- • tf.image.flip_up_down
wise, on two tensors. Flips an image vertically.
• tf.not_equal • tf.image.draw_bounding_boxes
Returns truth value of first tensor != second tensor, element- Draws bounding boxes on a batch of images.
wise, on two tensors. • tf.nn
A large collection of neural network ops.
• tf.greater_equal
Returns truth value of first tensor >= second tensor, element- • tf.contrib
wise, on two tensors. Contributed libraries around keras, audio, video, TFLearn, and more.
• tf.greater • tf.Session()
Returns truth value of first tensor > second tensor, element- An instance of a session that is the environment to execute
wise, on two tensors. operations in a graph to compute tensors.
• tf.less_equal
TRAINING
Returns truth value of first tensor <= second tensor, element-
wise, on two tensors. As we mentioned in an earlier section, you should not try your own
training unless your problem space is small enough or you have
• tf.less sufficient hardware to run your training. Training examples like
Returns truth value of first tensor < second tensor, element- CIFAR-10 will also require downloading anywhere from hundreds
wise, on two tensors. of megabytes of data to terabytes of training data, especially
when dealing with images and videos. You will be working on
• tf.where
datasets of thousands of items and thousands of steps. These
Returns elements from either of two tensors based on condition.
numbers can increase astronomically depending on your problem
• tf.image.decode_jpeg set and data. A cool dataset to check out is SVHN, which contains
Decodes a JPEG image to a uint8 tensor. real-world street house numbers.
too much noise in it in order for recognition to have a high USING TENSORBOARD FOR VISUALIZATION AND DEBUGGING
matching percentage. You will need to clone the TensorBoard GitHub repo. Then, you
can run TensorBoard pointing to a recent log. We have generated
For image recognition with the Inception v3 application, I one from the example given in this Refcard.
recommend you download the pre-trained model here.
bazel run tensorboard -- -- logdir /opt/demo/tflogs
The example has a pre-trained 80-megabyte model from the
TensorFlow models repo, which lets you quickly classify images
against that model. This will run on a smartphone, a Raspberry Pi, The summary data is logged and sent to the board for
or your laptop easily in a few seconds. visualization. It is a great tool for learning what is going on and
learning how to improve your results as you are training and
EXAMPLE tweaking your algorithms.
A B O U T T H E AU T H O R
TIMOTHY SPANN is a Big Data Solutions Engineer. He helps educate and disseminate performant
open source solutions for Big Data initiatives to customers and the community. With over 15 years of
experience in various technical leadership, architecture, sales engineering, and development roles, he
is well-experienced in all facets of Big Data, cloud, IoT, and microservices. As part of his community
efforts, he also runs the Future of Data Meetup in Princeton.
DZone communities deliver over 6 million pages each month to more than 3.3 million
software developers, architects and decision makers. DZone offers something for
everyone, including news, tutorials, cheat sheets, research guides, feature articles, DZONE, INC. REFCARDZ FEEDBACK
150 PRESTON EXECUTIVE DR. WELCOME
source code and more. "DZone is a developer's dream," says PC Magazine.
[email protected]
CARY, NC 27513
Copyright © 2017 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval SPONSORSHIP
system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior 888.678.0399 OPPORTUNITIES
written permission of the publisher. 919.678.0300 [email protected]