我爱编程

tensorflow变量

2018-03-06  本文已影响0人  东岳哥哥

tensorflow变量

#重点:
#初始化全局的变量
init = tf.global_variables_initializer()
import tensorflow as tf
x = tf.Variable([1,2])
a = tf.constant([3,3])
#减法op
sub = tf.subtract(x,a)

#加法
add = tf.add(x,sub)

#使用变量一定要进行初始化操作
#初始化全局的变量
init = tf.global_variables_initializer()

with tf.Session() as ss:
    
    ss.run(init)
    print(x)
    print(a)
    print(ss.run(sub))
    print(ss.run(add))
    
#结果:
<tf.Variable 'Variable_3:0' shape=(2,) dtype=int32_ref>
Tensor("Const_3:0", shape=(2,), dtype=int32)
[-2 -1]
[-1  1]
state = tf.Variable(0,name='counter')
value = tf.add(state,1)
#赋值操作,把value的值赋值给state
#tensorflow没有直接用等于号赋值的操作
update = tf.assign(state,value)
init = tf.global_variables_initializer()

with tf.Session() as ss:
    ss.run(init)
    print(ss.run(state))
    for _ in range(5):
        ss.run(update)
        print('state = ' + str(ss.run(state)))
#结果:
0
state = 1
state = 2
state = 3
state = 4
state = 5
上一篇 下一篇

猜你喜欢

热点阅读