【发布时间】:2019-09-08 20:32:41
【问题描述】:
作为我正在构建的推荐系统的一部分,我想实现基于余弦相似度的项目推荐。理想情况下,我想计算由 2048 个特征的 DenseVector 表示的 100 万个项目的余弦相似度,以便获得与给定项目最相似的前 n 个项目。
我的问题是我遇到的解决方案在我的数据集上表现不佳。
我试过了:
Calculating the cosine similarity between all the rows of a dataframe in pyspark
使用来自 mllib.linalg.distributed 的 columnSimilarities()
使用 PCA 降低维度
这是使用 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