Читать книгу Algorithms For Dummies - John Paul Mueller, John Mueller Paul, Luca Massaron - Страница 86
Multiplying matrixes
ОглавлениеMultiplying two matrixes involves the same concerns as multiplying two vectors (as discussed in the “Performing vector multiplication” section, earlier in this chapter). The following code produces an element-by-element multiplication of two matrixes:
a = np.array([[1,2,3],[4,5,6]])b = np.array([[1,2,3],[4,5,6]]) print(a*b)
The output looks like this:
[[ 1 4 9] [16 25 36]]
Note that a
and b
are the same shape: two rows and three columns. To perform an element-by-element multiplication, the two matrixes must be the same shape. Otherwise, you see an error message telling you that the shapes are wrong. As with vectors, the multiply()
function also produces an element-by-element result.
Dot products work completely differently with matrixes. In this case, the number of columns in matrix a
must match the number of rows in matrix b
. However, the number of rows in matrix a
can be any number, and the number of columns in matrix b
can be any number as long as you multiply a
by b
. For example, the following code produces a correct dot product:
a = np.array([[1,2,3],[4,5,6]])b = np.array([[1,2,3],[3,4,5],[5,6,7]]) print(a.dot(b))
with an output of:
[[22 28 34] [49 64 79]]
Note that the output contains the number of rows found in matrix a
and the number of columns found in matrix b
. So how does this all work? To obtain the value found in the output array at index [0,0] of 22, you sum the values of a[0,0] * b[0,0] (which is 1), a[0,1] * b[1,0] (which is 6), and a[0,2] * b[2,0] (which is 15) to obtain the value of 22. The other entries work precisely the same way.
To perform an element-by-element multiplication using two matrix
objects, you must use the numpy
multiply()
function.