Open the session of Tensorflow

bash-3.2$ source activate tensorflow

(tensorflow) bash-3.2$ jupyter notebook


In [1]:
import tensorflow as tf
print(tf.__version__)
import numpy as np
# to make this notebook's output stable across runs
np.random.seed(42)


1.0.1

Regression


In [2]:
x = tf.placeholder(dtype=tf.float64, name='x')
y = tf.placeholder(dtype=tf.float64, name='y')

In [3]:
w = tf.Variable(0., dtype=tf.float64, name='w')
b = tf.Variable(0., dtype=tf.float64, name='b')
tf.summary.scalar('w', w);
tf.summary.scalar('b', b);

In [4]:
with tf.name_scope('y1'):
    y1 = w*x + b

In [5]:
with tf.name_scope('loss'):
    loss = tf.reduce_mean(tf.square(y - y1))
    tf.summary.scalar('loss',loss)

In [6]:
optimizer = tf.train.GradientDescentOptimizer(0.5)
step = tf.Variable(0, name='step', trainable=False)
train = optimizer.minimize(loss, global_step=step)
initialize = tf.global_variables_initializer()

In [12]:
from datetime import datetime

now = datetime.utcnow().strftime("%Y%m%d")
root_logdir = "tf_logs"
logdir = "{}/run-{}/".format(root_logdir, now)

summary = [tf.summary.merge_all(), step]

writer = tf.summary.FileWriter(logdir)

In [13]:
logdir


Out[13]:
'tf_logs/run-20170719/'

tensorboard

$ source activate tensorflow

$ tensorboard --logdir tf_logs/run-20170719/


In [8]:
x_dat = np.random.rand(100)
y_dat = 3.*x_dat + 2. + 0.1*np.random.rand(100)
feed_dict = {x:x_dat, y:y_dat}

In [9]:
sess = tf.Session()
writer.add_graph(sess.graph)
sess.run(initialize)

In [10]:
for step in range(201):
    sess.run(train, feed_dict)
    if step%20 == 0:
        print(step, sess.run([w,b,loss], feed_dict))
        writer.add_summary(*sess.run(summary, feed_dict))


(0, [1.889529433232479, 3.4603254024501302, 0.89753071806440343])
(20, [2.6628478968447271, 2.2202597683132699, 0.010754677149330635])
(40, [2.919753691269722, 2.090267175989891, 0.0013751768481822097])
(60, [2.9789339103742267, 2.0603223858660966, 0.00087745690870083104])
(80, [2.9925665275018178, 2.053424373913777, 0.00085104557225393785])
(100, [2.9957069053604952, 2.0518353639825793, 0.00084964406382002336])
(120, [2.9964303154733867, 2.0514693233640795, 0.00084956969325970712])
(140, [2.9965969585383254, 2.0513850031016561, 0.00084956574681164295])
(160, [2.9966353460457666, 2.0513655792828347, 0.00084956553739474279])
(180, [2.9966441889023718, 2.0513611048572726, 0.00084956552628210561])
(200, [2.9966462259221776, 2.0513600741390445, 0.00084956552569241889])

In [ ]: