我在R和Python中尝试了矩阵和向量的元素乘法(*),得到了如下不同的结果。
这是R:
#R input
a=matrix(c(1,2,3,4,5,6,7,8),byrow=T,nrow=4)
b=c(9,10)
print(a)
print(b)
print(a*b)
#R output
# a
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
# b
[1] 9 10
# a*b
[,1] [,2]
[1,] 9 18
[2,] 30 40
[3,] 45 54
[4,] 70 80这是Python:
#Python input
a=np.array([[1,2],[3,4],[5,6],[7,8]])
b=np.array([9,10])
print(a)
print(b)
print(a*b)
#Python output
# a
[[1 2]
[3 4]
[5 6]
[7 8]]
# b
[ 9 10]
# a*b
[[ 9 20]
[27 40]
[45 60]
[63 80]]在执行*时,R和Python似乎不同地扩展了向量b。R使用以下矩阵逐元素乘一个元素:
[,1] [,2]
[1,] 9 9
[2,] 10 10
[3,] 9 9
[4,] 10 10Python使用以下矩阵:
[[ 9 10]
[ 9 10]
[ 9 10]
[ 9 10]]有人能解释一下为什么他们有不同的广播方式吗?Python是否有任何函数或操作符,其结果与R的结果相同?
谢谢!
发布于 2022-01-26 17:21:10
发布于 2022-01-26 17:20:46
我不知道R,所以不会试图解释它的行为。
In [130]: a=np.array([[1,2],[3,4],[5,6],[7,8]])
...: b=np.array([9,10])
In [131]: a.shape
Out[131]: (4, 2)
In [132]: b.shape
Out[132]: (2,)
In [133]: a*b
Out[133]:
array([[ 9, 20],
[27, 40],
[45, 60],
[63, 80]])numpy的广播规则如下
就你的情况而言,这相当于:
(4,2) * (2,) => (4,2) * (1,2) => (4,2) * (4,2) => (4,2)b被视为一个(4,2)数组,其中2列中有9和10:
In [134]: a*b.reshape(1,2)
Out[134]:
array([[ 9, 20],
[27, 40],
[45, 60],
[63, 80]])numpy广播不像R显示的那样复制值,但您可以使用repeat或tile这样做:
In [139]: b1 = np.tile(b[:,None],(2,1))
In [140]: b1
Out[140]:
array([[ 9],
[10],
[ 9],
[10]])
In [141]: a*b1
Out[141]:
array([[ 9, 18],
[30, 40],
[45, 54],
[70, 80]])这里的尺寸是
(4,2) * (4,1) => (4,2)即使我将b设为(2,1),numpy也不会像R那样重复它:
In [144]: b[:,None]
Out[144]:
array([[ 9],
[10]])
In [145]: a*b[:,None]
Traceback (most recent call last):
File "<ipython-input-145-a2236f333443>", line 1, in <module>
a*b[:,None]
ValueError: operands could not be broadcast together with shapes (4,2) (2,1) https://stackoverflow.com/questions/70866779
复制相似问题