【问题标题】:How do I get the dot product of two matrices using numpy?如何使用 numpy 获得两个矩阵的点积?
【发布时间】:2018-04-30 07:56:04
【问题描述】:

我正在尝试使用numpy 获取向量和矩阵的点积,但出现以下异常:ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)

基本上我只想将 2x1 矩阵(2 行向量)与 2x2 矩阵相乘,但 numpy 似乎不支持这一点。我已经尝试过用 1x2 矩阵做同样的事情,而且效果很好,但没有给我想要的结果。

我使用的代码是:

inputs = np.matrix([[1], [0]])
weights = np.matrix([[1, 2], [3, 4]])
print(np.add(np.dot(inputs, weights), 0))

#desired result = array([1, 3])

所以我的问题是:如何使用 numpy 执行我想要的操作?

编辑

会发生这样的事情:

>>> import numpy as np
>>> a = np.matrix([[1], [0]])
>>> b = np.matrix([[1, 2], [3, 4]])
>>> a * b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist- 
packages/numpy/matrixlib/defmatrix.py", line 309, in __mul__
    return N.dot(self, asmatrix(other))
ValueError: shapes (2,1) and (2,2) not aligned: 1 (dim 1) != 2 (dim 0)

【问题讨论】:

    标签: python numpy matrix vector


    【解决方案1】:

    点积适用于相同大小的向量。你可以在 numpy 中将矩阵相乘。如果您需要不同的解决方案 - 请在问题中包含您的代码和期望的结果。

    a = np.array([2,3])
    b = np.array([[4,5],[6,7]])
    
    >>> a * b
    array([[ 8, 15],
        [12, 21]])
    

    更新每个更新的问题:

    inputs = np.matrix([[1], [0]])
    weights = np.matrix([[1, 2], [3, 4]])
    >>> weights * inputs
    matrix([[1],
            [3]])
    

    【讨论】:

    • 更新答案。
    • 这只不过是操作数的顺序......我切换了它们并且它起作用了!非常感谢!
    猜你喜欢
    • 2018-02-04
    • 2018-10-02
    • 2015-03-31
    • 1970-01-01
    • 2017-05-10
    • 1970-01-01
    • 2017-02-26
    • 2019-10-08
    • 2022-01-26
    相关资源
    最近更新 更多