I am trying to find the cosine similarity between two columns of type array in a pyspark dataframe and add the cosine similarity as a third column, as shown below
| Col1 | Col2 | Dot Prod |
|---|---|---|
| [0.5, 0.6 ... 0.7] | [0.5, 0.3 .... 0.1] | dotProd(Col1, Col2) |
The current implementation I have is:
import pyspark.sql.functions as func
def cosine_similarity(df, col1, col2):
df_cosine = df.select(func.sum(df[col1] * df[col2]).alias('dot'),
func.sqrt(func.sum(df[col1]**2)).alias('norm1'),
func.sqrt(func.sum(df[col2] **2)).alias('norm2'))
d = df_cosine.rdd.collect()[0].asDict()
return d['dot']/(d['norm1'] * d['norm2'])
But I guess the above code only for works for columns with integer values. Is there anyway I would be able to extend the above function to achieve a similar behavior for array columns