# Matrix Factorization via Singular Value Decomposition

Matrix factorization is the breaking down of one matrix in a product of multiple matrices. It's extremely well studied in mathematics, and it's highly useful. There are many different ways to factor matrices, but singular value decomposition is particularly useful for making recommendations.

So what is singular value decomposition (SVD)? At a high level, SVD is an algorithm that decomposes a matrix $R$ into the best lower rank (i.e. smaller/simpler) approximation of the original matrix $R$. Mathematically, it decomposes R into a two unitary matrices and a diagonal matrix:

$$\begin{equation}
R = U\Sigma V^{T}
\end{equation}$$

where R is users's ratings matrix, $U$ is the user "features" matrix, $\Sigma$ is the diagonal matrix of singular values (essentially weights), and $V^{T}$ is the movie "features" matrix. $U$ and $V^{T}$ are orthogonal, and represent different things. $U$ represents how much users "like" each feature and $V^{T}$ represents how relevant each feature is to each movie.

To get the lower rank approximation, we take these matrices and keep only the top $k$ features, which we think of as the underlying tastes and preferences vectors.



```python
import pandas as pd
import numpy as np
```


```python
movies_df = pd.read_csv('movies.csv')
movies_df['movie_id'] = movies_df['movie_id'].apply(pd.to_numeric)
movies_df.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>movie_id</th>
      <th>title</th>
      <th>genres</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>Toy Story (1995)</td>
      <td>Adventure|Animation|Children|Comedy|Fantasy</td>
    </tr>
    <tr>
      <th>1</th>
      <td>2</td>
      <td>Jumanji (1995)</td>
      <td>Adventure|Children|Fantasy</td>
    </tr>
    <tr>
      <th>2</th>
      <td>3</td>
      <td>Grumpier Old Men (1995)</td>
      <td>Comedy|Romance</td>
    </tr>
  </tbody>
</table>
</div>




```python
ratings_df=pd.read_csv('ratings.csv')
ratings_df.head(3)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>user_id</th>
      <th>movie_id</th>
      <th>rating</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>1</td>
      <td>31</td>
      <td>2.5</td>
    </tr>
    <tr>
      <th>1</th>
      <td>1</td>
      <td>1029</td>
      <td>3.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>1</td>
      <td>1061</td>
      <td>3.0</td>
    </tr>
  </tbody>
</table>
</div>



These look good, but I want the format of my ratings matrix to be one row per user and one column per movie. I'll `pivot` `ratings_df` to get that and call the new variable `R`.


