常量constant:constant_name = tf.constant(value)
import tensorflow as tf
node1 = tf.constant(3.0,tf.float32,name='node1')
node2 = tf.constant(4.0,tf.float32,name='node2')
node3 = tf.add(node1,node2)
print(node3) # Tensor("Add:0", shape=(), dtype=float32)
sess=tf.Session()
print(sess.run(node3)) # 7.0
sess.close()
变量Variable,需要初始化:
name_Variable = tf.Variable(value, name)
init_op = tf.global_variables_initializer()
import tensorflow as tf
node1 = tf.Variable(3.0,tf.float32,name='node1')
node2 = tf.Variable(4.0,tf.float32,name='node2')
node3 = tf.add(node1,node2, name='add')
print(node3) # Tensor("Add:0", shape=(), dtype=float32)
sess=tf.Session()
init = tf.global_variables_initializer()
sess.run(init) # 所有变量初始化
print(sess.run(node3)) # 7.0
sess.close()
禁止更新:epoch = tf.Variable(0, name = 'epoch', trainable = False)
变量赋值:update_op = tf.assign(variable_to_be_updated, new_value)
e.g. 依次输出 1 2 3 4 5 6 7 8 9 10
import tensorflow as tf
value = tf.Variable(0, name='value')
one = tf.constant(1)
new_value = tf.add(value, one)
update_value = tf.assign(value, new_value)
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(10):
sess.run(update_value)
print(sess.run(value),end=' ') # 1 2 3 4 5 6 7 8 9 10
e.g. 计算1+2+3+...+10
import tensorflow as tf
value = tf.Variable(0, name='value')
sum_value = tf.Variable(0, name='sum_value')
one = tf.constant(1)
new_value = tf.add(value, one)
update_value = tf.assign(value, new_value)
newsum_value = tf.add(sum_value, value)
update_sum_value = tf.assign(sum_value, newsum_value)
init=tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
for _ in range(10):
sess.run(update_value)
sess.run(update_sum_value)
print(sess.run(sum_value)) # 55
占位符:tf.placeholder(dtype, shape = None, name = None)
多个操作可以通过一次feed_dict完成,一次可以返回多个值分别赋给多个变量。placeholder不需要初始化。
import tensorflow as tf
a = tf.placeholder(tf.float32, name='a')
b = tf.placeholder(tf.float32, name='b')
c = tf.multiply(a, b, name='c')
d = tf.subtract(a, b, name='d')
with tf.Session() as sess:
result1 = sess.run(c, feed_dict={a:8, b:4.0})
print(result1) # 32.0
result2 = sess.run([c,d],feed_dict={a:[8.0, 2.0], b:[2., 1.5]})
print(result2) # [array([16., 3.], dtype=float32), array([6. , 0.5], dtype=float32)]
print(result2[0]) # [16. 3.]
rc,rd = sess.run([c,d],feed_dict={a:[8.0, 2.0], b:[2., 1.5]})
print('value of c=',rc,'value of d=',rd) # value of c= [16. 3.] value of d= [6. 0.5]
以上。参考Mooc课程是吴明晖老师的《深度学习应用开发-TensorFlow实践》。