How to update the value of a variable in TensorFlow?
In order to update, increment and decrements the value of a variable, we use Variable.assign(), Variable.assign_add() and Variable.assign_sub() methods respectively.
## # TensorFlow program with example of variable assignment. from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf # Create a variable variableA = tf.Variable(10, name="variableA") # Start a session sess = tf.Session() # Initialization operation init = tf.global_variables_initializer() # Initialize variable sess.run(init) # Print session variable print(sess.run(variableA)) # Assign new value to variable sess.run(variableA.assign(20)) print(sess.run(variableA)) # Increment by 20 sess.run(variableA.assign_add(20)) print(sess.run(variableA)) # Decrement by 5 sess.run(variableA.assign_sub(5)) print(sess.run(variableA))
Sample output of above program.
C:\tf\examples\chapter6>pycodestyle --first example2.py
C:\tf\examples\chapter6>python example2.py
10
20
40
35
C:\tf\examples\chapter6>
C:\tf\examples\chapter6>python example2.py
10
20
40
35
C:\tf\examples\chapter6>
2018-08-05T12:37:09+05:30
2018-08-05T12:37:09+05:30
Amit Arora
Amit Arora
Python Programming Tutorial
Python
Practical Solution