```python
R_df = ratings_df.pivot(index = 'user_id', columns ='movie_id', values = 'rating').fillna(0)
R_df.head()
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>movie_id</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
      <th>7</th>
      <th>8</th>
      <th>9</th>
      <th>10</th>
      <th>...</th>
      <th>161084</th>
      <th>161155</th>
      <th>161594</th>
      <th>161830</th>
      <th>161918</th>
      <th>161944</th>
      <th>162376</th>
      <th>162542</th>
      <th>162672</th>
      <th>163949</th>
    </tr>
    <tr>
      <th>user_id</th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>1</th>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>...</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>2</th>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>4.0</td>
      <td>...</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>3</th>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>...</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>4</th>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>4.0</td>
      <td>...</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
    <tr>
      <th>5</th>
      <td>0.0</td>
      <td>0.0</td>
      <td>4.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>...</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
      <td>0.0</td>
    </tr>
  </tbody>
</table>
<p>5 rows × 9066 columns</p>
</div>



The last thing I need to do is de-mean the data (normalize by each users mean) and convert it from a dataframe to a numpy array.


```python
R = R_df.as_matrix()
user_ratings_mean = np.mean(R, axis = 1)
R_demeaned = R - user_ratings_mean.reshape(-1, 1)
```

# Singular Value Decomposition

Scipy and Numpy both have functions to do the singular value decomposition. I'm going to use the Scipy function `svds` because it let's me choose how many latent factors I want to use to approximate the original ratings matrix (instead of having to truncate it after).


```python
from scipy.sparse.linalg import svds
U, sigma, Vt = svds(R_demeaned, k = 50)
```

Done. The function returns exactly what I detailed earlier in this post, except that the $\Sigma$ returned is just the values instead of a diagonal matrix. This is useful, but since I'm going to leverage matrix multiplication to get predictions I'll convert it to the diagonal matrix form.


```python
sigma = np.diag(sigma)
```

# Making Predictions from the Decomposed Matrices

I now have everything I need to make movie ratings predictions for every user. I can do it all at once by following the math and matrix multiply $U$, $\Sigma$, and $V^{T}$ back to get the rank $k=50$ approximation of $R$.

I also need to add the user means back to get the actual star ratings prediction.


```python
all_user_predicted_ratings = np.dot(np.dot(U, sigma), Vt) + user_ratings_mean.reshape(-1, 1)
```


```python
preds_df = pd.DataFrame(all_user_predicted_ratings, columns = R_df.columns)
preds_df.head()
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th>movie_id</th>
      <th>1</th>
      <th>2</th>
      <th>3</th>
      <th>4</th>
      <th>5</th>
      <th>6</th>
      <th>7</th>
      <th>8</th>
      <th>9</th>
      <th>10</th>
      <th>...</th>
      <th>161084</th>
      <th>161155</th>
      <th>161594</th>
      <th>161830</th>
      <th>161918</th>
      <th>161944</th>
      <th>162376</th>
      <th>162542</th>
      <th>162672</th>
      <th>163949</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>-0.054239</td>
      <td>0.045130</td>
      <td>-0.004835</td>
      <td>-0.019817</td>
      <td>-0.011284</td>
      <td>0.041373</td>
      <td>-0.007822</td>
      <td>-0.017188</td>
      <td>0.012246</td>
      <td>0.037670</td>
      <td>...</td>
      <td>-0.005258</td>
      <td>-0.005453</td>
      <td>0.012369</td>
      <td>-0.004991</td>
      <td>-0.004639</td>
      <td>-0.019055</td>
      <td>0.021402</td>
      <td>-0.006365</td>
      <td>-0.006098</td>
      <td>-0.004819</td>
    </tr>
    <tr>
      <th>1</th>
      <td>0.419835</td>
      <td>1.406440</td>
      <td>-0.188807</td>
      <td>0.156658</td>
      <td>0.268032</td>
      <td>0.414698</td>
      <td>0.052172</td>
      <td>0.044728</td>
      <td>-0.020198</td>
      <td>2.220256</td>
      <td>...</td>
      <td>-0.005909</td>
      <td>-0.003974</td>
      <td>-0.012555</td>
      <td>-0.003555</td>
      <td>-0.002711</td>
      <td>-0.071621</td>
      <td>-0.016212</td>
      <td>0.001047</td>
      <td>-0.001468</td>
      <td>-0.006577</td>
    </tr>
    <tr>
      <th>2</th>
      <td>1.345619</td>
      <td>0.266505</td>
      <td>-0.011962</td>
      <td>0.012278</td>
      <td>0.079508</td>
      <td>0.090960</td>
      <td>-0.122094</td>
      <td>0.031327</td>
      <td>-0.018023</td>
      <td>0.141176</td>
      <td>...</td>
      <td>-0.002647</td>
      <td>-0.002364</td>
      <td>-0.010153</td>
      <td>0.000277</td>
      <td>-0.000116</td>
      <td>-0.018063</td>
      <td>-0.015761</td>
      <td>0.010611</td>
      <td>0.006792</td>
      <td>-0.006357</td>
    </tr>
    <tr>
      <th>3</th>
      <td>1.133455</td>
      <td>1.046982</td>
      <td>0.141275</td>
      <td>0.081841</td>
      <td>-0.339675</td>
      <td>-1.484659</td>
      <td>-0.263096</td>
      <td>-0.169750</td>
      <td>-0.021862</td>
      <td>1.611664</td>
      <td>...</td>
      <td>0.020805</td>
      <td>0.000410</td>
      <td>0.056040</td>
      <td>-0.002817</td>
      <td>-0.000767</td>
      <td>0.159159</td>
      <td>0.087519</td>
      <td>-0.030854</td>
      <td>-0.021279</td>
      <td>0.048529</td>
    </tr>
    <tr>
      <th>4</th>
      <td>1.389578</td>
      <td>1.466495</td>
      <td>0.605557</td>
      <td>-0.029647</td>
      <td>0.729380</td>
      <td>-0.118539</td>
      <td>-0.026017</td>
      <td>0.065577</td>
      <td>-0.156655</td>
      <td>0.307926</td>
      <td>...</td>
      <td>-0.007422</td>
      <td>-0.011810</td>
      <td>0.006644</td>
      <td>-0.005159</td>
      <td>-0.001249</td>
      <td>-0.034658</td>
      <td>0.016456</td>
      <td>0.001710</td>
      <td>-0.004166</td>
      <td>-0.001864</td>
    </tr>
  </tbody>
