Note : The rank of a tensor is not the same as the rank of a matrix. The rank of a tensor is the number of indices required to uniquely select each element of the tensor. Rank is also known as “order”, “degree”, or “ndims.”
1 2 3 4
x = tf.ones((1,3,2)) print(x) rank = tf.rank(x).numpy() print(rank)
Most tensor operations work on variables as expected, although variables cannot be reshaped
tf.convert_to_tensor
tf.argmax
tf.reshape
1 2 3 4 5 6 7
print("variable:", my_variable) print("\nViewed as a tensor:", tf.convert_to_tensor(my_variable)) print("variable:", my_variable) print("\nIndex of highest value:", tf.argmax(my_variable))
# This creates a new tensor; it does not reshape the variable. print("\nCopying and reshaping: ", tf.reshape(my_variable, ([1,4])))
can reassign the tensor using tf.Variable.assign Calling assign does not (usually) allocate a new tensor; instead, the existing tensor’s memory is reused.
1 2 3 4
new_value = tf.ones(shape=(2, 2)) print(my_variable) my_variable.assign(new_value) print('value of my_variable after assign new value:', my_variable)
<tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 2.],
[3., 4.]], dtype=float32)>
value of my_variable after assign new value: <tf.Variable 'Variable:0' shape=(2, 2) dtype=float32, numpy=
array([[1., 1.],
[1., 1.]], dtype=float32)>
a = tf.ones(shape=(2, 2)) b = tf.ones(shape=(2, 2)) print('a:', a.numpy().flatten()) print('b:', b.numpy().flatten()) c = a + b print('c:', c.numpy().flatten()) d = tf.square(c) print('square:', d.numpy().flatten()) e = tf.exp(d) print('exp :', e.numpy().flatten())