tensorflow-变量

#计数器

import tensorflow as tf

state = tf.Variable(0,name='counter') #设定变量
print(state.name) #打印变量
one = tf.constant(1) 
new_value = tf.add(state,one)   
update = tf.assign(state,new_value)

x = np.random.rand(3,2) #测试非tensor变量

t =  tf.convert_to_tensor(x, dtype=tf.float32) #tf.convert_to_tensor(...)这个方法,我们可以用在任何地方,以确保我们处理张量而不是其他类型

init = tf.initialize_all_variables() #重要,初始化变量
#sess = tf.Session()
#sess.run(init)
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))

 

备注:

如果执行过程中遇到<class ‘tensorflow.python.framework.ops.Tensor’>,是类型不对导致,因为TensorFlow中所有运算符(如neg)都设计为对张量对象进行操作
posted @ 2018-04-13 17:19  明夫人  阅读(147)  评论(0编辑  收藏  举报