code1
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
state = tf.Variable(0.0,dtype=tf.float32)
one = tf.constant(3.0,dtype=tf.float32)
print('----------type(state) type(one)--------------------------')
print(type(state),type(one))
print('-----------state one-----------')
print(state,one)
new_val = tf.add(state,one) # tf.add函数返回值是Tensor类型
print('---------type(new_val)----------------')
print(type(new_val))
update = tf.assign(state,new_val) # 返回tensor,值为new_val( A `Tensor` that will hold the new value of 'new_val'
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for _ in range(3):
print(sess.run(update))
输出:
----------type(state) type(one)-------------------------- <class 'tensorflow.python.ops.variables.RefVariable'> <class 'tensorflow.python.framework.ops.Tensor'> -----------state one----------- <tf.Variable 'Variable:0' shape=() dtype=float32_ref> Tensor("Const:0", shape=(), dtype=float32) ---------type(new_val)---------------- <class 'tensorflow.python.framework.ops.Tensor'> WARNING:tensorflow:From /usr/local/lib/python3.6/dist-packages/tensorflow/python/util/tf_should_use.py:247: initialize_all_variables (from tensorflow.python.ops.variables) is deprecated and will be removed after 2017-03-02. Instructions for updating: Use `tf.global_variables_initializer` instead. 3.0 6.0 9.0
code2
state = tf.Variable(0.0,dtype=tf.float32)
one = tf.constant(3.0,dtype=tf.float32)
print('----------type(state) type(one)--------------------------')
print(type(state),type(one))
print('-----------state one-----------')
print(state,one)
new_val = tf.add(state,one) # tf.add函数返回值是Tensor类型
print('---------type(new_val)----------------')
print(type(new_val))
update = tf.assign(state,10000) # 返回tensor,值为new_val( A `Tensor` that will hold the new value of 'new_val'
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for _ in range(3):
print(sess.run(update))
输出:
----------type(state) type(one)-------------------------- <class 'tensorflow.python.ops.variables.RefVariable'> <class 'tensorflow.python.framework.ops.Tensor'> -----------state one----------- <tf.Variable 'Variable_1:0' shape=() dtype=float32_ref> Tensor("Const_1:0", shape=(), dtype=float32) ---------type(new_val)---------------- <class 'tensorflow.python.framework.ops.Tensor'> 10000.0 10000.0 10000.0
code3
feed使用一个值临时替换一个op的输出结果。可以使用feed数据作为run()调用的参数。feed只在调用它的方法内有效,方法结束,feed就会消失。
y = tf.Variable(1)
b = tf.identity(y)
with tf.Session() as sess:
tf.global_variables_initializer().run()
# sess.run(tf.global_variables_initializer())
print(sess.run(b,feed_dict={y:3})) # 输出:3
print(sess.run(b)) # 输出:1
输出:
3 1