gpt4 book ai didi

python - 如何根据 numpy 中的搜索排序结果创建 "mapping"矩阵?

转载 作者:行者123 更新时间:2023-12-01 00:40:35 24 4
gpt4 key购买 nike

我想基于两个输入数组(XI 和 X)创建一个 MxN 矩阵,其中如果该列表示针对该行的 X 值(在 XI 内)排序的搜索结果,则每行都有 1。

代码:

import numpy as np

XI = np.array([1., 2., 4., 5., 7.])
X = np.array([6.5, 2.2, 1.4, 4., 3.7, 3.9, 0.1, 5.3, 10.2])

def bmap(xi, x):
i = np.searchsorted(xi, x, side="right") - 1
result_shape = (x.shape[0], xi.shape[0])
result = np.zeros(result_shape)
for row, column in enumerate(i):
if -1 < column < xi.shape[0] - 1:
result[row,column] = 1.
return result

bmap(XI, X)

预期输出:

array([[0., 0., 0., 1., 0.],
[0., 1., 0., 0., 0.],
[1., 0., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 0., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 0.]])

如何仅使用矢量化操作(例如排除 i 的枚举和边界检查)来执行此操作?奖励积分也可以在 TensorFlow 中使用(因为最终我试图将其移植到 TensorFlow,以便我可以利用算法微分)。

最佳答案

如果我理解你只是想将索引 i 转换为数组中的位置(每行一个),除非该索引为负数或位于最后一列。

i = np.searchsorted(xi, x, side="right") - 1
# array([ 3, 1, 0, 2, 1, 1, -1, 3, 4], dtype=int64)

创建输出数组和有效值掩码:

out=np.zeros([x.size, xi.size])
valid = (i>-1)&(i<xi.shape[0] - 1)
#valid: array([ True, True, True, True, True, True, False, True, False])

使用valid掩码来索引行,i(如果有效)用作列的索引:

out[valid, i[valid]] = 1

关于python - 如何根据 numpy 中的搜索排序结果创建 "mapping"矩阵?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57375455/

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