TensorFlow Getting Started Tutorial


In [1]:
import tensorflow as tf

In [2]:
sess = tf.InteractiveSession()

In [3]:
x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])

In [4]:
# Initialize 'x' using the run() method of its initializer op.
x.initializer.run()

In [5]:
# Add an op to subtract 'a' from 'x'.  Run it and print the result
sub = tf.sub(x, a)
print(sub.eval())


[-2. -1.]

In [ ]:


In [6]:
import numpy as np

In [7]:
# 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

In [8]:
# 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

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

In [10]:
# Before starting, initialize the variables. We will 'run' this first. 
init = tf.initialize_all_variables()

In [11]:
# Launch the graph.
sess = tf.Session()
sess.run(init)

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


(0, array([ 0.56993598], dtype=float32), array([ 0.07380156], dtype=float32))
(20, array([ 0.25244093], dtype=float32), array([ 0.22169706], dtype=float32))
(40, array([ 0.15010804], dtype=float32), array([ 0.27426147], dtype=float32))
(60, array([ 0.11647075], dtype=float32), array([ 0.29153964], dtype=float32))
(80, array([ 0.10541401], dtype=float32), array([ 0.29721904], dtype=float32))
(100, array([ 0.1017796], dtype=float32), array([ 0.29908589], dtype=float32))
(120, array([ 0.10058497], dtype=float32), array([ 0.29969954], dtype=float32))
(140, array([ 0.10019229], dtype=float32), array([ 0.29990125], dtype=float32))
(160, array([ 0.10006322], dtype=float32), array([ 0.29996753], dtype=float32))
(180, array([ 0.1000208], dtype=float32), array([ 0.29998934], dtype=float32))
(200, array([ 0.10000685], dtype=float32), array([ 0.2999965], dtype=float32))

In [ ]: