gpt4 book ai didi

python - Numpy 意味着现在需要 reshape ?

转载 作者:太空宇宙 更新时间:2023-11-04 08:55:20 25 4
gpt4 key购买 nike

我想用列的平均值减去 numpy 数组中的所有值。

以前,以下代码有效:

centered_data = data - data.mean(axis = 1)

现在这段代码产生如下错误信息:

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

将此行更改为:

centered_data = data - data.mean(axis = 1).reshape(data.shape[0],1)

数据是 numpy.ndarray 类型。

为什么平均向量现在需要 reshape ,而以前不需要?

最佳答案

np.mean 有一个 keepdims 参数。 (data.mean 也有它,但它记录在 np.mean 中):

In [642]: data=np.arange(12).reshape(3,4)

In [643]: data.mean(axis=1, keepdims=True)
Out[643]:
array([[ 1.5],
[ 5.5],
[ 9.5]])

In [644]: data-data.mean(axis=1, keepdims=True)
Out[644]:
array([[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5],
[-1.5, -0.5, 0.5, 1.5]])

如果没有这个,meansum 等操作会删除一个维度。 reshape(-1,1)[:,None] 也可以重新添加维度。

如果您在另一个轴上取平均值,则不需要保留(或恢复)尺寸。这是因为如果需要,广播规则会在开头自动添加一个维度:

In [645]: data-data.mean(axis=0)
Out[645]:
array([[-4., -4., -4., -4.],
[ 0., 0., 0., 0.],
[ 4., 4., 4., 4.]])

您的“之前”案例是否像这样 - 在 axis=0 上减少?

我不知道 numpy 有任何变化可以启用 axis=1 情况而无需某种 reshape 或 keeaxis。


如果 data.shape==(3, 4)

data+np.array([1,1,1,1])
# data+np.array([1,1,1,1])[None,:] # automatic None

有效。

这引发了一个值错误:

data+np.array([1,1,1])
ValueError: operands could not be broadcast together with shapes (3,4) (3)

这个有效:

data+np.array([1,1,1])[:,None]

关于python - Numpy 意味着现在需要 reshape ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30734174/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com