PhABC
PhABC

Reputation: 1593

Tensorflow : Assign variable by name

I would like to assign/modify the values of my variables and I wish to do so by calling them by their name.

For exemple:

vars = tf.trainable_variables()
print(vars[1].name)

'matrix1:0'

upt = vars['matrix1:0'].assign_add(tf.constant(1))
sess.run(upt)

The reason for this is that indexes for variables aren't reliable as they are dependant as to when they are ran in the code. By adding a new variable, all the indexes would need to be shifted, which is not convenient. Using names would make my life much easier.

Upvotes: 0

Views: 954

Answers (1)

Yaroslav Bulatov
Yaroslav Bulatov

Reputation: 57913

You can use Python generator expression to construct a dictionary like this

vars={v.name:v for v in tf.trainable_variables()}

and then you modify the variable as

vars['matrix1:0'].assign_add(tf.constant(1))

Upvotes: 3

Related Questions