Tensorflow: How to modify the value in tensor
Use assign and eval (or sess.run) the assign:
import numpy as np
import tensorflow as tf
npc = np.array([[1.,2.],[3.,4.]])
tfc = tf.Variable(npc) # Use variable
row = np.array([[.1,.2]])
with tf.Session() as sess:
tf.initialize_all_variables().run() # need to initialize all variables
print('tfc:\n', tfc.eval())
print('npc:\n', npc)
for i in range(2):
for j in range(2):
npc[i,j] += row[0,j]
tfc.assign(npc).eval() # assign_sub/assign_add is also available.
print('modified tfc:\n', tfc.eval())
print('modified npc:\n', npc)
It outputs:
tfc:
[[ 1. 2.]
[ 3. 4.]]
npc:
[[ 1. 2.]
[ 3. 4.]]
modified tfc:
[[ 1.1 2.2]
[ 3.1 4.2]]
modified npc:
[[ 1.1 2.2]
[ 3.1 4.2]]