gpt4 book ai didi

python - 向量化 Numpy 中的操作

转载 作者:太空宇宙 更新时间:2023-11-03 13:37:31 26 4
gpt4 key购买 nike

我正在尝试在不使用循环的情况下在 Numpy 上执行以下操作:

  • 我有一个维度为 N*d 的矩阵 X 和一个维度为 N 的向量 y。y 包含从 1 到 K 的整数。
  • 我想得到一个大小为 K*d 的矩阵 M,其中 M[i,:]=np.mean(X[y==i,:],0)

我可以不使用循环实现吗?

有了循环,它会像这样。

import numpy as np

N=3
d=3
K=2

X=np.eye(N)
y=np.random.randint(1,K+1,N)
M=np.zeros((K,d))
for i in np.arange(0,K):
line=X[y==i+1,:]
if line.size==0:
M[i,:]=np.zeros(d)
else:
M[i,:]=mp.mean(line,0)

提前谢谢你。

最佳答案

代码基本上是从 X 中收集特定的行并添加它们,我们在 np.add.reduceat 中内置了一个 NumPy | .因此,以这一点为重点,以矢量化方式解决它的步骤可能如下所列 -

# Get sort indices of y
sidx = y.argsort()

# Collect rows off X based on their IDs so that they come in consecutive order
Xr = X[np.arange(N)[sidx]]

# Get unique row IDs, start positions of each unique ID
# and their counts to be used for average calculations
unq,startidx,counts = np.unique((y-1)[sidx],return_index=True,return_counts=True)

# Add rows off Xr based on the slices signified by the start positions
vals = np.true_divide(np.add.reduceat(Xr,startidx,axis=0),counts[:,None])

# Setup output array and set row summed values into it at unique IDs row positions
out = np.zeros((K,d))
out[unq] = vals

关于python - 向量化 Numpy 中的操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37236666/

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