对TensorFlow的assign赋值用法详解

TensorFlow修改变量值后,需要重新赋值,assign用起来有点小技巧,就是需要需要弄个操作子,运行一下。

下面这么用是不行的

import tensorflow as tf
import numpy as np
 
x = tf.Variable(0)
init = tf.initialize_all_variables()
sess = tf.InteractiveSession()
sess.run(init)
 
print(x.eval())
 
x.assign(1)
print(x.eval())

正确用法

1.

import tensorflow as tf
x = tf.Variable(0)
y = tf.assign(x, 1)
with tf.Session() as sess:
 sess.run(tf.global_variables_initializer())
 print sess.run(x)
 print sess.run(y)
 print sess.run(x)

2.

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)
 
In [214]: with tf.Session() as sess:
  ...:  sess.run(w_new)
  ...:  print(w_new.eval())
 
# output
34

3.

import tensorflow as tf
x = tf.Variable(0)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(x)) # Prints 0.
x.load(1, sess)
print(sess.run(x)) # Prints 1.

我的方法

import numpy as np #这是Python的一种开源的数值计算扩展,非常强大
import tensorflow as tf #导入tensorflow 

##构造数据##
x_data=np.random.rand(100).astype(np.float32) #随机生成100个类型为float32的值
y_data=x_data*0.1+0.3 #定义方程式y=x_data*A+B
##-------##

##建立TensorFlow神经计算结构##
weight=tf.Variable(tf.random_uniform([1],-1.0,1.0)) 
biases=tf.Variable(tf.zeros([1]))  
y=weight*x_data+biases

w1=weight*2

loss=tf.reduce_mean(tf.square(y-y_data)) #判断与正确值的差距
optimizer=tf.train.GradientDescentOptimizer(0.5) #根据差距进行反向传播修正参数
train=optimizer.minimize(loss) #建立训练器

init=tf.global_variables_initializer() #初始化TensorFlow训练结构
#sess=tf.Session() #建立TensorFlow训练会话
sess = tf.InteractiveSession() 
sess.run(init)  #将训练结构装载到会话中
print('weight',weight.eval())
for step in range(400): #循环训练400次
  sess.run(train) #使用训练器根据训练结构进行训练
  if step%20==0: #每20次打印一次训练结果
  print(step,sess.run(weight),sess.run(biases)) #训练次数,A值,B值
  
print(sess.run(loss))  
print('weight new',weight.eval())


#wop=weight.assign([3])
#wop.eval()
weight.load([1],sess)
print('w1',w1.eval())

相关推荐