我是python的新手,对代码感到困惑
X = np.array([2,3,4,4])
print(np.dot(X,X))
这有效
Y = np.array([[100],
[200],
[300],
[400]])
print(np.dot(Y,Y))
不是。我了解这是由于与数组尺寸的关系。但我不明白如何。请解释。
答案 0 :(得分:0)
X
是一维数组(行向量不是正确的描述符):
In [382]: X = np.array([2,3,4,4])
In [383]: X.shape
Out[383]: (4,)
In [384]: np.dot(X,X) # docs for 1d arrays apply
Out[384]: 45
Y
是2d数组。
In [385]: Y = X[:,None]
In [386]: Y
Out[386]:
array([[2],
[3],
[4],
[4]])
In [387]: Y.shape
Out[387]: (4, 1)
In [388]: np.dot(Y,Y)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-388-3a0bc5156893> in <module>()
----> 1 np.dot(Y,Y)
ValueError: shapes (4,1) and (4,1) not aligned: 1 (dim 1) != 4 (dim 0)
对于2d数组,第一个对的最后一个维度与第二个对的最后一个维度。
In [389]: np.dot(Y,Y.T) # (4,1) pair with (1,4) to produce (4,4)
Out[389]:
array([[ 4, 6, 8, 8],
[ 6, 9, 12, 12],
[ 8, 12, 16, 16],
[ 8, 12, 16, 16]])
In [390]: np.dot(Y.T,Y) # (1,4) pair with (4,1) to produce (1,1)
Out[390]: array([[45]])