We can use numpy nd-array to create a tensor in Python. We can use the following Python code to perform tensor addition and subtraction.
import numpy A = numpy.random.randint(low=1, high=10, size=(3, 3, 3)) B = numpy.random.randint(low=1, high=10, size=(3, 3, 3)) C = A + B D = A - B print("A: \n", A) print("B: \n", B) print("C = A + B: \n", C) print("D = A - B: \n", D)
Here, we are using randint() function from the numpy.random module to generate random integers within the range [low, high). And the shape of the created tensor is given by the size argument. For example, size = (3, 3, 3) indicates that the tensor has 3 elements across each dimension.
After that, we are adding the two tensors A and B to create the tensor C. And the tensor D contains the tensor (A – B). The output of the given program will be:
A: [[[7 5 5] [4 9 3] [2 4 8]] [[3 4 2] [8 6 4] [4 1 2]] [[1 9 4] [3 3 6] [3 3 6]]] B: [[[7 9 5] [5 8 4] [2 6 6]] [[6 6 6] [1 4 7] [6 2 5]] [[2 9 1] [9 8 9] [4 4 1]]] C = A + B: [[[14 14 10] [ 9 17 7] [ 4 10 14]] [[ 9 10 8] [ 9 10 11] [10 3 7]] [[ 3 18 5] [12 11 15] [ 7 7 7]]] D = A - B: [[[ 0 -4 0] [-1 1 -1] [ 0 -2 2]] [[-3 -2 -4] [ 7 2 -3] [-2 -1 -3]] [[-1 0 3] [-6 -5 -3] [-1 -1 5]]]
0 Comments