numpy 1d数组与矩阵形状不匹配

ki1q1bka  于 2023-08-05  发布在  其他
关注(0)|答案(1)|浏览(114)

我在基本的numpy代码中收到一条错误消息,说明我的矩阵和id数组(I np.dot()在一起)的形状没有对齐。
我试着一遍又一遍地通读代码,但我仍然不能弄清楚。
代码:import numpy as np

X = [0.2, 0.1, 0.1, -0.9 ]
weights = [[0.3, 0.4, 0.5],
           [-0.1, 0.9, -0.23],
           [0.05, -0.3, 0.7],
           [0.5, -0.123 , -0.008]]
   

biases = 2   
output = np.dot(weights, X) + biases

print(output)

字符串
如你所见,有一个矩阵和一个一维数组,矩阵的形状=(3,4),一维数组的形状=(4,)
下面是错误代码:

output = np.dot(weights, X) + biases
  File "<__array_function__ internals>", line 200, in dot
ValueError: shapes (4,3) and (4,) not aligned: 3 (dim 1) != 4 (dim 0)

mec1mxoz

mec1mxoz1#

矩阵不是你说的(3,4),而是(4,3),错误消息告诉你。因此,您的尺寸不兼容。您可以通过交换点积调用的顺序或转置weights来解决此问题。
由于你有Python列表,你必须将它们转换为numpy数组来执行转置。使用numpy时,最好只使用numpy数组。

import numpy as np

X = np.array([0.2, 0.1, 0.1, -0.9])
weights = np.array([[0.3, 0.4, 0.5],
                    [-0.1, 0.9, -0.23],
                    [0.05, -0.3, 0.7],
                    [0.5, -0.123, -0.008]])

biases = 2
output = np.dot(weights.T, X) + biases
print(output)  # [1.605  2.2507 2.1542]

字符串

相关问题