我正在尝试使用numpy来向量化下面的函数,结果完全丢失了。
A = ndarray: Z x 3
B = ndarray: Z x 3
C = integer
D = ndarray: C x 3伪码:
entries = []
means = []
For i in range(C):
for p in range(len(B)):
if B[p] == D[i]:
entries.append(A[p])
means.append(columnwise_means(entries))
return means一个例子是:
A = [[1,2,3],[1,2,3],[4,5,6],[4,5,6]]
B = [[9,8,7],[7,6,5],[1,2,3],[3,4,5]]
C = 2
D = [[1,2,3],[4,5,6]]返回:
[average([9,8,7],[7,6,5]), average(([1,2,3],[3,4,5])] = [[8,7,6],[2,3,4]]我试过使用np.where、np.argwhere、np.mean等,但似乎没有达到预期的效果。任何帮助都将不胜感激。
谢谢!
发布于 2016-03-28 17:25:39
按照问题的预期输出,我假设在实际代码中,您应该有:
if A[p] == D[i],和entries.append(B[p])中追加。所以,这里有一个用NumPy broadcasting和dot-product进行矢量化的方法-
mask = (D[:,None,:] == A).all(-1)
out = mask.dot(B)/(mask.sum(1)[:,None])如果输入数组是整数数组,则可以节省内存并提高性能,将数组视为n维数组的索引,从而创建2D mask而不像3D那样-
dims = np.maximum(A.max(0),D.max(0))+1
mask = np.ravel_multi_index(D.T,dims)[:,None] == np.ravel_multi_index(A.T,dims)样本运行-
In [107]: A
Out[107]:
array([[1, 2, 3],
[1, 2, 3],
[4, 5, 6],
[4, 5, 6]])
In [108]: B
Out[108]:
array([[9, 8, 7],
[7, 6, 5],
[1, 2, 3],
[3, 4, 5]])
In [109]: mask = (D[:,None,:] == A).all(-1)
...: out = mask.dot(B)/(mask.sum(1)[:,None])
...:
In [110]: out
Out[110]:
array([[8, 7, 6],
[2, 3, 4]])发布于 2016-03-28 17:14:11
我看到两个提示:
首先,逐行比较数组。这样做的一种方法是简化1D中的索引系统:
def indexer(M,base=256):
return (M*base**arange(3)).sum(axis=1)基数是整数> A.max()。然后选择就可以这样做:
indices=np.equal.outer(indexer(D),indexer(A))适用于:
array([[ True, True, False, False],
[False, False, True, True]], dtype=bool)第二,每个组都有不同的长度,因此最后一步的矢量化是困难的。这里是完成这份工作的方法。
B=array(B)
means=[B[i].mean(axis=0) for i in indices]https://stackoverflow.com/questions/36266295
复制相似问题