本系列使用的是tensorflow0.12和极客学院的中文教程有出入


import tensorflow as tf
state=tf.Variable(0,name="counter")#使用tensorflow在默认的图中创建节点,这个节点是一个变量
one=tf.constant(1)
new_value=tf.add(state,one)#对常量与变量进行简单的加法操作
update=tf.assign(state, new_value)#赋值操作。将new_value的值赋值给state变量,返回值=new_value赋给updata
init_op=tf.global_variables_initializer()#之前只是定义好了图,并没有变量并没有初始化
with tf.Session()  as sess:
    print(sess.run(init_op))
    print("new_value",sess.run(new_value))#0+1
    print("state",sess.run(state))#初始化的0
    print("------")
    for _ in range(3):
        print("update",sess.run(update))#赋值更新操作。将new_value的值赋值给update,state变量。
        print("new_value",sess.run(new_value))#state+one
        print("state",sess.run(state))
        print("------")

输出:
None new_value 1 state 0 ------ update 1 new_value 2 state 1 ------ update 2 new_value 3 state 2 ------ update 3 new_value 4 state 3 ------ 
 
输出多个值
import tensorflow as tf
input1 = tf.constant(3.0)
input2 = tf.constant(2.0)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session() as sess:
  result = sess.run([mul, intermed])
  print(result)

[21.0, 7.0]
 
使用placeholder作为占位符
import tensorflow as tf
input1 = tf.constant(3.0)
input2 = tf.placeholder(tf.float32)
input3 = tf.constant(5.0)
intermed = tf.add(input2, input3)
mul = tf.mul(input1, intermed)

with tf.Session() as sess:
  result = sess.run([mul], feed_dict={input2:[7.]})
  print(result)

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