如何使scikitlearn近邻算法运行得更快?

2024-04-18 12:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试运行一个基于文本的推荐系统,从大约56K个零件的文件中查找零件的类别: 例如:铜管->;电线, 电视-电子设备等

但是,在我的8gbram系统中运行时,获得推荐系统输出大约需要4个小时。我试着在一个32gb左右的ram上运行相同的脚本,但是在计算时间上没有任何改进,仍然需要4个小时。推荐系统的训练集约为11k

如何让我的推荐系统运行得更快?脚本似乎没有有效地利用内存。任何帮助都将不胜感激。你知道吗

注:所示的示例仅用于说明,原始数据集要复杂得多。你知道吗

from sklearn.neighbors import NearestNeighbors

#Code for recommendation system
def recommendhts(x,model,train):
    distance,index=model.kneighbors(x.toarray(),n_neighbors=1)
    mi=distance.argmax()
    idx=index[mi][0]
    return(train.iloc[idx]['sHTS'],distance[0][0])

#Training the model of training set
train=pd.read_csv('train0207190144.csv')
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(train['keywords'])
x=X.toarray()
df=pd.DataFrame(x,columns=vectorizer.get_feature_names())
model=NearestNeighbors(metric='correlation',n_neighbors=1)
model.fit(df)
vect=vectorizer.fit(train['keywords'])

#Fitting the Count vectoriser on keywords(product description to be queried)

x_new=vect.transform(product['keywords'])

for i in range(len(product)):
    key=x_new[i]
    output,probability=recommendhts(key,model,train)

编辑: 我附加了评测Code profiling results结果的快照,如注释中所示。我运行了1000行的样本,所用的时间大约是1085秒。你知道吗


Tags: 脚本formodel系统时间codeneighborstrain
1条回答
网友
1楼 · 发布于 2024-04-18 12:09:50

首先,您肯定需要分析您的代码。我建议对profiling your script使用IPython/Jupyter中的%prunmagic命令。你知道吗

还有几件事要尝试

  1. 设置“n\u jobs”参数,以便在进行预测时允许并行性。你知道吗

    # setting n_jobs=2 will use 2 cores; setting n_jobs=-1 will use all cores
    model=NearestNeighbors(metric='correlation',n_neighbors=1, n_jobs=2)
    
  2. 我不清楚重新拟合vectorizer是必要的。你知道吗

    vect=vectorizer.fit(train['keywords'])  # can be removed?
    

最后,您应该能够对预测进行矢量化并替换for循环,但这需要重构您的推荐系统,如果没有更多信息,我将无能为力。你知道吗

相关问题 更多 >