Detail usage of assign assignment for TensorFlow

  • 2020-11-30 08:26:15
  • OfStack

After TensorFlow changes the value of the variable, it needs to be re-assigned, and assign is a little tricky to use, but you need to get an operand, run 1.

You can't use it this way


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())

Proper use

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.

My method


import numpy as np # This is a Python the 1 A very powerful open source extension of numerical computing 
import tensorflow as tf # The import tensorflow 

## Structural data ##
x_data=np.random.rand(100).astype(np.float32) # Randomly generated 100 A type of float32 The value of the 
y_data=x_data*0.1+0.3 # Defining equation y=x_data*A+B
##-------##

## To establish TensorFlow Neural computational structure ##
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)) # The difference between the judgment and the correct value 
optimizer=tf.train.GradientDescentOptimizer(0.5) # The parameters are corrected by back propagation according to the gap 
train=optimizer.minimize(loss) # Set up a trainer 

init=tf.global_variables_initializer() # Initialize the TensorFlow Training structure 
#sess=tf.Session() # To establish TensorFlow The training session 
sess = tf.InteractiveSession() 
sess.run(init)  # Load the training structure into the session 
print('weight',weight.eval())
for step in range(400): # Circuit training 400 time 
  sess.run(train) # Use a trainer to train according to the training structure 
  if step%20==0: # every 20 Time to print 1 Secondary training results 
  print(step,sess.run(weight),sess.run(biases)) # Training times, A Value, B value 
  
print(sess.run(loss))  
print('weight new',weight.eval())


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

Related articles: