evaluate embeddings as recommendations on X_test
Source: openai_cookbooks

## User and product embeddingsWe calculate user and product embeddings based on the training set, and evaluate the results on the unseen test set. We will evaluate the results by plotting the user and product similarity versus the review score. The dataset is created in the [Get_embeddings_from_dataset Notebook](Get_embeddings_from_dataset.ipynb).### 1. Calculate user and product embeddingsWe calculate these embeddings simply by averaging all the reviews about the same product or written by the same user within the training set.```pythonimport pandas as pdimport numpy as npfrom sklearn.model_selection import train_test_splitfrom ast import literal_evaldf = pd.read_csv('data/fine_food_reviews_with_embeddings_1k.csv', index_col=0)  # note that you will need to generate this file to run the code belowdf.head(2)```<div><style scoped>    .dataframe tbody tr th:only-of-type {        vertical-align: middle;    }    .dataframe tbody tr th {        vertical-align: top;    }    .dataframe thead th {        text-align: right;    }</style><table border="1" class="dataframe">  <thead>    <tr style="text-align: right;">      <th></th>      <th>ProductId</th>      <th>UserId</th>      <th>Score</th>      <th>Summary</th>      <th>Text</th>      <th>combined</th>      <th>n_tokens</th>      <th>embedding</th>    </tr>  </thead>  <tbody>    <tr>      <th>0</th>      <td>B003XPF9BO</td>      <td>A3R7JR3FMEBXQB</td>      <td>5</td>      <td>where does one  start...and stop... with a tre...</td>      <td>Wanted to save some to bring to my Chicago fam...</td>      <td>Title: where does one  start...and stop... wit...</td>      <td>52</td>      <td>[0.03599238395690918, -0.02116263099014759, -0...</td>    </tr>    <tr>      <th>297</th>      <td>B003VXHGPK</td>      <td>A21VWSCGW7UUAR</td>      <td>4</td>      <td>Good, but not Wolfgang Puck good</td>      <td>Honestly, I have to admit that I expected a li...</td>      <td>Title: Good, but not Wolfgang Puck good; Conte...</td>      <td>178</td>      <td>[-0.07042013108730316, -0.03175969794392586, -...</td>    </tr>  </tbody></table></div>```pythondf['babbage_similarity'] = df["embedding"].apply(literal_eval).apply(np.array)X_train, X_test, y_train, y_test = train_test_split(df, df.Score, test_size = 0.2, random_state=42)user_embeddings = X_train.groupby('UserId').babbage_similarity.apply(np.mean)prod_embeddings = X_train.groupby('ProductId').babbage_similarity.apply(np.mean)len(user_embeddings), len(prod_embeddings)```    (577, 706)We can see that most of the users and products appear within the 50k examples only once.### 2. Evaluate the embeddingsTo evaluate the recommendations, we look at the similarity of the user and product embeddings amongst the reviews in the unseen test set. We calculate the cosine distance between the user and product embeddings, which gives us a similarity score between 0 and 1. We then normalize the scores to be evenly split between 0 and 1, by calculating the percentile of the similarity score amongst all predicted scores.```pythonfrom utils.embeddings_utils import cosine_similarity# evaluate embeddings as recommendations on X_testdef evaluate_single_match(row):    user_id = row.UserId    product_id = row.ProductId    try:        user_embedding = user_embeddings[user_id]        product_embedding = prod_embeddings[product_id]        similarity = cosine_similarity(user_embedding, product_embedding)        return similarity    except Exception as e:        return np.nanX_test['cosine_similarity'] = X_test.apply(evaluate_single_match, axis=1)X_test['percentile_cosine_similarity'] = X_test.cosine_similarity.rank(pct=True)```#### 2.1 Visualize cosine similarity by review scoreWe group the cosine similarity scores by the review score, and plot the distribution of cosine similarity scores for each review score.```pythonimport matplotlib.pyplot as pltimport statsmodels.api as smcorrelation = X_test[['percentile_cosine_similarity', 'Score']].corr().values[0,1]print('Correlation between user & vector similarity percentile metric and review number of stars (score): %.2f%%' % (100*correlation))# boxplot of cosine similarity for each scoreX_test.boxplot(column='percentile_cosine_similarity', by='Score')plt.title('')plt.show()plt.close()```    Correlation between user & vector similarity percentile metric and review number of stars (score): 29.56%    ![png](output_8_1.png)    We can observe a weak trend, showing that the higher the similarity score between the user and the product embedding, the higher the review score. Therefore, the user and product embeddings can weakly predict the review score - even before the user receives the product!Because this signal works in a different way than the more commonly used collaborative filtering, it can act as an additional feature to slightly improve the performance on existing problems.