4

I want to modify the value of a tensor when I am training my model with Tensorflow.

This tensor is one of the tensors in my model

weight = tf.Variable(np_matrix)

After some iterations, the value of weight will be updated automatically.

My question is: How can I modify the value of weight nonautomatically. I have tried this method but it didn't work.

modify_weight = sess.run([weight], feed_dict = feed_dict)
modify_weight[0] = [0, 0]
weight = tf.Variable(modify_weight)

This part code is in tf.Session() section(since I want to modify the value during the training time.)

Thank you!

Engineero
  • 12,340
  • 5
  • 53
  • 75
Tozz
  • 256
  • 1
  • 5
  • 19

1 Answers1

4

Like everything else, also the assignment is an operation, and we have to create a graph with the tf.assign and run it in a session.

So you you create an operation like this:

assign = tf.assign(weight, value)

where value is a numpy array with the same shape of weight (or a tf.Placeholder that you can modify with a feed dictionary) then you run this graph in the session:

sess.run(assign)

The tf.Variable also has a method assign, thus you can directly create the operation starting from the variable:

assign = weight.assign(value)

and than run it in a session.

Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34
  • Really thank you! I use `assign = weight.assign(value)` `sess.run(assign)` . But then if I don't use `new_weight = sess.run([weight], feed_dict = feed_dict)`, it still cannot modify the weight value. But now it works, thank you! – Tozz Aug 31 '17 at 17:51