Learning numpy while writing code

1. numpy.matmul() usage

matmul() is used to calculate the matrix product of two arrays. The example is as follows

def matmul_test():
    array1 = np.array([
        [[1.0, 3], [1, 1], [2, 3]]
    ])
    array2 = np.array([[2, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0],
                       [1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0], ])
    result = np.matmul(array1, array2)
    print(result)

if __name__ == '__main__':
    matmul_test()

The resulting output:

    [[[5. 4. 1. 3. 3. 0. 0. 4. 4. 0. 1. 0.]
      [3. 2. 1. 1. 1. 0. 0. 2. 2. 0. 1. 0.]
      [7. 5. 2. 3. 3. 0. 0. 5. 5. 0. 2. 0.]]]

2. numpy.multiple() usage

Let’s talk about the simpler multiply first. If two matrices with exactly the same dimensions are multiplied by multiply, then they only perform multiplication between elements at corresponding positions to obtain a matrix output of the same dimension. This is the so-called element-wise product.

def multiple_test():
    array1 = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], ndmin=3)
    array2 = np.array([[9, 8, 7], [6, 5, 4], [3, 2, 1]], ndmin=3)
    result = np.multiply(array1, array2)
    print(result)
if __name__ == '__main__':
    multiple_test()

result output

     [[[ 9 16 21]
      [24 25 24]
      [21 16  9]]]

3. numpy.dot() usage

Multiplication of matrices in linear algebra is called the dot product operation (Dot Product), also known as the inner product. First of all, based on the knowledge of linear algebra, one thing that needs special attention is:
matrix X1 and matrix X2 perform dot product operations, where the dimensions corresponding to X1 and X2 (in layman's terms, the number of columns of the first matrix, and the number of columns of the second matrix The number of rows must be equal), the number of elements must be consistent, the calculation process is shown in the figure below

insert image description here

 The dot product operation in numpy is represented by np.dot, and its general format is:
numpy.dot(a, b, out = None)

X1 = np.array([[1,2], [3,4]])
X2 = np.array([[5, 6, 7], [8, 9, 10]])
result = dot(X1, X2)
print(result)

"""
  计算结果为 :[[21,24,27]
               [47,54,61]]
"""

Guess you like

Origin blog.csdn.net/keeppractice/article/details/132137341