Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow,assign value to variable

Tags:

tensorflow

I am total newbie to tensorflow, I am learning from

https://www.tensorflow.org/get_started/get_started

fixW = tf.assign(W, [-1.])

works fine,but

fixb = tf.assign(b, [1.])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/milenko/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/state_ops.py", line 272, in assign
    return ref.assign(value)
AttributeError: 'Tensor' object has no attribute 'assign'

One other example

zero_tsr = tf.zeros([1.,2.])
zero_tsr
<tf.Tensor 'zeros:0' shape=(1, 2) dtype=float32>

If I try to change zero_tsr

fixz = tf.assign(zero_tsr, [2.,2.])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/milenko/anaconda3/lib/python3.6/site-packages/tensorflow/python/ops/state_ops.py", line 272, in assign
    return ref.assign(value)
AttributeError: 'Tensor' object has no attribute 'assign'

Again,the same problem.

I have not changed shell,everything is the same.Why do I have problem here?

like image 390
MishaVacic Avatar asked Jun 26 '17 08:06

MishaVacic


People also ask

How do you declare a TensorFlow variable?

In TensorFlow variables are created using the Variable() constructor. The Variable() constructor expects an initial value for the variable, which can be any kind or shape of Tensor. The type and form of the variable are defined by its initial value. The shape and the variables are fixed once they are created.

How do you get the value of a tf variable?

To get the current value of a variable x in TensorFlow 2, you can simply print it with print(x) . This prints a representation of the tf. Variable object that also shows you its current value.

What is tf Global_variables_initializer ()?

Variable() function in order to create a Variable and define what value it will be initialized with. We then have to explicitly perform an initialization operation by running the session with the tf. global_variables_initializer() method, which allocates the memory for the Variable and sets its initial values.


1 Answers

In the example you posted:

zero_tsr = tf.zeros([1.,2.])
zero_tsr
<tf.Tensor 'zeros:0' shape=(1, 2) dtype=float32>

zero_tsr is a constant and not a variable, so you cannot assign a value to it.

From the documentation:

assign( ref, value, validate_shape=None, use_locking=None, name=None )

ref: A mutable Tensor. Should be from a Variable node. May be uninitialized.

For example, this will work fine:

import tensorflow as tf
zero_tsr = tf.Variable([0,0])
tf.assign(zero_tsr,[4,5])

while this code will raise an error

import tensorflow as tf
zero_tsr = tf.zeros([1,2])
tf.assign(zero_tsr,[4,5])

The error that is raised is exactly the error you posted:

AttributeError: 'Tensor' object has no attribute 'assign'

like image 105
Miriam Farber Avatar answered Nov 03 '22 01:11

Miriam Farber