7

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?

MishaVacic
  • 1,812
  • 8
  • 25
  • 29

1 Answers1

9

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'

Miriam Farber
  • 18,986
  • 14
  • 61
  • 76
  • Im confused - that is not his error, nor does it have anything to do with the error OP posted, does it? (I am talking about `AttributeError: 'Tensor' object has no attribute 'assign'`) – Xatenev Jun 26 '17 at 08:34
  • @Xatenev This is the OP's error, see the example I added. – Miriam Farber Jun 26 '17 at 08:40
  • 1
    Wow that is really weird - can you elaborate (for me) on how/why that error is thrown? Error seems to imply the problem is somewhere else. – Xatenev Jun 26 '17 at 08:44
  • 2
    @Xatenev I think it is related to the discussion in the comments in the answer here: https://stackoverflow.com/questions/37566925/preserving-tensor-values-between-session-runs. (tf.Variable has the attribute assign, while constant does not). Also, as listed in tf.assign documentation, ref should be from a Variable node. constant is not from such a node. – Miriam Farber Jun 26 '17 at 08:55
  • True - now it all makes sense. Thanks :) +1 – Xatenev Jun 26 '17 at 09:14
  • 1
    How would I go about assigning ones to a subset of a tf.zeros tensor if I cannot use assign? – Perm. Questiin Dec 24 '17 at 22:51