Tensorflow学习教程------变量

  代码

#coding:utf-8
import tensorflow as tf

x = tf.Variable([1,2])
a = tf.constant([3,3])
#增加一个减法op
sub = tf.subtract(x,a)
#增加一个加法op
add = tf.add(x,sub)
#有变量 一定要初始化 初始化所有的变量
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print(sess.run(sub))
    print(sess.run(add))

#自加操作
#创建一个变量初始化为0
state = tf.Variable(0,name='counter')
#创建一个op 作用是使state加1
new_value = tf.add(state,1)
#赋值操作  将new_value赋值给state
update = tf.assign(state,new_value)
init = tf.global_variables_initializer()
with tf.Session() as sess:
    sess.run(init)
    print (sess.run(state))
    for _ in range(5):
        sess.run(update)
        print (sess.run(state))

  结果

name: GeForce GTX 1080 Ti
major: 6 minor: 1 memoryClockRate (GHz) 1.582
pciBusID 0000:03:00.0
Total memory: 10.91GiB
Free memory: 10.18GiB
I tensorflow/core/common_runtime/gpu/gpu_device.cc:906] DMA: 0 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:916] 0:   Y 
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0)
[-2 -1]
[-1  1]
I tensorflow/core/common_runtime/gpu/gpu_device.cc:975] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX 1080 Ti, pci bus id: 0000:03:00.0)
0
1
2
3
4
5

 

posted @ 2017-10-07 13:02  qilibin  阅读(278)  评论(0编辑  收藏  举报