In one of our previous articles, we already discussed what the Hadamard product in linear algebra is. We discussed that if A and B are two matrices of size mxn, then the Hadamard product of A and B is another mxn matrix C such that:
where Ai,j and Bi,j are the elements in the ith row and jth column of the matrices A and B, respectively.
So, we can say that, if A and B are two mxn matrices, we can say:
Similarly, we can calculate the Hadamard product of two tensors A and B. The tensor Hadamard product of A and B will be another tensor C of the same size such that each element of C will be the element-wise product of the corresponding elements of the tensors A and B.
We can use the following Python code to calculate the Hadamard product of two tensors A and B.
import numpy m = 3 n = 3 p = 3 A = numpy.random.randint(low=1, high=10, size=(m, n, p)) B = numpy.random.randint(low=1, high=10, size=(m, n, p)) H = numpy.multiply(A, B) print("A: \n", A) print("B: \n", B) print("The Hadamard product of A and B: \n", H)
Here, A and B are two tensors that contain random integers within the range [low, high). And the tensors have m, n, and p elements across each axis. The size argument of the numpy.random.randint() function specifies the size of the tensors.
After that, we are using the numpy.multiply() function to calculate the Hadamard product of two tensors. The output of the given program will be:
A: [[[3 7 7] [3 2 7] [1 3 6]] [[7 5 5] [6 8 8] [1 1 4]] [[6 6 2] [7 6 1] [2 7 9]]] B: [[[2 6 3] [1 2 6] [1 8 2]] [[3 6 7] [6 1 1] [6 8 5]] [[8 8 2] [8 6 5] [9 4 6]]] The Hadamard product of A and B: [[[ 6 42 21] [ 3 4 42] [ 1 24 12]] [[21 30 35] [36 8 8] [ 6 8 20]] [[48 48 4] [56 36 5] [18 28 54]]]
0 Comments