基于余弦相似度的物品-物品推荐

Item-item recommendation based on cosine similarity

作为我正在构建的推荐系统的一部分,我想实现一个基于余弦相似度的项目间推荐。理想情况下,我想计算由 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 个最相似的项目?

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

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