gpt4 book ai didi

python - 基于另一个数组在 Numpy 数组中设置值

转载 作者:行者123 更新时间:2023-11-28 21:43:25 25 4
gpt4 key购买 nike

1 term_map 跟踪哪个术语在哪个位置。

In [256]: term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])

In [257]: term_map
Out[257]: array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])

2 term_scores 跟踪每个术语在每个位置的权重。

In [258]: term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])

In [259]: term_scores
Out[259]: array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])

3 获取唯一值和逆索引。

In [260]: unqID, idx = np.unique(term_map, return_inverse=True)

In [261]: unqID
Out[261]: array([0, 2, 3, 4])

4 计算唯一值的分数。

In [262]: value_sums = np.bincount(idx, term_scores)

In [263]: value_sums
Out[263]: array([ 4., 16., 9., 21.])

5 初始化要更新的数组。索引对应于 term_map 变量中的值。

In [254]: vocab = np.zeros(13)

In [255]: vocab
Out[255]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])

6 DESIRED: 将 3 中列出的位置对应的值 4 插入到 vocab 变量中。

In [255]: updated_vocab
Out[255]: array([ 4., 0., 16., 9., 21., 0., 0., 0., 0., 0., 0., 0., 0.])

如何创建 6?

最佳答案

事实证明,我们可以避免 np.unique 这一步,通过输入 term_mapterm_scores 直接获得所需的输出到 np.bincount 并提及输出数组的长度及其可选参数 minlength

因此,我们可以简单地做 -

final_output = np.bincount(term_map, term_scores, minlength=13)

sample 运行-

In [142]: term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])
...: term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])
...:

In [143]: np.bincount(term_map, term_scores, minlength=13)
Out[143]:
array([ 4., 0., 16., 9., 21., 0., 0., 0., 0., 0., 0.,
0., 0.])

关于python - 基于另一个数组在 Numpy 数组中设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42282726/

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