【问题标题】:Item-item recommendation based on cosine similarity基于余弦相似度的item-item推荐
【发布时间】:2019-09-08 20:32:41
【问题描述】:

作为我正在构建的推荐系统的一部分,我想实现基于余弦相似度的项目推荐。理想情况下,我想计算由 2048 个特征的 DenseVector 表示的 100 万个项目的余弦相似度,以便获得与给定项目最相似的前 n 个项目。

我的问题是我遇到的解决方案在我的数据集上表现不佳。

我试过了:

这是使用 columnSimilarities() 的解决方案

import pyspark
from pyspark.sql import SparkSession
from pyspark.ml.feature import PCA
from pyspark.mllib.linalg.distributed import IndexedRow, IndexedRowMatrix
from pyspark.sql.functions import row_number

new_df = url_rdd.zip(vector_rdd.map(lambda x:Vectors.dense(x))).toDF(schema=['url','features'])

# PCA
pca = PCA(k=1024, inputCol="features", outputCol="pca_features")
pca_model = pca.fit(new_df)
pca_df = pca_model.transform(new_df)

# Indexing my dataframe
pca_df.createOrReplaceTempView('pca_df')
indexed_df = spark.sql('select row_number() over (order by url) - 1 as id, * from pca_df')

# Computing Cosine Similarity
mat = IndexedRowMatrix(indexed_df.select("id", "pca_features").rdd.map(lambda row: IndexedRow(row.id, row.pca_features.toArray()))).toBlockMatrix().transpose().toIndexedRowMatrix()
cos_mat = mat.columnSimilarities()

在 pyspark 上是否有更好的解决方案来计算余弦相似度并获得前 n 个最相似的项目?

【问题讨论】:

  • 我看到您使用的是 lambda,因此强制反序列化为 Python 对象。这可能是性能问题的根源。您能否在示例中提供完整的导入,以便我们获得实际的 mcve 并知道哪些部分来自 pyspark,哪些不是?
  • 感谢您的回复 Oliver,我编辑了代码。

标签: python apache-spark pyspark cosine-similarity recommender-systems


【解决方案1】:

考虑缓存new_df,因为您至少要检查两次(一次用于拟合模型,另一次用于转换数据)。

此外,不要忘记可以传递给columnSimilarities 方法的可选阈值。

【讨论】:

  • 感谢您的提示!我尝试使用阈值,但似乎在使用 IndexedRowMatrix 时我无法将参数传递给columnSimilarities(但它适用于 RowMatrix)
  • 是的,只有当columnSimilarities 是从RowMatrix 使用而不是IndexedRowMatrix 时,该阈值才可接受。
猜你喜欢
  • 2014-09-21
  • 2018-01-23
  • 2015-06-07
  • 2014-12-02
  • 2011-02-21
  • 2020-08-12
  • 2020-02-03
  • 1970-01-01
  • 2011-01-01
相关资源
最近更新 更多