Table Of Contents

Creating Tensors with Variables

In [2]:
import tensorflow as tf
In [6]:
startingArr = [10,6]
varTensor = tf.Variable(startingArr)
constTensor = tf.constant(startingArr)
varTensor, constTensor
Out [6]:
(<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([10,  6], dtype=int32)>,
 <tf.Tensor: shape=(2,), dtype=int32, numpy=array([10,  6], dtype=int32)>)

Changing A Variable Tensor

In [7]:
varTensor[0].assign(123)
varTensor
Out [7]:
<tf.Variable 'Variable:0' shape=(2,) dtype=int32, numpy=array([123,   6], dtype=int32)>

Changing A Constant Tensor

In [9]:
constTensor[0].assign(123)
constTensor
# shows error
# object has no attribute 'assign'
---------------------------------------------------------------------------AttributeError Traceback (most recent call last)Cell In[9], line 1 ----> 1 constTensor[0].assign(123) 2 constTensor 3 # shows error 4 # object has no attribute 'assign' File /opt/conda/lib/python3.11/site-packages/tensorflow/python/framework/tensor.py:261, in Tensor.__getattr__(self, name) 253 if name in {"T", "astype", "ravel", "transpose", "reshape", "clip", "size", 254 "tolist", "data"}: 255 # TODO(wangpeng): Export the enable_numpy_behavior knob 256 raise AttributeError( 257 f"{type(self).__name__} object has no attribute '{name}'. " + """ 258 If you are looking for numpy-related methods, please run the following: 259 tf.experimental.numpy.experimental_enable_numpy_behavior() 260 """) --> 261 self.__getattribute__(name) AttributeError: 'tensorflow.python.framework.ops.EagerTensor' object has no attribute 'assign'