gpt4 book ai didi

python - 按行查找矩阵和向量之间的交集

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

考虑以下几点:

tmp1 = ['a', 'b', 'c', 'd', 'e']
tmp2 = ['f', 'g', 'h', 'b', 'd']
tmp3 = ['b', 'i', 'j', 'k', 'l']
matr = np.array([tmp1, tmp2, tmp3])

matr

产生一个矩阵:

array([['a', 'b', 'c', 'd', 'e'],
['f', 'g', 'h', 'b', 'd'],
['b', 'i', 'j', 'k', 'l']],
dtype='|S1')

现在,我想知道与向量相交的每一行中值的总和。说,

vec = ['a', 'c', 'f', 'b']
[sum([y in vec for y in row]) for row in matr]

返回,

[3, 2, 1]

这是期望的输出。它的问题是我的“matr”实际上是 ≈ 1000000 x 2200,我有 6700 个向量要比较。我这里的解决方案太慢了,无法尝试。

我怎样才能改进我正在做的事情?

值得注意的是,matr 中的值来自一组约 30000 个值,我有完整的集合。我已经考虑过解决方案,我对每个向量进行了这 30000 个值的字典,并在按行求和之前使用字典将整个矩阵转换为 True/False。我不确定这是否有帮助。

最佳答案

对于 matrvec 作为数组,这里有一个 np.searchsorted -

def count_in_rowwise(matr,vec):
sidx = vec.argsort()
idx = np.searchsorted(vec,matr,sorter=sidx)
idx[idx==len(vec)] = 0
return (vec[sidx[idx]] == matr).sum(1)

使用相对较小的 vec,我们可以对其进行预排序并使用,为我们提供另一种方法来计算行数,就像这样 -

def count_in_rowwise_v2(matr,vec,assume_sorted=False):
if assume_sorted==1:
sorted_vec = vec
else:
sorted_vec = np.sort(vec)
idx = np.searchsorted(sorted_vec,matr)
idx[idx==len(sorted_vec)] = 0
return (sorted_vec[idx] == matr).sum(1)

上述解决方案适用于通用输入(类似数字或字符串)。为了解决字符串的具体情况,我们可以通过使用 np.unique 将字符串转换为数字,然后重新使用 count_in_rowwise/count_in_rowwise_v2 来进一步优化它,这将给出我们是第二种方法,就像这样 -

u,ids = np.unique(matr, return_inverse=True)
out = count_in_rowwise(ids.reshape(matr.shape),ids[np.searchsorted(u,vec)])

关于python - 按行查找矩阵和向量之间的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55171006/

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