The problem of multiplying matrices and arrays in python

The problem of multiplying matrices and arrays such as np.dot (array, matrix) and np.dot (matrix, array)

1. np.dot (array, matrix)

import numpy as np
A = np.array([6,7,8])
B = np.array([[1,2], [3, 4], [5,6]])
print(A.shape)
print(B.shape)
print(np.dot(A,B).shape)
print(np.dot(A,B))

The result is:
insert image description here
Summary: A is an array of 3 elements (note that it is not a matrix!), and the number of elements is 3
B is a 3x2 matrix. np.dot(A,B) obtains an array with 2 elements.

2. np.dot (matrix, array):

import numpy as np
A = np.array([[1, 2], [3, 4], [5, 6]])
B = np.array([7, 8])
print(A.shape, B.shape)
print(np.dot(A, B).shape)
print(np.dot(A, B))

The result is:
insert image description here
Summary: A is a 3x2 matrix, B is an array of 2 elements, and np.dot(A,B) obtains an array with 3 elements.

in conclusion:

  • In python, when matrices and arrays are calculated using np.dot(), the result is an array ;
  • When the array is in front, the array can be regarded as a matrix of 1 row and n columns, and the calculation result can be obtained by multiplying the matrix. However, it should be noted that the calculation result is still only an array, and its shape is in the form of (k,) instead of (1, k);
  • When the array is in the back, multiply the rows of the matrix with the array respectively, and the vector formed by the result is the result . That is, 1x7+2x8=23, 3x7+4x8=53, 5x7+6x8=83, forming an array [23,53,83].
  • [23,53,83] is an array whose shape is (3,)
  • [ [23,53,83] ] is a matrix whose shape is (1,3)
  • Only [[23],[53],[83]] is a column vector

In python, the multiplication of arrays and matrices is very different from the idea that we regard vectors as a column vector in linear algebra. The storage of arrays in python is stored by row (in C language, matlab is also by row storage). According to Mr. Wu Enda's suggestion, he generally does not use arrays when building neural networks, but converts arrays into matrices through the reshape() function to reduce the possibility of errors .

Guess you like

Origin blog.csdn.net/qq_45652492/article/details/124035317