元素级除法,比如MATLAB的./operator?

2024-05-08 22:17:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试规范化一些Nx3数据。如果X是Nx3数组,D是Nx1数组,在MATLAB中,我可以这样做 Y=X/D

如果我在Python中执行以下操作,就会得到一个错误

X = np.random.randn(100,3)    
D = np.linalg.norm(X,axis=1)
Y = X/D

ValueError: operands could not be broadcast together with shapes (100,3) (100,) 

有什么建议吗

编辑:多亏了dm2

Y = X/D.reshape((100,1))

另一种方法是使用scikitlearn

from sklearn import preprocessing
Y = preprocessing.normalize(X)

1条回答
网友
1楼 · 发布于 2024-05-08 22:17:58

从阵列广播的numpy documentation开始:

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its way left. Two dimensions are compatible when

  1. they are equal, or
  2. one of them is 1

两个阵列的第一维度相同,但X阵列是二维的,而D阵列是一维的,这意味着这两个阵列的形状不符合一起广播的要求

为了确保它们是正确的,您可以将D数组重塑为形状为(100,1)的二维数组,这将满足广播的要求:最右边的维度是3和1(其中一个是1),其他维度是相等的(100和100)

因此:

Y = X/D.reshape((-1,1))

Y = X/D.reshape((100,1))

Y = X/D[:,np.newaxis]

应该给你你想要的结果

相关问题 更多 >

    热门问题