【发布时间】:2021-01-06 19:40:41
【问题描述】:
目标:我正在尝试创建一个有序的项目列表,这些项目根据它们与测试项目的接近程度进行排名。
我有 1 个具有 10 个属性的测试项目和 250,000 个具有 10 个属性的项目。我想要一个对 250,000 个项目进行排名的列表。例如,如果结果列表返回 [10,50,21,11,10000....] 比索引 10 的项目最接近我的测试项目,索引 50 是第二接近我的测试项目,等等。
我尝试过的方法适用于小数据帧,但不适用于较大的数据帧:
import pandas as pd
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity
similarity_matrix = pd.np.random.rand(4,4)
#4 items with the first being the test
#0.727048 0.113704 0.886672 0.0345438
#0.496636 0.678949 0.0627973 0.547752
#0.641021 0.498811 0.628728 0.575058
#0.760778 0.955595 0.646792 0.126714
#creates the cosine similarity matrix
winner = cosine_similarity(similarity_matrix)
#I just need the first row, how similar each item is to the test, I'm excluding how similar the test is to the test
winner = np.argsort(winner[0:1,1:])
#I want to reverse the order and add one so the list matches the original index
winner = np.flip(winner) +1
不幸的是,250,000 我收到以下错误“MemoryError: Unable to allocate 339. GiB for an array with shape (250000, 250000) and data type float64”
我真的只需要第一行,而不是创建一个 250000X250000 矩阵。还有其他方法吗?
【问题讨论】:
标签: python pandas numpy sklearn-pandas cosine-similarity