</table>
<p>5 rows × 9066 columns</p>
</div>




```python
def recommend_movies(predictions_df, userID, movies_df, original_ratings_df, num_recommendations):
    
    # Get and sort the user's predictions
    user_row_number = userID - 1 # UserID starts at 1, not 0
    sorted_user_predictions = preds_df.iloc[user_row_number].sort_values(ascending=False) # UserID starts at 1
    
    # Get the user's data and merge in the movie information.
    user_data = original_ratings_df[original_ratings_df.user_id == (userID)]
    user_full = (user_data.merge(movies_df, how = 'left', left_on = 'movie_id', right_on = 'movie_id').
                     sort_values(['rating'], ascending=False)
                 )

    print('User {0} has already rated {1} movies.'.format(userID, user_full.shape[0]))
    print('Recommending highest {0} predicted ratings movies not already rated.'.format(num_recommendations))
    
    # Recommend the highest predicted rating movies that the user hasn't seen yet.
    recommendations = (movies_df[~movies_df['movie_id'].isin(user_full['movie_id'])].
         merge(pd.DataFrame(sorted_user_predictions).reset_index(), how = 'left',
               left_on = 'movie_id',
               right_on = 'movie_id').
         rename(columns = {user_row_number: 'Predictions'}).
         sort_values('Predictions', ascending = False).
                       iloc[:num_recommendations, :-1]
                      )

    return user_full, recommendations
```


```python
already_rated, predictions = recommend_movies(preds_df,11, movies_df, ratings_df, 10)
```

    User 11 has already rated 38 movies.
    Recommending highest 10 predicted ratings movies not already rated.



