gpt4 book ai didi

python - (Python) 具有优先数组的两个数组之间的映射

转载 作者:行者123 更新时间:2023-12-01 01:55:50 28 4
gpt4 key购买 nike

给定一个源数组

src = np.random.rand(320,240)

和一个索引数组

idx = np.indices(src.shape).reshape(2, -1)
np.random.shuffle(idx.T)

我们可以将 src 中的线性索引 i 映射到目标数组中的二维索引 idx[:,i] dst 通过

dst = np.empty_like(src)
dst[tuple(idx)] = src.ravel()

这在 Python: Mapping between two arrays with an index array 中进行了讨论

但是,如果此映射不是一对一,即 src 中的多个条目映射到 dst 中的同一条目,according to the docs未指定哪个源条目将写入 dst:

For advanced assignments, there is in general no guarantee for the iteration order. This means that if an element is set more than once, it is not possible to predict the final result.

如果我们另外给出一个优先级数组

p = np.random.rand(*src.shape)

如何使用p来消除这种情况的歧义,即根据p写入优先级最高的条目?

最佳答案

这是一种使用稀疏矩阵进行排序的方法(它的开销很大,但比 argsort 具有更好的扩展性,大概是因为它使用了一些类似于基数排序的方法(?))。没有优先级的重复索引显式设置为 -1。我们使目标数组的一个单元太大,多余的单元充当垃圾桶。

import numpy as np
from scipy import sparse

N = 2
idx = np.random.randint(0, N, (2, N, N))
prec = np.random.random((N, N))
src = np.arange(N*N).reshape(N, N)

def f_sparse(idx, prec, src):
idx = np.ravel_multi_index(idx, src.shape).ravel()
sp = sparse.csr_matrix((prec.ravel(), idx, np.arange(idx.size+1)),
(idx.size, idx.size)).tocsc()
top = sp.indptr.argmax()
mx = np.repeat(np.maximum.reduceat(sp.data, sp.indptr[:top]),
np.diff(sp.indptr[:top+1]))
res = idx.copy()
res[sp.indices[sp.data != mx]] = -1

dst = np.full((idx.size + 1,), np.nan)
dst[res] = src.ravel()
return dst[:-1].reshape(src.shape)

print(idx)
print(prec)
print(src)
print(f_sparse(idx, prec, src))

示例运行:

[[[1 0]
[1 0]]

[[0 1]
[0 0]]]
[[0.90995366 0.92095225]
[0.60997092 0.84092015]]
[[0 1]
[2 3]]
[[ 3. 1.]
[ 0. nan]]

关于python - (Python) 具有优先数组的两个数组之间的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50205937/

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