4 Chapter 9 TensorFlow Programming Basics Experiment Guide
4 Chapter 9 TensorFlow Programming Basics Experiment Guide
4 Chapter 9 TensorFlow Programming Basics Experiment Guide
HCIA-AI
TensorFlow Programming Basics
Experiment Guide
Version: 1.0
and other Huawei trademarks are trademarks of Huawei Technologies Co., Ltd.
All other trademarks and trade names mentioned in this document are the property of their respective holders.
Notice
The purchased products, services and features are stipulated by the contract made between Huawei and the customer.
All or part of the products, services and features described in this document may not be within the purchase scope or
the usage scope. Unless otherwise specified in the contract, all statements, information, and recommendations in this
document are provided "AS IS" without warranties, guarantees or representations of any kind, either express or
implied.
The information in this document is subject to change without notice. Every effort has been made in the preparation
of this document to ensure accuracy of the contents, but all statements, information, and recommendations in this
document do not constitute a warranty of any kind, express or implied.
Email: [email protected]
Preface
Brief Introduction
This document is an HCIA-AI certification training course, intended to trainees who are
preparing for HCIA-AI tests or readers who want to know about AI basics and TensorFlow
basic programming.
Content Description
This experiment guide includes nine experiments, introducing basic equipment operation and
configuration, TensorFlow's helloworld, sessions, matrix multiplication, TensorFlow
virtualization, and housing price prediction.
Experiment 1: "Hello, TensorFlow".
Experiment 2: Understand functions of sessions through a session experiment using the
with session function.
Experiment 3: Understand matrix multiplication by multiplying two matrices with ranks
of tensors greater than 2.
Experiment 4: Understand the definition of variables. Define variables with Variable and
get_variable respectively and observe the difference between these two methods.
Experiment 5: Understand the visualization of TensorBoard. TensorBoard aggregates all
kinds of data into a log file. You can enable TensorBoard service to read the log file and
enable the 6060 port to provide web services so that users can view data via a browser.
Experiment 6: Understand data reading and processing by reading .csv files and
displaying them based on given conditions.
Experiment 7: Understand graphic operations. Create a graph in three ways and set it as
the default graph. Use the get_default_graph() function to access the default graph and
verify its settings.
Experiment 8: Understand save and use of models. After importing data, analyze data
characteristics and define variables based on the characteristics. Create a model and
define output nodes. Build the structure for forward propagation and then the structure
for backpropagation. Compile and train the model to get appropriate parameters. After
training data and testing the model, create a saver and a path to save parameters in the
session automatically. When the model is saved, you can access the model for use.
Experiment 9: A comprehensive experiment of forecasting housing price through the
instantiation of linear regression. Use the dataset of housing prices in Beijing and skills
in the prior eight experiments to forecast the housing price.
Experimental Environment
Networking
This experimental environment is compiled for AI engineers who are preparing for HCIA-AI
tests. Each set of experimental environment includes a remote elastic cloud server (ECS) with
two cores, 4-GB memory, and 64-bit CentOS 7.4.
Equipment
To meet the HCIA-AI experiment needs, adopt the following configuration for each set of
experimental environment:
The following table shows the device names and types and software versions.
Contents
Preface......................................................................................................................................... iii
1 Hello, TensorFlow! ................................................................................................................... 1
1.1 Introduction to the Experiment............................................................................................................................... 1
1.1.1 About the Experiment ......................................................................................................................................... 1
1.1.2 Objectives of the Experiment .............................................................................................................................. 1
1.1.3 Experiment Content ............................................................................................................................................ 1
1.1.4 Experimental Operations..................................................................................................................................... 1
1.2 Experimental Process ............................................................................................................................................ 2
1.2.1 Setting Encoding Declarations ............................................................................................................................ 2
1.2.2 Importing a Module ............................................................................................................................................ 2
1.2.3 Defining Variables .............................................................................................................................................. 2
1.2.4 Creating a Session .............................................................................................................................................. 2
1.2.5 Closing the Session ............................................................................................................................................. 2
1.2.6 Experimental Results .......................................................................................................................................... 3
1.3 Instance Description .............................................................................................................................................. 3
2 Session ....................................................................................................................................... 4
2.1 Introduction to the Experiment............................................................................................................................... 4
2.1.1 About the Experiment ......................................................................................................................................... 4
2.1.2 Objectives of the Experiment .............................................................................................................................. 4
2.1.3 Experiment Content ............................................................................................................................................ 4
2.1.4 Experimental Operations..................................................................................................................................... 4
2.2 Experimental Process ............................................................................................................................................ 5
2.2.1 Setting Encoding Declarations ............................................................................................................................ 5
2.2.2 Importing a Module ............................................................................................................................................ 5
2.2.3 Defining Constants ............................................................................................................................................. 5
2.2.4 Creating a Session .............................................................................................................................................. 5
2.2.5 Experimental Results .......................................................................................................................................... 6
2.3 Instance Description .............................................................................................................................................. 6
5 Visualization of TensorBoard............................................................................................... 13
5.1 Introduction to the Experiment..............................................................................................................................13
5.1.1 About the Experiment ........................................................................................................................................13
5.1.2 Objectives of the Experiment .............................................................................................................................13
5.1.3 Experiment Content ...........................................................................................................................................13
5.1.4 Experimental Operations....................................................................................................................................13
5.2 Experimental Process ...........................................................................................................................................14
5.2.1 Setting Encoding Declarations ...........................................................................................................................14
5.2.2 Importing a Module ...........................................................................................................................................14
5.2.3 Generating Analog Data .....................................................................................................................................14
5.2.4 Resetting the Computation Graph.......................................................................................................................14
5.2.5 Creating a Model ...............................................................................................................................................14
5.2.6 Creating a Forward Structure .............................................................................................................................15
5.2.7 Reverse Optimization ........................................................................................................................................15
5.2.8 Initializing Variables ..........................................................................................................................................15
1 Hello, TensorFlow!
Step 3 Select an ECS. Applicable operations of the ECS are displayed. Select Remote Login to log
in to the ECS.
Relational
database (0)
2 Session
Step 3 Select an ECS. Applicable operations of the ECS are displayed. Select Remote Login to log
in to the ECS.
3 Matrix Multiplication
w1 = tf.Variable(tf.random_normal([2,3],mean=1.0, stddev=1.0))
w2 = tf.Variable(tf.random_normal([3,1],mean=1.0, stddev=1.0))
4 Definition of Variables
with tf.variable_scope("test2"):
var6 = tf.get_variable("varname",shape=[2],dtype=tf.float32)
5 Visualization of TensorBoard
tf.reset_default_graph()
#Placeholders
X = tf.placeholder("float")
Y = tf.placeholder("float")
#Model parameters
W = tf.Variable(tf.random_normal([1]), name="weight")
b = tf.Variable(tf.zeros([1]), name="bias")
#Set parameters.
training_epochs = 20
display_step = 2
summary_writer = tf.summary.FileWriter('log/mnist_with_summaries',sess.graph)
#Generate a summary.
summary_str = sess.run(merged_summary_op,feed_dict={X: x, Y: y});
summary_writer.add_summary(summary_str, epoch);#Write summary to files.
plotdata["avgloss"] = moving_average(plotdata["loss"])
plt.figure(1)
plt.subplot(211)
plt.show()
#Run the coord.request_stop () command to terminate all threads. Run the coord.join
(threads) to add threads to the main thread. Wait for the termination of threads.
7 Graphic Operation
g = tf.Graph()
with g.as_default():
c1 = tf.constant(0.0)
print(c1.graph)
print(g)
print(c.graph)
g2 = tf.get_default_graph()
print(g2)
tf.reset_default_graph()
g3 = tf.get_default_graph()
print(g3)
print(tensor1.name,tensor1)
test = g3.get_tensor_by_name("exampleop:0")
print(test)
print(tensor1.op.name)
testop = g3.get_operation_by_name("exampleop")
print(testop)
exampleop
name: "exampleop"
op: "MatMul"
input: "Const"
input: "Const_1"
attr {
key: "T"
value {
type: DT_FLOAT
}
}
attr {
key: "transpose_a"
value {
b: false
}
}
attr {
key: "transpose_b"
value {
b: false
}
}
2018-05-11 15:43:16.483655: I
T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140] Your CPU
suppo
rts instructions that this TensorFlow binary was not compiled to use: AVX2
[[7.]]
Tensor("exampleop:0", shape=(1, 1), dtype=float32)
[<tf.Operation 'Const' type=Const>]
Tensor("Const:0", shape=(), dtype=float32)
________________________
import tensorflow as tf
import os
#Define parameters.
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
init = tf.global_variables_initializer()
#Define a session.
sess = tf.Session()
print("Training finished!")
import tensorflow as tf
#Define parameters.
W = tf.Variable(tf.zeros([784, 10]))
b = tf.Variable(tf.zeros([10]))
9 Linear Regression:
Housing Price Forecast
print("Optimization Finished!")
training_cost = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')