In [2]:
"""
    tf_xy_fit.py - Yevheniy Chuba - 11/11/2016
    Create random data in 2D and fit a line to it using TensorFlow
    
    Following turorial @:
        https://www.tensorflow.org/versions/r0.11/get_started/index.html
"""

import tensorflow as tf
import numpy as np

# Create 100 random 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
# W and b are known, but we will TensorFlow figure it out
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()

# 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))


0 [ 0.68023217] [-0.04991785]
20 [ 0.30141884] [ 0.1858454]
40 [ 0.1688471] [ 0.26098076]
60 [ 0.12353268] [ 0.28666282]
80 [ 0.10804374] [ 0.29544121]
100 [ 0.10274943] [ 0.29844177]
120 [ 0.10093977] [ 0.29946738]
140 [ 0.10032123] [ 0.29981795]
160 [ 0.10010981] [ 0.29993778]
180 [ 0.10003754] [ 0.29997873]
200 [ 0.10001285] [ 0.29999274]

In [13]:
# create two constant ops using matrixes and one multiplication op
matrix1 = tf.constant([[3., 3.]])   # 1X2 matrix
matrix2 = tf.constant([[2.], [2.]]) # 2x1 matrix
# Create a Matmul (matrix multiplier) op that takes both matrixes as inputs
product = tf.matmul(matrix1, matrix2)
print ("1. graph w/ 3 nodes: ", product) # a graph with 3 nodes (ops)

# To actually multiply the matrices and get the result of multiplication,
# you mush launch the graph session


1. graph w/ 3 nodes:  Tensor("MatMul_5:0", shape=(1, 1), dtype=float32)

In [ ]: