2

numpy 的一维向量如何参与计算

 3 years ago
source link: https://zhiqiang.org/coding/numpy-array-is-row.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

numpy 的一维向量如何参与计算

作者: 张志强

, 发表于 2020-09-10

, 共 620 字 , 共阅读 131 次

numpy 的一维向量:

a = np.array([1, 2, 3])
a.shape # (3,)

一维向量没有行列之分,它可以转置(a.T),但值不变。而且它参与到计算的方式很有意思:

b = a.reshape((3, 1))
c = a.reshape((1, 3))

a + b # shape: (3, 3)
b + a # shape: (3, 3)

a + c # shape: (1, 3)
c + a # shape: (3, 1)

np.dot(a, b) # shape: (1,)
np.dot(b, a) # error

np.dot(a, c) # error
np.dot(c, a) # shape: (1,)
  • 一维向量在广播运算时,是作为行向量的,需要时,将被复制多行。
  • 一维向量在参与矩阵乘法时,如果放在前面作为行向量,放在后面作为列向量。所以np.dot(a, a)是合法的,相当于向量内积。

其中第一条结合 numpy 矩阵取行取列都返回行向量,有时候会和预期不一样:

m = np.array(range(9)).reshape((3, 3))
c = m[:, 0] # 此处c为一维向量,而不是一个列。
a = np.array([1, 2, 3]).reshape((3, 1))
a + c # shape: (3, 3),其中 c 被当做一个行向量。

Q. E. D.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK