I am trying to compute cosine similarity between a given user_id
from user's table and another table with movies in order to sort out most similar movies to recommend.
Cosine similarity: = dot(a,b) / (norm(a) * norm(b))
or dot(a,b)/sqrt((dot(a)*dot(b))
df = self.given_user.crossJoin(self.movies_df)
df = df.select('userId', 'movieId', 'user_features', 'movie_features')
df = df.rdd.map(lambda x: (x[0], x[1], x[2], x[3], float(np.dot(np.array(x[2]), np.array(x[3]))))).toDF(df.columns + ['dotxy'])
df = df.rdd.map(lambda x: (x[0], x[1], x[2], x[3], x[4], float(np.dot(np.array(x[2]), np.array(x[2]))))).toDF(df.columns + ['dotxx'])
df = df.rdd.map(lambda x: (x[0], x[1], x[2], x[3], x[4], x[5], float(np.dot(np.array(x[3]), np.array(x[3]))))).toDF(df.columns + ['dotyy'])
output = df.withColumn('cosine_sim', F.col("dotxy") / F.sqrt(F.col("dotxx") * F.col("dotyy")))
output.select('userId', 'movieId', 'dotxy', 'dotxx', 'dotyy', 'cosine_sim').orderBy('cosine_sim', ascending=False).show(5)
The resulting output looks like:
+------+-------+-----+-----+-----+----------+
|userId|movieId|dotxy|dotxx|dotyy|cosine_sim|
+------+-------+-----+-----+-----+----------+
| 18| 1430| 1.0| 0.5| 2.0| 1.0|
| 18| 2177| 1.0| 0.5| 2.0| 1.0|
| 18| 1565| 1.0| 0.5| 2.0| 1.0|
| 18| 415| 1.0| 0.5| 2.0| 1.0|
| 18| 1764| 1.0| 0.5| 2.0| 1.0|
+------+-------+-----+-----+-----+----------+
Is there more efficient/ compact way of cosine similarity function implementation in PySpark 1.6?
You could use more numpy
functions.
import numpy as np
df = spark.createDataFrame([(18, 1, [1, 0, 1], [1, 1, 1])]).toDF('userId','movieId','user_features','movie_features')
df.rdd.map(lambda x: (x[0], x[1], x[2], x[3], float(np.dot(np.array(x[2]), np.array(x[3])) / (np.linalg.norm(np.array(x[2])) * np.linalg.norm(np.array(x[3])))))).toDF(df.columns + ['cosine_sim']).show()
+------+-------+-------------+--------------+------------------+
|userId|movieId|user_features|movie_features| cosine_sim |
+------+-------+-------------+--------------+------------------+
| 18| 1| [1, 0, 1]| [1, 1, 1]|0.8164965809277259|
+------+-------+-------------+--------------+------------------+