...

/

TF Ops (Part 2)

TF Ops (Part 2)

Know about common TF ops performed on tensors, and learn about linear algebra operations supported by the TF framework.

Common TF ops

Here, we discuss some important TF ops applied to tensors. These include the following:

  • tf.transpose(): This is for taking the transpose of a tensor.

  • tf.matmul(): This is for matrix (tensor) multiplication.

  • tf.reshape(): This is to change the shape of the tensor.

  • tf.reduce_mean(): This is for reducing a tensor using its mean (equivalent to np.mean() in NumPy).

  • tf.reduce_sum(): This is for reducing a tensor using its sum (equivalent to np.sum() in NumPy).

  • tf.reduce_max(): This is for reducing a tensor using its maximum value (equivalent to np.max() in NumPy).

  • tf.squeeze(): This is to remove dimensions of size 1 from a tensor.

  • tf.slice(): This is to extract a slice of the specified size from an input tensor.

  • tf.tile(): This is for tiling a tensor a number of times along each axis as specified by some multiple.

Press + to interact
import tensorflow as tf
# Matrix multiplication
my_mat1 = tf.constant([[2.0, 1.0],
[4.0, 3.0]])
my_mat2 = tf.constant([[[[2.0, 1.0],
[4.0, 3.0]]]])
my_mat3 = tf.constant([[[2.0, 1.0, 0.0], [4.0, 3.0, 5.0]],
[[6.0, 7.0, -5.0], [9.0, 8.0, 10.0]]])
my_mat1_transpose = tf.transpose(my_mat1)
mat1_mul_result = tf.matmul(my_mat1_transpose, my_mat1)
print('\nMatrix 1:\n', my_mat1,
'\n\nTransposed matrix 1:\n', my_mat1_transpose,
'\n\nTransposed matrix 1 * Original matrix 1: \n', mat1_mul_result,
'\n\nReduced mean result:\n', tf.reduce_mean(mat1_mul_result),
'\n\nReduced sum result:\n', tf.reduce_sum(mat1_mul_result),
'\n\nReduced max result:\n', tf.reduce_max(mat1_mul_result),
'\n\nMatrix 2:\n', my_mat2,
'\n\nSqueezing dimensions of matrix 2:\n', tf.squeeze(my_mat2),
'\n\nTiling matrix 1:\n', tf.tile(my_mat1, [3, 2]),
'\n\nSlicing a tensor:\n', tf.slice(my_mat3, [1, 0, 0], [1, 2, 3]))
  • Line 22: This constructs a tensor by copying an input tensor the number of times in the specified dimensions: ...