CS256
Chris Pollett
Oct 23, 2017
Which of the following is true?
pip install tensorflow
import tensorflow as tfat the start of your program.
... TensorFlow library wasn't compiled to use SSE4.2 instructions, but these are available on your machine and could speed up CPU computations. ...
import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2'to the start of your code.
node1 = tf.constant(5.0, dtype=tf.float32) node2 = tf.constant(4.0) #defaults to float32 node3 = tf.multiply(node1, node2) # could also have done node1*node2 # similarly tf.add(node1mnode2) equiv to node1 + node2 node4 = tf.placeholder(tf.float32) node5 = tf.Variable([.4], dtype=tf.float32) # .4 is the initial value of the Variable # which might change with training node6 = node4 * node5 + node3 # this implicitly create a node for node4 * node 5 # that doesn't have a name
session = tf.Session() session.run(node3) #outputs 20 session.run(node4, {node4: 5}) # fills in 5 into placeholder #array(5.0, dtype=float32)
init = tf.global_variables_initializer() session.run(init) #now it is okay to call session.run(node6, {node4: 5}) # outputs array([ 22.], dtype=float32) as .4*5 + 4.0*5. = 22.0
update = tf.assign(node5, [3.]) session.run([update]) session.run(node6, {node4: 5}) #outputs array([ 35.], dtype=float32) as 3.* 5. + 4.*5. =35.
session.run(node6, {node4: [1,2,3,4,5]}) #outputs array([ 23., 26., 29., 32., 35.], dtype=float32)
node7 = tf.reduce_sum(node6) session.run(node7, {node4: [1,2,3,4,5]}) #outputs 145.0
epsilon = 0.01 # the learning rate optimizer = tf.train.GradientDescentOptimizer(epsilon)
train = optimizer.minimize(loss)
import tensorflow as tf # Model parameters W = tf.Variable([.3], dtype=tf.float32) b = tf.Variable([-.3], dtype=tf.float32) # Model input and output x = tf.placeholder(tf.float32) linear_model = W * x + b y = tf.placeholder(tf.float32) # loss loss = tf.reduce_sum(tf.square(linear_model - y)) # sum of the squares # optimizer optimizer = tf.train.GradientDescentOptimizer(0.01) train = optimizer.minimize(loss) # training data x_train = [1, 2, 3, 4] y_train = [0, -1, -2, -3] # training loop init = tf.global_variables_initializer() sess = tf.Session() sess.run(init) # reset values to wrong for i in range(1000): sess.run(train, {x: x_train, y: y_train}) # evaluate training accuracy curr_W, curr_b, curr_loss = sess.run([W, b, loss], {x: x_train, y: y_train}) print("W: %s b: %s loss: %s"%(curr_W, curr_b, curr_loss))