我一直在使用sklearn的NearestNeighbors进行名称匹配,但在某个点上,结果开始出现错位。我的标准化名称列表有数亿条。我需要匹配的名称列表相对较小,但仍可能在25万到50万的范围内。在某个点之后,索引似乎开始偏移1个或更多。
nbrs = NearestNeighbors(n_neighbors=1, n_jobs=-1).fit(tfidf) unique_org = set(names['VariationName'].values) # set used for increased performance#matching query:def getNearestN(query): queryTFIDF_ = vectorizer.transform(query) distances, indices = nbrs.kneighbors(queryTFIDF_) return distances, indicesprint('Getting nearest n...')distances, indices = getNearestN(unique_org)unique_org = list(unique_org) #need to convert back to a listprint('Finding matches...')matches = []for i,j in enumerate(indices): temp = [round(distances[i][0],2), clean_org_names.values[j][0][0],unique_org[i]] matches.append(temp)print('Building data frame...') matches = pd.DataFrame(matches, columns=['Match confidence (lower is better)','Matched name','Original name'])print('Data frame built')
看起来一旦我的标准化列表超过8万条,结果就会开始向下偏移。
“杂乱名称”为VITALI, ANGELO(带有逗号)
VITALI, ANGELO
标准化名称列表可能包括这些(没有逗号)
VITALI ANGELO SENSABLE TECHNOLOGIES INC
在通过上述匹配运行后,下面的结果显示VITALI, ANGELO与SENSABLE TECHNOLOGIES INC几乎完美匹配,因为索引向下偏移了一个…我认为是这样。
0.00 SENSABLE TECHNOLOGIES INC VITALI, ANGELO
是否有可能是因为记录的大小或数量超出了矩阵限制,从而导致索引出现混乱?
回答:
集合通常不保证顺序的保留。因此,getNearestN
遍历unique_org
的顺序可能与list
构造函数的顺序不同:
distances, indices = getNearestN(unique_org) # computed distances with respect to an unordered setunique_org = list(unique_org) # `unique_org` was potentially shuffled here
尝试改用列表,看看是否有效。如果使用列表速度明显变慢,我怀疑罪魁祸首是重复名称,而不是集合更适合这项工作。你可以在pandas中处理重复项(names['VariationName'].unique()
),或者在普通Python中处理(list(set(names['VariationName']))
)。
总之,我会确保没有重复项(可能使用pandas),然后始终使用列表,看看是否有效。
来源:
集合对象是不同可哈希对象的无序集合。