【问题标题】:How come python do multiplication of two 4x1 matrices with same shapepython怎么做两个具有相同形状的4x1矩阵的乘法
【发布时间】:2020-10-29 17:26:20
【问题描述】:

我刚刚意识到 python 将两个 4x1 矩阵相乘,但据我所知,不可能将两个 4x1 矩阵与另一个 4x1 矩阵相乘。我写了以下代码来测试这个:

import numpy as np

first_four_by_one = np.array([[1], [2], [3], [4]])
print(first_four_by_one.shape)

second_four_by_one = np.array([[4], [5], [6], [7]])
print(second_four_by_one.shape)

result = first_four_by_one * second_four_by_one
print(result.shape)
print(result)

结果如下:

(4, 1)
(4, 1)
(4, 1)
[[ 4]
 [10]
 [18]
 [28]]

谁能描述一下?

【问题讨论】:

  • 这是一个元素乘法。数学矩阵乘法在较新的 Python 版本中有自己的运算符 @
  • 嗯,这不是矩阵乘法。它只是将两个数组的所有成员相乘。

标签: python numpy matrix-multiplication


【解决方案1】:

您实际上是在执行逐元素矩阵乘法。要执行矩阵乘法,您应该使用 numpy 函数np.dot()

对于二维矩阵,您还可以使用代表np.matmul()@ 运算符。正如here 所写,此运算符在处理更高维矩阵 (>2D) 时可能会导致副作用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-06-01
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-16
    • 2020-03-06
    • 2020-12-06
    相关资源
    最近更新 更多