```python
predictions
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>movie_id</th>
      <th>title</th>
      <th>genres</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>279</th>
      <td>318</td>
      <td>Shawshank Redemption, The (1994)</td>
      <td>Crime|Drama</td>
    </tr>
    <tr>
      <th>6894</th>
      <td>58559</td>
      <td>Dark Knight, The (2008)</td>
      <td>Action|Crime|Drama|IMAX</td>
    </tr>
    <tr>
      <th>2359</th>
      <td>2959</td>
      <td>Fight Club (1999)</td>
      <td>Action|Crime|Drama|Thriller</td>
    </tr>
    <tr>
      <th>530</th>
      <td>608</td>
      <td>Fargo (1996)</td>
      <td>Comedy|Crime|Drama|Thriller</td>
    </tr>
    <tr>
      <th>1356</th>
      <td>1732</td>
      <td>Big Lebowski, The (1998)</td>
      <td>Comedy|Crime</td>
    </tr>
    <tr>
      <th>959</th>
      <td>1213</td>
      <td>Goodfellas (1990)</td>
      <td>Crime|Drama</td>
    </tr>
    <tr>
      <th>7264</th>
      <td>70286</td>
      <td>District 9 (2009)</td>
      <td>Mystery|Sci-Fi|Thriller</td>
    </tr>
    <tr>
      <th>2025</th>
      <td>2542</td>
      <td>Lock, Stock &amp; Two Smoking Barrels (1998)</td>
      <td>Comedy|Crime|Thriller</td>
    </tr>
    <tr>
      <th>520</th>
      <td>593</td>
      <td>Silence of the Lambs, The (1991)</td>
      <td>Crime|Horror|Thriller</td>
    </tr>
    <tr>
      <th>871</th>
      <td>1089</td>
      <td>Reservoir Dogs (1992)</td>
      <td>Crime|Mystery|Thriller</td>
    </tr>
  </tbody>
</table>
</div>




```python
already_rated.head(10)
```




<div>
<style>
    .dataframe thead tr:only-child th {
        text-align: right;
    }

    .dataframe thead th {
        text-align: left;
    }

    .dataframe tbody tr th {
        vertical-align: top;
    }
</style>
<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>user_id</th>
      <th>movie_id</th>
      <th>rating</th>
      <th>title</th>
      <th>genres</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>0</th>
      <td>11</td>
      <td>50</td>
      <td>5.0</td>
      <td>Usual Suspects, The (1995)</td>
      <td>Crime|Mystery|Thriller</td>
    </tr>
    <tr>
      <th>7</th>
      <td>11</td>
      <td>923</td>
      <td>5.0</td>
      <td>Citizen Kane (1941)</td>
      <td>Drama|Mystery</td>
    </tr>
    <tr>
      <th>36</th>
      <td>11</td>
      <td>104841</td>
      <td>5.0</td>
      <td>Gravity (2013)</td>
      <td>Action|Sci-Fi|IMAX</td>
    </tr>
    <tr>
      <th>18</th>
      <td>11</td>
      <td>26614</td>
      <td>5.0</td>
      <td>Bourne Identity, The (1988)</td>
      <td>Action|Adventure|Drama|Mystery|Thriller</td>
    </tr>
    <tr>
      <th>17</th>
      <td>11</td>
      <td>6598</td>
      <td>5.0</td>
      <td>Step Into Liquid (2002)</td>
      <td>Documentary</td>
    </tr>
    <tr>
      <th>10</th>
      <td>11</td>
      <td>1408</td>
      <td>5.0</td>
      <td>Last of the Mohicans, The (1992)</td>
      <td>Action|Romance|War|Western</td>
    </tr>
    <tr>
      <th>9</th>
      <td>11</td>
      <td>1201</td>
      <td>5.0</td>
      <td>Good, the Bad and the Ugly, The (Buono, il bru...</td>
      <td>Action|Adventure|Western</td>
    </tr>
    <tr>
      <th>19</th>
      <td>11</td>
      <td>48516</td>
      <td>5.0</td>
      <td>Departed, The (2006)</td>
      <td>Crime|Drama|Thriller</td>
    </tr>
    <tr>
      <th>37</th>
      <td>11</td>
      <td>106487</td>
      <td>5.0</td>
      <td>The Hunger Games: Catching Fire (2013)</td>
      <td>Action|Adventure|Sci-Fi|IMAX</td>
    </tr>
    <tr>
      <th>4</th>
      <td>11</td>
      <td>296</td>
      <td>5.0</td>
      <td>Pulp Fiction (1994)</td>
      <td>Comedy|Crime|Drama|Thriller</td>
    </tr>
  </tbody>
</table>
</div>



# Conclusion

We've seen that we can make good recommendations with raw data based collaborative filtering methods (neighborhood models) and latent features from low-rank matrix factorization methods (factorization models).

Low-dimensional matrix recommenders try to capture the underlying features driving the raw data (which we understand as tastes and preferences). From a theoretical perspective, if we want to make recommendations based on people's tastes, this seems like the better approach. This technique also scales **significantly** better to larger datasets.

However, we still likely lose some meaningful signals by using a lower-rank matrix. And though these factorization based techniques work extremely well, there's research being done on new methods. These efforts have resulted in various types probabilistic matrix factorization (which works and scales even better) and many other approaches.

0e10669f34e5476b4c81bae13ce1309f272e9456
ipynb
Jupyter Notebook
recommender-system/ml-latest-small/model.ipynb
ankitpandey2708/ml
2d32e91cb5a73dd47306cc32a8eedd379aaee032
MIT
recommender-system/ml-latest-small/model.ipynb
ankitpandey2708/ml
2d32e91cb5a73dd47306cc32a8eedd379aaee032
MIT
recommender-system/ml-latest-small/model.ipynb
ankitpandey2708/ml
2d32e91cb5a73dd47306cc32a8eedd379aaee032
MIT
Qwen/Qwen-72B
1. YES
2. YES