我正在使用以下内容来相互比较多个字符串。这是我能设计出的最快的方法,但它会产生非常大的二维数组。我可以查看并看到我想要的内容。理想情况下,我想设置一个阈值并将每个值的索引拉到该数字以上。让事情变得更复杂的是,我不希望索引将字符串与其自身进行比较,并且该字符串可能在其他地方重复,所以我想知道是否是这种情况,所以我不能只忽略 1。
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
texts = sql.get_corpus()
vectorizer = TfidfVectorizer()
vectors = vectorizer.fit_transform(texts)
similarity = cosine_similarity(vectors)
sql.get_corups()
返回字符串列表,目前有 1600 个字符串。
我想要的可以吗?我尝试使用 Levenshtein 来比较每个 1.4M 组合,这确实有效,但需要 2.5 小时,而上面的一半则需要 2.5 小时。我还尝试过使用 spacy 的 vecotrs,这需要几天时间。
最佳答案
我不完全确定我正确地阅读了您的帖子,但我相信这应该可以帮助您开始:
import numpy as np
# randomly distributed data we want to filter
data = np.random.rand(5, 5)
# get index of all values above a threshold
threshold = 0.5
above_threshold = data > threshold
# I am assuming your matrix has all string comparisons to
# itself on the diagonal
not_ident = np.identity(5) == 0.
# [edit: to prevent duplicate comparisons, use this instead of not_ident]
#upper_only = np.triu(np.ones((5,5)) - np.identity(5))
# 2D array, True when criteria met
result = above_threshold * not_ident
print(result)
# original shape, but 0 in place of all values not matching above criteria
values_orig_shape = data * result
print(values_orig_shape)
# all values that meet criteria, as a 1D array
values = data[result]
print(values)
# indices of all values that meet criteria (in same order as values array)
indices = [index for index,value in np.ndenumerate(result) if value]
print(indices)
关于python - 您可以从 numpy 数组或 pandas 数据帧中提取超过阈值的数据索引吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66391988/