【问题标题】:Sklearn Nearest Neighbors and unseen dataSklearn 最近邻和看不见的数据
【发布时间】:2018-06-01 02:14:08
【问题描述】:

我使用最近邻查找密切相关的客户,以便向目标客户推荐热门产品。我已经拟合了一个训练用户的稀疏矩阵来获得余弦距离。但是,我无法在拟合模型上获得新用户的索引和距离,因为这些用户不在原始矩阵中。有没有办法解决这个问题,还是每次引入新用户时我都必须重新调整模型?

谢谢!!

from scipy.sparse import csr_matrix
train_df = train.pivot(index = 'user', columns = 'product_id', values = 'rating').fillna(0)
test_df = test.pivot(index = 'user', columns = 'product_id', values = 'rating').fillna(0)
train_mat = csr_matrix(train_df.values)
test_mat = csr_matrix(test_df.values)

from sklearn.neighbors import NearestNeighbors

model_knn = NearestNeighbors(metric = 'cosine', algorithm = 'brute', n_neighbors=30)
model_knn.fit(train_mat)

test_user = list(np.sort(test_df.user.unique())) 

list1=[]
query_index = np.random.choice(test_user)
distances, indices = model_knn.kneighbors(test_df.loc[query_index, :].values.reshape(1, -1))
for i in range(0, len(distances.flatten())):
    list1.append(test_df.index[indices.flatten()[i]])

这里是错误信息:

ValueError: Incompatible dimension for X and Y matrices: X.shape[1] == 1605 while Y.shape[1] == 2724

【问题讨论】:

  • 这感觉很宽泛。我不清楚您是在谈论 冷启动问题 还是只是在使用旧软件的 API。在后者中,我们可能需要看代码。
  • 感谢@sascha。我的道歉不清楚。刚刚编辑了帖子。

标签: python nearest-neighbor collaborative-filtering


【解决方案1】:

documentation 中声明:

Returns:
dist : array
    Array representing the lengths to points, only present if return_distance=True

所以你可以试试:

distances, indices = model_knn.kneighbors( 
    test_df.loc[query_index,:].values.reshape(1, -1), 
    return_distance=True
  )

【讨论】:

    猜你喜欢
    • 2016-09-10
    • 2020-05-05
    • 1970-01-01
    • 2016-06-18
    • 2019-01-03
    • 2012-12-28
    • 2011-08-10
    • 2018-07-29
    • 2022-01-01
    相关资源
    最近更新 更多