In [1]:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import tensorflow as tf
import numpy as np

In [2]:
'''
A linear regression example
'''

# generate phony data
x_data = np.float32(np.random.rand(2, 100))
y_data = np.dot([0.1, 0.2], x_data) + 0.3

# build graph
b = tf.Variable(tf.zeros(1))
W = tf.Variable(tf.random_uniform([1, 2], -1.0, 1.0))
y = tf.matmul(W, x_data) + b

# target
loss = tf.reduce_mean(tf.square(y - y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)

# initialize variables
init = tf.global_variables_initializer()

# startup graph
with tf.Session() as sess:
    sess.run(init)
    for step in range(1, 201):
        sess.run(train)
        if step % 20 == 0:
            print(step, sess.run(W), sess.run(b))


20 [[-0.01901932  0.08293114]] [ 0.43430245]
40 [[ 0.06485737  0.1670514 ]] [ 0.33870724]
60 [[ 0.08958521  0.19076458]] [ 0.31115481]
80 [[ 0.09690159  0.19742496]] [ 0.30321541]
100 [[ 0.09907433  0.19928673]] [ 0.30092713]
120 [[ 0.09972219  0.19980404]] [ 0.3002674]
140 [[ 0.09991623  0.19994672]] [ 0.30007717]
160 [[ 0.09997462  0.19998571]] [ 0.30002224]
180 [[ 0.09999227  0.19999625]] [ 0.30000642]
200 [[ 0.09999762  0.19999905]] [ 0.30000186]

In [3]:
'''
tensor operation example
'''

matrix1 = tf.constant([[3., 3.]], name = 'left')
matrix2 = tf.constant([[2.], [2.]], name = 'right')
product = tf.matmul(matrix1, matrix2)
with tf.Session() as sess:
    result = sess.run(product)
    print(result)
    
    # show the value
    print(matrix1.eval())
    print(matrix2.eval())
    
    # show the tensor
    print(matrix1)
    print(matrix2)


[[ 12.]]
[[ 3.  3.]]
[[ 2.]
 [ 2.]]
Tensor("left:0", shape=(1, 2), dtype=float32)
Tensor("right:0", shape=(2, 1), dtype=float32)

In [4]:
'''
variables and constants, gat more than one outputs
'''

state = tf.Variable(0, name = 'counter')
one = tf.constant(1)
new_value = tf.add(state, one)
update = tf.assign(state, new_value)

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
    print(state.eval())
    for _ in range(3):
        sess.run(update)
        print(state.eval())
        result = sess.run([state, one])
        
print('result : ', result)


0
1
2
3
result :  [3, 1]

In [5]:
'''
usage of placeholder
'''

input1 = tf.placeholder(tf.float32)
input2 = tf.placeholder(tf.float32)
output = tf.multiply(input1, input2)

with tf.Session() as sess:
    result = sess.run([output], feed_dict = {input1:[2.], input2:[3.]})
    print(result)


[array([ 6.], dtype=float32)]