如何使用numpy将矩阵与另一个矩阵中的每一行相乘

时间:2019-10-29 05:33:46

标签: python numpy

import numpy
A = numpy.array([
  [0,1,1],
  [2,2,0],
  [3,0,3]
])

B = numpy.array([
  [1,1,1],
  [2,2,2],
  [3,2,9],
  [4,4,4],
  [5,9,5]
])

A的尺寸:N * N(3 * 3)

B的尺寸:K * N(5 * 3)

预期结果是:     C = [A * B [0],A * B [1],A * B [2],A * B [3],A * B [4]](C的尺寸也是5 * 3)

我是numpy的新手,不确定在不使用for循环的情况下如何执行此操作。

谢谢!

2 个答案:

答案 0 :(得分:3)

您可以这样前进:

import numpy as np

matrix_a = np.array([
    [0, 1, 1],
    [2, 2, 0],
    [3, 0, 3]
])

matrix_b = np.array([
    [1, 1, 1],
    [2, 2, 2],
    [3, 2, 9],
    [4, 4, 4],
    [5, 9, 5]
])

记住: 对于matrix乘法,matrix-A的第一列的顺序== matrix-B的第一行的顺序-例如:B->(3,3)==(3,5),要获取矩阵的列和行的顺序,可以使用:

rows_of_second_matrix = matrix_b.shape[0]
columns_of_first_matrix = matrix_a.shape[1]

在这里,您可以检查matrix-A的第一列的顺序== matrix-B的第一行的顺序。如果顺序不相同,则进行matrix-B的转置,否则只需相乘即可。

if columns_of_first_matrix != rows_of_second_matrix:

    transpose_matrix_b = np.transpose(matrix_b)

    output_1 = np.dot(matrix_a, transpose_matrix_b)
    print('Shape of dot product:', output_1.shape)
    print('Dot product:\n {}\n'.format(output_1))

    output_2 = np.matmul(matrix_a, transpose_matrix_b)
    print('Shape of matmul product:', output_2.shape)
    print('Matmul product:\n {}\n'.format(output_2))

    # In order to obtain -> Output_Matrix of shape (5, 3), Again take transpose

    output_matrix = np.transpose(output_1)
    print("Shape of required matrix: ", output_matrix.shape)

else:
    output_1 = np.dot(matrix_a, matrix_b)
    print('Shape of dot product:', output_1.shape)
    print('Dot product:\n {}\n'.format(output_1))

    output_2 = np.matmul(matrix_a, matrix_b)
    print('Shape of matmul product:', output_2.shape)
    print('Matmul product:\n {}\n'.format(output_2))

    output_matrix = output_2
    print("Shape of required matrix: ", output_matrix.shape)

输出:

   - Shape of dot product: (3, 5)
    Dot product:
     [[ 2  4 11  8 14]
     [ 4  8 10 16 28]
     [ 6 12 36 24 30]]

    - Shape of matmul product: (3, 5)
    Matmul product:
     [[ 2  4 11  8 14]
     [ 4  8 10 16 28]
     [ 6 12 36 24 30]]

    - Shape of required matrix:  (5, 3)

答案 1 :(得分:2)

根据您提供的数学公式,我认为您正在评估A乘以B换位。如果您希望结果矩阵的大小为5 * 3,则可以对其进行转置(相当于numpy.matmul(B.transpose(),A))

import numpy
A = numpy.array([
  [0,1,1],
  [2,2,0],
  [3,0,3]
])

B = numpy.array([
  [1,1,1],
  [2,2,2],
  [3,2,9],
  [4,4,4],
  [5,9,5]
])

print(numpy.matmul(A,B.transpose()))
output :array([[ 2,  4, 11,  8, 14],
               [ 4,  8, 10, 16, 28],
               [ 6, 12, 36, 24, 30]])

for i in range(5):
    print (numpy.matmul(A,B[i]))
Output:
[2 4 6]
[ 4  8 12]
[11 10 36]
[ 8 16 24]
[14 28 30]