tensorflow采用C实现,variable就是C语言的变量,tensorflow规定变量必须初始化其实是减少变量的不确定性,在C语言里面,变量可以不初始化,但为初始化的变量的值不可预估
看代码:
a=tf.Variable([0,0,0]) //这其实就相当于C的变量的定义,int a[3];
b=tf.assign(a,[1,2,3]) //这其实就是变量的赋值,a[3]={1,2,3};
看完整代码:
import tensorflow as tf
a=tf.Variable([0,0,0])
op1=tf.assign(a,[1,2,3])
op2=tf.assign(a,[4,5,6])
with tf.Session() as sess:
print(op1)
print(op2)
print(sess.run(op1))
print(sess.run(op2))
输出为:
Tensor(“Assign:0”, shape=(3,), dtype=int32_ref)
Tensor(“Assign_1:0”, shape=(3,), dtype=int32_ref)
[1 2 3]
[4 5 6]
这里的assign()函数的作用是给tensorflow里面的C变量赋值,而run()函数作用于赋值操作时,就是执行操作,作用于variable对象时把tensorflow里面的C数据类型提取出来转换为numpy对象使用,就是return一个numpy对象,其实变量a在run()前和run后并没有发生变化,请看代码:
import tensorflow as tf
a=tf.Variable([0,0,0])
op1=tf.assign(a,[1,2,3])
op2=tf.assign(a,[4,5,6])
print(a)
with tf.Session() as sess:
print(op1)
print(op2)
print(sess.run(op1))
print(sess.run(op2))
print(a)
输出为:
<tf.Variable ‘Variable:0’ shape=(3,) dtype=int32_ref>
Tensor(“Assign:0”, shape=(3,), dtype=int32_ref)
Tensor(“Assign_1:0”, shape=(3,), dtype=int32_ref)
[1 2 3]
[4 5 6]
<tf.Variable ‘Variable:0’ shape=(3,) dtype=int32_ref>
变量a在run前和run后都是一个tensorflow的variable对象,并没有发生变化,run()作用于variable对象时就是return一个numpy对象,注意赋值操作也要run一下才会执行,其实我搞不懂为什么要这样设计???
注意,tensorflow的坑来了,请看下面代码:
import tensorflow as tf
a=tf.Variable([0,0,0])
op1=tf.assign(a,[1,2,3])
op2=tf.assign(a,[4,5,6])
with tf.Session() as sess:
print(op1)
print(op2)
print(sess.run(op1))
print(type(sess.run(op2)))
with tf.Session() as sess:
sess.run(a)
上面代码会报错:Attempting to use uninitialized value Variable,明明已经初始化了呀???
其实两个sess是不同的,我们第一个sess执行的赋值操作,而第二个没有,不同的sess使用同一variable时,都要先执行赋值操作才能使用,请看代码:
import tensorflow as tf
a=tf.Variable([0,0,0])
op1=tf.assign(a,[1,2,3])
op2=tf.assign(a,[4,5,6])
with tf.Session() as sess:
print(sess)
with tf.Session() as sess:
print(sess)
输出:
<tensorflow.python.client.session.Session object at 0x0000000009C7FE10>
<tensorflow.python.client.session.Session object at 0x0000000009C7FE48>
其实我不明白为什么要这样设计,完全可以把Session设计成单例模式的