According to other StackOverFlow questions, you cannot change tf.constant, but when I do this it runs perfectly:
>>>c = tf.constant([2])
>>>c += 1
>>>print(c)
[3]
Why is that?
According to other StackOverFlow questions, you cannot change tf.constant, but when I do this it runs perfectly:
>>>c = tf.constant([2])
>>>c += 1
>>>print(c)
[3]
Why is that?
The original c is constant and remains unchanged. You loose reference to it by creating a new tensor with the same name c that equals to the old value of c plus 1.
It's still a constant in the sense that you cannot assign to it. Running c += 1 just change the object that c points to like c = c + 1.
c = tf.constant(2)
print(id(c)) # "Address" is 140481630446312 (for my run)
c += 1
print(id(c)) # "Address" is different
but this fails everytime: c.assign(2)
This is not a limitation of Tensorflow, but of Python itself. Since it's not compiled, we can't check for constants. The best you can do these days is use a type hint (Python 3.6+) to signify to IDEs and optional static typecheckers that you don't want a variable to be reassigned. See this answer for details.