tf.Variable
转自:TensorFlow图变量tf.Variable的用法解析
1.在TensorFlow的世界里,变量的定义和初始化是分开的,所有关于图变量的赋值和计算都要通过tf.Session的run来进行。想要将所有图变量进行集体初始化时应该使用tf.global_variables_initializer。
2.
tf.Variable
tf.Variable.init(initial_value, trainable=True, collections=None, validate_shape=True, name=None)
In [1]: import tensorflow as tf
In [2]: a = tf.Variable(3,name='a')
In [3]: a2 = a.assign(5)
In [4]: sess = tf.Session()
In [5]: sess.run(a.initializer) #必须先定义a的值,否则会报错
In [6]: sess.run(a)
Out[6]: 13
In [7]: sess.run(a2)
Out[7]: 24
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-30 14:57:27
# @Author : Lebhoryi@gmail.com
# @Link : https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/2-2-example2/
# @Version : Tensorflow 例子2
import tensorflow as tf
import numpy as np
#creat data
x_data = np.random.rand(100).astype(np.float32)
y_data = x_data*0.1 + 0.3
### creat tensorflow strucure start ###
Weights = tf.Variable(tf.random_uniform([1],-1.0,1.0))
biases = tf.Variable(tf.zeros([1]))
y = Weights*x_data + biases
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescentOptimizer(0.5)
train = optimizer.minimize(loss)
init = tf.initialize_all_variables()
### creat tensorflow strucure end ###
sess = tf.Session()
sess.run(init) #Important
for step in range(201):
sess.run(train)
if step % 10 == 0:
print(step,sess.run(Weights),sess.run(biases))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2017-11-30 19:51:50
# @Author : Lebhoryi@gmail.com
# @Link : https://morvanzhou.github.io/tutorials/machine-learning/tensorflow/2-4-variable/
# @Version : Variable 变量
import tensorflow as tf
state = tf.Variable(0,name='counter')
print(state.name)
one = tf.constant(1)
new_value = tf.add(state,one) #add
update = tf.assign(state,new_value) #赋值,new_value赋值state
init = tf.initialize_all_variables() #must have if define variable
with tf.Session() as sess:
sess.run(init)
for _ in range(3):
sess.run(update)
print(sess.run(state))