你可以这样前进:
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)