Class05 Answer:

Run a Simple TensorFlow Demo

This is an easy lab.

I found a simple demo by loading this URL:

https://www.tensorflow.org

On the above page I found a link: "GET STARTED"

It sent me to the URL listed below:

https://www.tensorflow.org/get_started

There I found a simple page of syntax:


"""
tensorflow_test.py


I found a simple demo by loading this URL:

https://www.tensorflow.org

On the above page I found a link: "GET STARTED"

It sent me to the URL listed below:

https://www.tensorflow.org/get_started

There I found a simple page of syntax.
Now, you are looking at it.

Demo:
~/anaconda3/bin/python tensorflow_test.py
"""

import tensorflow as tf
import numpy as np

# Create 100 phony x, y data points in NumPy, y = x * 0.1 + 0.3
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data * 0.1 + 0.3

# Try to find values for W and b that compute y_data = W * x_data + b
# (We know that W should be 0.1 and b 0.3, but TensorFlow will
# figure that out for us.)
W = tf.Variable(tf.random_uniform([1], -1.0, 1.0))
b = tf.Variable(tf.zeros([1]))
y = W * x_data + b

# Minimize the mean squared errors.
loss      = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train     = optimizer.minimize(loss)

# Before starting, initialize the variables.  We will 'run' this first.
#init = tf.initialize_all_variables()
init  = tf.global_variables_initializer() # better than above line.

# Launch the graph.
sess = tf.Session()
sess.run(init)

# Fit the line.
for step in range(201):
    sess.run(train)
    if step % 20 == 0:
        print(step, sess.run(W), sess.run(b))

# Learns best fit is W: [0.1], b: [0.3]

I pasted that syntax into a file and ran it on my laptop.

I saw this:


ml4@ub100:~/ml4/public/class05tf $ ~/anaconda3/bin/python tensorflow_test.py
0 [-0.1276308] [ 0.60317343]
20 [ 0.00370979] [ 0.35302234]
40 [ 0.06937664] [ 0.31686279]
60 [ 0.09026082] [ 0.30536291]
80 [ 0.09690265] [ 0.30170557]
100 [ 0.09901495] [ 0.30054244]
120 [ 0.09968671] [ 0.30017254]
140 [ 0.09990038] [ 0.30005488]
160 [ 0.09996833] [ 0.30001745]
180 [ 0.09998993] [ 0.30000556]
200 [ 0.09999678] [ 0.30000177]
ml4@ub100:~/ml4/public/class05tf $ 
ml4@ub100:~/ml4/public/class05tf $ 
ml4@ub100:~/ml4/public/class05tf $ 

The idea of the above demo is to generate 100 random x_data values.

Then generate y_data from x_data using this expression:

y_data = x_data * 0.1 + 0.3

After that we have 100 points to create a scatter-plot.

We should then use TensorFlow to fit a line to that scatter-plot.

TensorFlow assumes the line has this form:

y = W*x + b

TensorFlow uses an error-minimization loop to calculate that W is 0.09999678 and b is 0.30000177.

According to the output, TensorFlow approaches near the correct answer after 60 iterations of the loop.

Class05 Lab


learn4.us About Blog Contact Class01 Class02 Class03 Class04 Class05 Class06 Class07 Class08 Class09 Class10 dan101 Forum Google Hangout Vboxen