<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://douglasrizzo.github.io/feed.xml" rel="self" type="application/atom+xml"/><link href="https://douglasrizzo.github.io/" rel="alternate" type="text/html" hreflang="en"/><updated>2025-10-06T22:49:47+00:00</updated><id>https://douglasrizzo.github.io/feed.xml</id><title type="html">Douglas Meneghetti</title><subtitle>A simple, whitespace theme for academics. Based on [*folio](https://github.com/bogoli/-folio) design. </subtitle><entry><title type="html">Building a content-based movie recommendation system using the MovieLens dataset</title><link href="https://douglasrizzo.github.io/blog/2025/03/content-based-filtering/" rel="alternate" type="text/html" title="Building a content-based movie recommendation system using the MovieLens dataset"/><published>2025-03-31T00:00:00+00:00</published><updated>2025-03-31T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2025/03/content-based-filtering</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2025/03/content-based-filtering/"><![CDATA[<h2 id="introduction">Introduction</h2> <p>In this project, we will build a movie recommendation system using content-based filtering. We will use the <a href="https://www.kaggle.com/datasets/grouplens/movielens-20m-dataset">MovieLens dataset</a>, provided in Kaggle, which contains movie and user data, to recommend movies to an user based on the genres of movies he has liked the most.</p> <h3 id="resources">Resources</h3> <ul> <li>GitHub repository containing this project and a list of dependencies <a href="https://github.com/douglasrizzo/recsys-movies/blob/master/src/content-based-filtering.ipynb"><img src="https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&amp;logo=github&amp;logoColor=white" alt="GitHub"/></a></li> <li>Open this page in Google Colab <a href="https://colab.research.google.com/github/douglasrizzo/recsys-movies/blob/master/src/content-based-filtering.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a></li> <li><a href="https://douglasrizzo.com.br/blog/2025/03/content-based-filtering/">Read the contents in my website</a></li> </ul> <p>The video below contains an overview of the method we will implement. However, unlike the example above, they use a method which gives more weight to genres a user has rated more movies in. We will fix that mistake and show the differences in both methods.</p> <iframe width="560" height="315" src="https://www.youtube.com/embed/YMZmLx-AUvY?si=jz2I8XVknb9X2Y3a" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen=""></iframe> <h2 id="content-based-filtering-overview">Content-based filtering overview</h2> <p>The idea of content-based filtering is simple.</p> <ol> <li>represent items with a set of features</li> <li>discover a user’s preferences to each of those features, based on items they have already rated/consumed/liked that contain the features</li> <li>infer the user’s preference to unseen items based on those item features.</li> </ol> <p>Unlike more sophisticated recommendation systems, such as collaborative filtering, content-based filtering only uses data provided by a single user to model their preferences. Thus it is much simpler to implement.</p> <h3 id="a-concrete-example">A concrete example</h3> <p>In our project, we will build a movie recommendation system, so let’s build an example using this theme. I will number the steps below and you can look for references to these tables in the Python implementation that comes right after.</p> <ol> <li> <p>We begin with a list of ratings a user has given to the movies they have watched.</p> <table> <thead> <tr> <th>Movie ID</th> <th>Movie Title</th> <th>User Rating</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Inception</td> <td>5.0</td> </tr> <tr> <td>2</td> <td>The Matrix</td> <td>4.5</td> </tr> <tr> <td>3</td> <td>Interstellar</td> <td>4.0</td> </tr> </tbody> </table> </li> <li> <p>Each of the movies belongs to a list of genres.</p> <table> <thead> <tr> <th>Movie ID</th> <th>Movie Title</th> <th>Genres</th> </tr> </thead> <tbody> <tr> <td>1</td> <td>Inception</td> <td>Sci-Fi, Thriller</td> </tr> <tr> <td>2</td> <td>The Matrix</td> <td>Sci-Fi, Action</td> </tr> <tr> <td>3</td> <td>Interstellar</td> <td>Sci-Fi, Drama</td> </tr> </tbody> </table> </li> <li> <p>If we average the ratings the user has given for each movie <em>by genre</em>, we get the user’s ratings for each genre.</p> <ul> <li>Sci-Fi appears in all three movies, so its average rating is: \(\frac{(5.0 + 4.5 + 4.0)}{3} = 4.5\)</li> <li>Thriller appears only in <em>Inception</em>, so its average rating is: <strong>5.0</strong></li> <li>Action appears only in <em>The Matrix</em>, so its average rating is: <strong>4.5</strong></li> <li>Drama appears only in <em>Interstellar</em>, so its average rating is: <strong>4.0</strong></li> </ul> <p>This gives us the ratings by genre for that particular user.</p> <table> <thead> <tr> <th>Genre</th> <th>Average Rating</th> </tr> </thead> <tbody> <tr> <td>Sci-Fi</td> <td>4.5</td> </tr> <tr> <td>Thriller</td> <td>5.0</td> </tr> <tr> <td>Action</td> <td>4.5</td> </tr> <tr> <td>Drama</td> <td>4.0</td> </tr> </tbody> </table> <p>In technical jargon, this is called the <strong><em>user profile</em></strong> and the component in your system that generates this is the <strong><em>user profiler</em></strong>.</p> </li> <li> <p>Now, let’s consider a new list of movies this user has not yet watched.</p> <table> <thead> <tr> <th>Movie ID</th> <th>Movie Title</th> <th>Genres</th> </tr> </thead> <tbody> <tr> <td>4</td> <td>Blade Runner 2049</td> <td>Sci-Fi, Thriller</td> </tr> <tr> <td>5</td> <td>Mad Max: Fury Road</td> <td>Action, Sci-Fi</td> </tr> <tr> <td>6</td> <td>The Social Network</td> <td>Drama</td> </tr> <tr> <td>7</td> <td>The Crow</td> <td>Action, Horror</td> </tr> <tr> <td>8</td> <td>La La Land</td> <td>Musical, Romantic Comedy</td> </tr> </tbody> </table> </li> </ol> <p>When we select and preprocess item features, keeping them ready to match against user profiles, we performing <strong><em>content analysis</em></strong>. In our example, we use movie genres as their features, transforming them into what are called <strong><em>tags</em></strong>, and we are not considering other information such as the movie description, its release date or its director. Some of these could also be transformed into tags, while others need to be processed using NLP techniques.</p> <ol> <li> <p>To estimate the current user’s ratings for these unwatched movies, we take the <strong>average of the user’s ratings for the movie’s genres</strong>:</p> <ul> <li><strong>Blade Runner 2049 (Sci-Fi, Thriller)</strong><br/> \(\frac{(4.5 + 5.0)}{2} = 4.75\)</li> <li><strong>Mad Max: Fury Road (Action, Sci-Fi)</strong><br/> \(\frac{(4.5 + 4.5)}{2} = 4.5\)</li> <li><strong>The Social Network (Drama)</strong> <ul> <li>Drama’s average rating is <strong>4.0</strong>, so the estimated rating is <strong>4.0</strong>.</li> </ul> </li> <li><strong>The Crow (Action, Horror)</strong> <ul> <li>Because the user has not ranked any horror movies yet, we can average over the ratings of the genres we do have. In this case, only Action, whose estimated rating is <strong>4.5</strong>.</li> </ul> </li> <li><strong>La La Land (Musical, Romantic Comedy)</strong> <ul> <li>The user has not rated any romantic comedies or musicals yet, so we are unable to estimate a rating for <em>La La Land</em> and thus we are unable to recommend it to this user.</li> </ul> </li> </ul> <table> <thead> <tr> <th>Movie ID</th> <th>Movie Title</th> <th>Inferred Rating</th> </tr> </thead> <tbody> <tr> <td>4</td> <td>Blade Runner 2049</td> <td>4.75</td> </tr> <tr> <td>5</td> <td>Mad Max: Fury Road</td> <td>4.5</td> </tr> <tr> <td>6</td> <td>The Social Network</td> <td>4.0</td> </tr> <tr> <td>7</td> <td>The Crow</td> <td>4.5</td> </tr> <tr> <td>8</td> <td>La La Land</td> <td>—</td> </tr> </tbody> </table> </li> </ol> <p>Now we know that, if we were to recommend new movies for that user to watch, we would recommend <em>“Blade Runner 2049”</em> first, then <em>“Mad Max: Fury Road”</em> or <em>“The Crow”</em> and <em>“The Social Network”</em> last.</p> <p>The process of selecting ranked items for a given users is called <strong><em>content retrieval</em></strong>.</p> <p>Maybe we would like to prioritize <em>“Mad Max: Fury Road”</em> over <em>“The Crow”</em> since we have more user preference information to estimate the rating of the first movie, but that is not strictly necessary and we can consider them tied until the user rates more movies.</p> <h2 id="downloading-the-dataset">Downloading the dataset</h2> <p>As you have seen above, we need a dataset that contains:</p> <ol> <li>movies with their genres</li> <li>user ratings for movies</li> </ol> <p>Fortunately, the MovieLens dataset has both of these pieces of data. We will download it using the <a href="https://github.com/Kaggle/kagglehub"><code class="language-plaintext highlighter-rouge">kagglehub</code></a> package.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">pathlib</span> <span class="k">as</span> <span class="n">pl</span>

<span class="kn">import</span> <span class="n">kagglehub</span>
<span class="kn">import</span> <span class="n">pandas</span> <span class="k">as</span> <span class="n">pd</span>

<span class="p">(</span><span class="n">mvls_links_path</span><span class="p">,</span> <span class="n">mvls_genometags_path</span><span class="p">,</span> <span class="n">mvls_movies_path</span><span class="p">,</span> <span class="n">mvls_genomescores_path</span><span class="p">,</span> <span class="n">mvls_tags_path</span><span class="p">,</span> <span class="n">mvls_ratings_path</span><span class="p">)</span> <span class="o">=</span> <span class="p">(</span>
  <span class="nf">list</span><span class="p">(</span><span class="n">pl</span><span class="p">.</span><span class="nc">Path</span><span class="p">(</span><span class="n">kagglehub</span><span class="p">.</span><span class="nf">dataset_download</span><span class="p">(</span><span class="sh">"</span><span class="s">grouplens/movielens-20m-dataset</span><span class="sh">"</span><span class="p">)).</span><span class="nf">iterdir</span><span class="p">())</span>
<span class="p">)</span>
<span class="nf">print</span><span class="p">(</span>
  <span class="n">mvls_links_path</span><span class="p">,</span> <span class="n">mvls_genometags_path</span><span class="p">,</span> <span class="n">mvls_movies_path</span><span class="p">,</span> <span class="n">mvls_genomescores_path</span><span class="p">,</span> <span class="n">mvls_tags_path</span><span class="p">,</span> <span class="n">mvls_ratings_path</span>
<span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/home/dodo/.cache/kagglehub/datasets/grouplens/movielens-20m-dataset/versions/1/link.csv /home/dodo/.cache/kagglehub/datasets/grouplens/movielens-20m-dataset/versions/1/genome_tags.csv /home/dodo/.cache/kagglehub/datasets/grouplens/movielens-20m-dataset/versions/1/movie.csv /home/dodo/.cache/kagglehub/datasets/grouplens/movielens-20m-dataset/versions/1/genome_scores.csv /home/dodo/.cache/kagglehub/datasets/grouplens/movielens-20m-dataset/versions/1/tag.csv /home/dodo/.cache/kagglehub/datasets/grouplens/movielens-20m-dataset/versions/1/rating.csv
</code></pre></div></div> <p>MovieLens contains a collection of CSV files. You can see below the movie-related data, which contains the movie and year of release in one column, and all of its genres on another. This equivalent to table 2 in the example.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">movies</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="nf">read_csv</span><span class="p">(</span><span class="n">mvls_movies_path</span><span class="p">).</span><span class="nf">set_index</span><span class="p">(</span><span class="sh">"</span><span class="s">movieId</span><span class="sh">"</span><span class="p">).</span><span class="nf">sort_index</span><span class="p">()</span>
<span class="n">movies</span><span class="p">.</span><span class="nf">head</span><span class="p">()</span>
</code></pre></div></div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>title</th> <th>genres</th> </tr> <tr> <th>movieId</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>1</th> <td>Toy Story (1995)</td> <td>Adventure|Animation|Children|Comedy|Fantasy</td> </tr> <tr> <th>2</th> <td>Jumanji (1995)</td> <td>Adventure|Children|Fantasy</td> </tr> <tr> <th>3</th> <td>Grumpier Old Men (1995)</td> <td>Comedy|Romance</td> </tr> <tr> <th>4</th> <td>Waiting to Exhale (1995)</td> <td>Comedy|Drama|Romance</td> </tr> <tr> <th>5</th> <td>Father of the Bride Part II (1995)</td> <td>Comedy</td> </tr> </tbody> </table> <p>The first thing we will do is represent movie genres by one-hot encoded columns. We will also keep a record of the names of these columns for later.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># get a single list of all unique genres for all movies
</span><span class="n">genres</span> <span class="o">=</span> <span class="nf">list</span><span class="p">(</span><span class="nf">set</span><span class="p">(</span><span class="n">movies</span><span class="p">[</span><span class="sh">"</span><span class="s">genres</span><span class="sh">"</span><span class="p">].</span><span class="nb">str</span><span class="p">.</span><span class="nf">split</span><span class="p">(</span><span class="sh">"</span><span class="s">|</span><span class="sh">"</span><span class="p">).</span><span class="nf">sum</span><span class="p">()))</span>
<span class="n">genres</span> <span class="o">=</span> <span class="nf">sorted</span><span class="p">(</span><span class="n">genres</span><span class="p">)</span>
<span class="n">movies</span> <span class="o">=</span> <span class="n">movies</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="n">movies</span><span class="p">[</span><span class="sh">"</span><span class="s">genres</span><span class="sh">"</span><span class="p">].</span><span class="nb">str</span><span class="p">.</span><span class="nf">get_dummies</span><span class="p">(</span><span class="n">sep</span><span class="o">=</span><span class="sh">"</span><span class="s">|</span><span class="sh">"</span><span class="p">)).</span><span class="nf">drop</span><span class="p">(</span><span class="sh">"</span><span class="s">genres</span><span class="sh">"</span><span class="p">,</span> <span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Unique genres: </span><span class="si">{</span><span class="n">genres</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Number of genres: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">genres</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="n">movies</span><span class="p">.</span><span class="nf">head</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Unique genres: ['(no genres listed)', 'Action', 'Adventure', 'Animation', 'Children', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Fantasy', 'Film-Noir', 'Horror', 'IMAX', 'Musical', 'Mystery', 'Romance', 'Sci-Fi', 'Thriller', 'War', 'Western']
Number of genres: 20
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>title</th> <th>(no genres listed)</th> <th>Action</th> <th>Adventure</th> <th>Animation</th> <th>Children</th> <th>Comedy</th> <th>Crime</th> <th>Documentary</th> <th>Drama</th> <th>...</th> <th>Film-Noir</th> <th>Horror</th> <th>IMAX</th> <th>Musical</th> <th>Mystery</th> <th>Romance</th> <th>Sci-Fi</th> <th>Thriller</th> <th>War</th> <th>Western</th> </tr> <tr> <th>movieId</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>Toy Story (1995)</td> <td>0</td> <td>0</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>2</th> <td>Jumanji (1995)</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>3</th> <td>Grumpier Old Men (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>4</th> <td>Waiting to Exhale (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>5</th> <td>Father of the Bride Part II (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </tbody> </table> <p>5 rows × 21 columns</p> </div> <p>Regarding user ratings to movies, MovieLens provides us with 20 million ratings. In the cell below, you can see a few basic characteristics of user ratings. Most importantly, they range from 0.5 to 5 in intervals of 0.5</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ratings</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="nf">read_csv</span><span class="p">(</span><span class="n">mvls_ratings_path</span><span class="p">)</span>
<span class="n">ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">rating</span><span class="sh">"</span><span class="p">].</span><span class="nf">value_counts</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>rating
4.0    5561926
3.0    4291193
5.0    2898660
3.5    2200156
4.5    1534824
2.0    1430997
2.5     883398
1.0     680732
1.5     279252
0.5     239125
Name: count, dtype: int64
</code></pre></div></div> <p>A user rating to a movie ties a user ID to a movie ID and contains the 0.5–5 rating the user has given the movie. In this project, we will work only with the user whose ID is 1. Let’s peek at some movies he has seen and their ratings.</p> <p>We can see that user 1 has watched and rated 175 movies. That is a lot of movies. Also, the minimum rating user 1 has given to a movie is 3, far from the 0.5 it is allowed to give.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_ratings</span> <span class="o">=</span> <span class="n">ratings</span><span class="p">[</span><span class="n">ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">userId</span><span class="sh">"</span><span class="p">]</span> <span class="o">==</span> <span class="mi">1</span><span class="p">]</span>
<span class="n">ax</span> <span class="o">=</span> <span class="n">user_ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">rating</span><span class="sh">"</span><span class="p">].</span><span class="nf">hist</span><span class="p">(</span><span class="n">bins</span><span class="o">=</span><span class="mi">10</span><span class="p">,</span> <span class="nb">range</span><span class="o">=</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="mi">5</span><span class="p">))</span>
<span class="n">ax</span><span class="p">.</span><span class="nf">bar_label</span><span class="p">(</span><span class="n">ax</span><span class="p">.</span><span class="n">containers</span><span class="p">[</span><span class="mi">0</span><span class="p">]);</span>
</code></pre></div></div> <p><img src="/assets/img/content-based-filtering_9_0.png" alt="png"/></p> <p>This is what the user-movie rating data actually looks like. This is equivalent to table 1 in the example.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_ratings</span><span class="p">.</span><span class="nf">head</span><span class="p">()</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>userId</th> <th>movieId</th> <th>rating</th> <th>timestamp</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>1</td> <td>2</td> <td>3.5</td> <td>2005-04-02 23:53:47</td> </tr> <tr> <th>1</th> <td>1</td> <td>29</td> <td>3.5</td> <td>2005-04-02 23:31:16</td> </tr> <tr> <th>2</th> <td>1</td> <td>32</td> <td>3.5</td> <td>2005-04-02 23:33:39</td> </tr> <tr> <th>3</th> <td>1</td> <td>47</td> <td>3.5</td> <td>2005-04-02 23:32:07</td> </tr> <tr> <th>4</th> <td>1</td> <td>50</td> <td>3.5</td> <td>2005-04-02 23:29:40</td> </tr> </tbody> </table> </div> <h2 id="computing-user-genre-preferences">Computing user-genre preferences</h2> <p>Our goal now will be to generate the user’s features, which will be derived from the genres of the movies they have watched and their ratings.</p> <p>To make things easier for us, we will join user 1’s movie ratings with the genres of those movies.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_ratings</span> <span class="o">=</span> <span class="n">user_ratings</span><span class="p">[[</span><span class="sh">"</span><span class="s">userId</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">movieId</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">rating</span><span class="sh">"</span><span class="p">]].</span><span class="nf">merge</span><span class="p">(</span><span class="n">movies</span><span class="p">,</span> <span class="n">on</span><span class="o">=</span><span class="sh">"</span><span class="s">movieId</span><span class="sh">"</span><span class="p">)</span>
<span class="n">user_ratings</span><span class="p">.</span><span class="nf">head</span><span class="p">()</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>userId</th> <th>movieId</th> <th>rating</th> <th>title</th> <th>(no genres listed)</th> <th>Action</th> <th>Adventure</th> <th>Animation</th> <th>Children</th> <th>Comedy</th> <th>...</th> <th>Film-Noir</th> <th>Horror</th> <th>IMAX</th> <th>Musical</th> <th>Mystery</th> <th>Romance</th> <th>Sci-Fi</th> <th>Thriller</th> <th>War</th> <th>Western</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>1</td> <td>2</td> <td>3.5</td> <td>Jumanji (1995)</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>1</th> <td>1</td> <td>29</td> <td>3.5</td> <td>City of Lost Children, The (Cité des enfants p...</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>2</th> <td>1</td> <td>32</td> <td>3.5</td> <td>Twelve Monkeys (a.k.a. 12 Monkeys) (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>1</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <th>3</th> <td>1</td> <td>47</td> <td>3.5</td> <td>Seven (a.k.a. Se7en) (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <th>4</th> <td>1</td> <td>50</td> <td>3.5</td> <td>Usual Suspects, The (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> </tbody> </table> <p>5 rows × 24 columns</p> </div> <p>Now, we will propagate the user’s ratings to the genres of each movie. by multiplying the ratings user 1 has given to a movie with the genre columns of each movie. You will see that the one-hot encoding of that movie will become the actual ratings user 1 has given to the movie.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># multiply the genre columns by the rating
</span><span class="n">user_ratings</span><span class="p">[</span><span class="n">genres</span><span class="p">]</span> <span class="o">=</span> <span class="n">user_ratings</span><span class="p">[</span><span class="n">genres</span><span class="p">].</span><span class="nf">multiply</span><span class="p">(</span><span class="n">user_ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">rating</span><span class="sh">"</span><span class="p">],</span> <span class="n">axis</span><span class="o">=</span><span class="sh">"</span><span class="s">index</span><span class="sh">"</span><span class="p">)</span>
<span class="n">user_ratings</span><span class="p">.</span><span class="nf">head</span><span class="p">()</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>userId</th> <th>movieId</th> <th>rating</th> <th>title</th> <th>(no genres listed)</th> <th>Action</th> <th>Adventure</th> <th>Animation</th> <th>Children</th> <th>Comedy</th> <th>...</th> <th>Film-Noir</th> <th>Horror</th> <th>IMAX</th> <th>Musical</th> <th>Mystery</th> <th>Romance</th> <th>Sci-Fi</th> <th>Thriller</th> <th>War</th> <th>Western</th> </tr> </thead> <tbody> <tr> <th>0</th> <td>1</td> <td>2</td> <td>3.5</td> <td>Jumanji (1995)</td> <td>0.0</td> <td>0.0</td> <td>3.5</td> <td>0.0</td> <td>3.5</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>1</th> <td>1</td> <td>29</td> <td>3.5</td> <td>City of Lost Children, The (Cité des enfants p...</td> <td>0.0</td> <td>0.0</td> <td>3.5</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>3.5</td> <td>0.0</td> <td>3.5</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>2</th> <td>1</td> <td>32</td> <td>3.5</td> <td>Twelve Monkeys (a.k.a. 12 Monkeys) (1995)</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>3.5</td> <td>0.0</td> <td>3.5</td> <td>3.5</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>3</th> <td>1</td> <td>47</td> <td>3.5</td> <td>Seven (a.k.a. Se7en) (1995)</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>3.5</td> <td>0.0</td> <td>0.0</td> <td>3.5</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>4</th> <td>1</td> <td>50</td> <td>3.5</td> <td>Usual Suspects, The (1995)</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>3.5</td> <td>0.0</td> <td>0.0</td> <td>3.5</td> <td>0.0</td> <td>0.0</td> </tr> </tbody> </table> <p>5 rows × 24 columns</p> </div> <p>Now, if we sum all the ratings user 1 has given to the movies they have watched <em>by genre</em>, we get a proxy value that denotes how much user 1 enjoys each of the genres.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_genre_preferences</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="nc">DataFrame</span><span class="p">(</span>
  <span class="n">data</span><span class="o">=</span><span class="p">{</span><span class="sh">"</span><span class="s">Movies</span><span class="sh">"</span><span class="p">:</span> <span class="p">(</span><span class="n">user_ratings</span><span class="p">[</span><span class="n">genres</span><span class="p">]</span> <span class="o">!=</span> <span class="mi">0</span><span class="p">).</span><span class="nf">sum</span><span class="p">(),</span> <span class="sh">"</span><span class="s">Sum of ratings</span><span class="sh">"</span><span class="p">:</span> <span class="n">user_ratings</span><span class="p">[</span><span class="n">genres</span><span class="p">].</span><span class="nf">sum</span><span class="p">()}</span>
<span class="p">)</span>
<span class="n">user_genre_preferences</span><span class="p">.</span><span class="nf">sort_values</span><span class="p">(</span><span class="sh">"</span><span class="s">Sum of ratings</span><span class="sh">"</span><span class="p">,</span> <span class="n">ascending</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>Movies</th> <th>Sum of ratings</th> </tr> </thead> <tbody> <tr> <th>Adventure</th> <td>73</td> <td>276.5</td> </tr> <tr> <th>Fantasy</th> <td>69</td> <td>261.5</td> </tr> <tr> <th>Action</th> <td>66</td> <td>246.0</td> </tr> <tr> <th>Horror</th> <td>45</td> <td>168.5</td> </tr> <tr> <th>Drama</th> <td>43</td> <td>162.0</td> </tr> <tr> <th>Thriller</th> <td>42</td> <td>158.0</td> </tr> <tr> <th>Comedy</th> <td>41</td> <td>153.0</td> </tr> <tr> <th>Sci-Fi</th> <td>40</td> <td>148.5</td> </tr> <tr> <th>Crime</th> <td>21</td> <td>80.0</td> </tr> <tr> <th>Children</th> <td>19</td> <td>68.5</td> </tr> <tr> <th>Mystery</th> <td>18</td> <td>65.0</td> </tr> <tr> <th>Romance</th> <td>11</td> <td>43.5</td> </tr> <tr> <th>Animation</th> <td>10</td> <td>36.5</td> </tr> <tr> <th>War</th> <td>9</td> <td>33.0</td> </tr> <tr> <th>Western</th> <td>4</td> <td>13.5</td> </tr> <tr> <th>Musical</th> <td>3</td> <td>11.0</td> </tr> <tr> <th>IMAX</th> <td>2</td> <td>8.5</td> </tr> <tr> <th>(no genres listed)</th> <td>0</td> <td>0.0</td> </tr> <tr> <th>Documentary</th> <td>0</td> <td>0.0</td> </tr> <tr> <th>Film-Noir</th> <td>0</td> <td>0.0</td> </tr> </tbody> </table> </div> <p>Because the magnitudes of these sums of ratings can get out of hand, we can divide them by the sum of all ratings and get neat values that all add up to 1.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Normalized sum of ratings</span><span class="sh">"</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span>
  <span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Sum of ratings</span><span class="sh">"</span><span class="p">]</span> <span class="o">/</span> <span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Sum of ratings</span><span class="sh">"</span><span class="p">].</span><span class="nf">max</span><span class="p">()</span>
<span class="p">)</span>
<span class="n">user_genre_preferences</span><span class="p">.</span><span class="nf">sort_values</span><span class="p">(</span><span class="sh">"</span><span class="s">Normalized sum of ratings</span><span class="sh">"</span><span class="p">,</span> <span class="n">ascending</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>Movies</th> <th>Sum of ratings</th> <th>Normalized sum of ratings</th> </tr> </thead> <tbody> <tr> <th>Adventure</th> <td>73</td> <td>276.5</td> <td>1.000000</td> </tr> <tr> <th>Fantasy</th> <td>69</td> <td>261.5</td> <td>0.945750</td> </tr> <tr> <th>Action</th> <td>66</td> <td>246.0</td> <td>0.889693</td> </tr> <tr> <th>Horror</th> <td>45</td> <td>168.5</td> <td>0.609403</td> </tr> <tr> <th>Drama</th> <td>43</td> <td>162.0</td> <td>0.585895</td> </tr> <tr> <th>Thriller</th> <td>42</td> <td>158.0</td> <td>0.571429</td> </tr> <tr> <th>Comedy</th> <td>41</td> <td>153.0</td> <td>0.553345</td> </tr> <tr> <th>Sci-Fi</th> <td>40</td> <td>148.5</td> <td>0.537071</td> </tr> <tr> <th>Crime</th> <td>21</td> <td>80.0</td> <td>0.289331</td> </tr> <tr> <th>Children</th> <td>19</td> <td>68.5</td> <td>0.247740</td> </tr> <tr> <th>Mystery</th> <td>18</td> <td>65.0</td> <td>0.235081</td> </tr> <tr> <th>Romance</th> <td>11</td> <td>43.5</td> <td>0.157324</td> </tr> <tr> <th>Animation</th> <td>10</td> <td>36.5</td> <td>0.132007</td> </tr> <tr> <th>War</th> <td>9</td> <td>33.0</td> <td>0.119349</td> </tr> <tr> <th>Western</th> <td>4</td> <td>13.5</td> <td>0.048825</td> </tr> <tr> <th>Musical</th> <td>3</td> <td>11.0</td> <td>0.039783</td> </tr> <tr> <th>IMAX</th> <td>2</td> <td>8.5</td> <td>0.030741</td> </tr> <tr> <th>(no genres listed)</th> <td>0</td> <td>0.0</td> <td>0.000000</td> </tr> <tr> <th>Documentary</th> <td>0</td> <td>0.0</td> <td>0.000000</td> </tr> <tr> <th>Film-Noir</th> <td>0</td> <td>0.0</td> <td>0.000000</td> </tr> </tbody> </table> </div> <p>These values are interesting and they may be used as an indication of how much a user prefers certain movie genres. This is the way that is taught in the video at the beginning of the page.</p> <p>However, because this method just sums all ratings the user has given to a collection of movies, it favors those genres in which the user has given more ratings, regardless of how low the ratings are.</p> <p>For example, if a user watches 9 action movies and gives a rating of 1 to all of them, the Action genre will have a weight of 9 in our preference vector:</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 + 1 = 9
</code></pre></div></div> <p>If that same user watches 2 musicals (I know, who likes musicals) but gives a rating of 4 to both of them, the Musical genre will have a weight of 8 in our fetaure vector, which is less than the weight of the Action genre.</p> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>4 + 4 = 8
</code></pre></div></div> <p>But we can clearly see that this user hates action movies but loves musicals!</p> <p>Our hypothesis is corroborated in the chart below, in which our sum of ratings for a genre grows as the user watches more movies.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_genre_preferences</span><span class="p">[[</span><span class="sh">"</span><span class="s">Movies</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">Sum of ratings</span><span class="sh">"</span><span class="p">]].</span><span class="nf">sort_values</span><span class="p">(</span><span class="sh">"</span><span class="s">Movies</span><span class="sh">"</span><span class="p">,</span> <span class="n">ascending</span><span class="o">=</span><span class="bp">False</span><span class="p">).</span><span class="n">plot</span><span class="p">.</span><span class="nf">barh</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;Axes: &gt;
</code></pre></div></div> <p><img src="/assets/img/content-based-filtering_21_1.png" alt="png"/></p> <p>By looking at the correlations between number of movies watched, sum of ratings and the normalized sum of ratings, we can see a pretty hgh positive correlation between all of them.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_genre_preferences</span><span class="p">.</span><span class="nf">corr</span><span class="p">()</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>Movies</th> <th>Sum of ratings</th> <th>Normalized sum of ratings</th> </tr> </thead> <tbody> <tr> <th>Movies</th> <td>1.000000</td> <td>0.999871</td> <td>0.999871</td> </tr> <tr> <th>Sum of ratings</th> <td>0.999871</td> <td>1.000000</td> <td>1.000000</td> </tr> <tr> <th>Normalized sum of ratings</th> <td>0.999871</td> <td>1.000000</td> <td>1.000000</td> </tr> </tbody> </table> </div> <p>One way we can mitigate this is by taking the <em>average</em> of the ratings a user gives to the movies of a particular genre as their preference for that genre. The table below is the one presented in step 3 of the example.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Normalized by movies in genre</span><span class="sh">"</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span>
  <span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Sum of ratings</span><span class="sh">"</span><span class="p">]</span> <span class="o">/</span> <span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Movies</span><span class="sh">"</span><span class="p">]</span>
<span class="p">).</span><span class="nf">fillna</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
<span class="n">user_genre_preferences</span> <span class="o">=</span> <span class="n">user_genre_preferences</span><span class="p">.</span><span class="nf">sort_values</span><span class="p">(</span><span class="sh">"</span><span class="s">Normalized by movies in genre</span><span class="sh">"</span><span class="p">,</span> <span class="n">ascending</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
<span class="n">user_genre_preferences</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>Movies</th> <th>Sum of ratings</th> <th>Normalized sum of ratings</th> <th>Normalized by movies in genre</th> </tr> </thead> <tbody> <tr> <th>IMAX</th> <td>2</td> <td>8.5</td> <td>0.030741</td> <td>4.250000</td> </tr> <tr> <th>Romance</th> <td>11</td> <td>43.5</td> <td>0.157324</td> <td>3.954545</td> </tr> <tr> <th>Crime</th> <td>21</td> <td>80.0</td> <td>0.289331</td> <td>3.809524</td> </tr> <tr> <th>Fantasy</th> <td>69</td> <td>261.5</td> <td>0.945750</td> <td>3.789855</td> </tr> <tr> <th>Adventure</th> <td>73</td> <td>276.5</td> <td>1.000000</td> <td>3.787671</td> </tr> <tr> <th>Drama</th> <td>43</td> <td>162.0</td> <td>0.585895</td> <td>3.767442</td> </tr> <tr> <th>Thriller</th> <td>42</td> <td>158.0</td> <td>0.571429</td> <td>3.761905</td> </tr> <tr> <th>Horror</th> <td>45</td> <td>168.5</td> <td>0.609403</td> <td>3.744444</td> </tr> <tr> <th>Comedy</th> <td>41</td> <td>153.0</td> <td>0.553345</td> <td>3.731707</td> </tr> <tr> <th>Action</th> <td>66</td> <td>246.0</td> <td>0.889693</td> <td>3.727273</td> </tr> <tr> <th>Sci-Fi</th> <td>40</td> <td>148.5</td> <td>0.537071</td> <td>3.712500</td> </tr> <tr> <th>War</th> <td>9</td> <td>33.0</td> <td>0.119349</td> <td>3.666667</td> </tr> <tr> <th>Musical</th> <td>3</td> <td>11.0</td> <td>0.039783</td> <td>3.666667</td> </tr> <tr> <th>Animation</th> <td>10</td> <td>36.5</td> <td>0.132007</td> <td>3.650000</td> </tr> <tr> <th>Mystery</th> <td>18</td> <td>65.0</td> <td>0.235081</td> <td>3.611111</td> </tr> <tr> <th>Children</th> <td>19</td> <td>68.5</td> <td>0.247740</td> <td>3.605263</td> </tr> <tr> <th>Western</th> <td>4</td> <td>13.5</td> <td>0.048825</td> <td>3.375000</td> </tr> <tr> <th>(no genres listed)</th> <td>0</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> </tr> <tr> <th>Documentary</th> <td>0</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> </tr> <tr> <th>Film-Noir</th> <td>0</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> </tr> </tbody> </table> </div> <p>If we now look at the correlation of the two feature sets implemented, we can see they are mostly uncorrelated, which means they are two completely different ways of expressing user preference.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">user_genre_preferences</span><span class="p">[[</span><span class="sh">"</span><span class="s">Normalized sum of ratings</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">Normalized by movies in genre</span><span class="sh">"</span><span class="p">]].</span><span class="nf">corr</span><span class="p">()</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>Normalized sum of ratings</th> <th>Normalized by movies in genre</th> </tr> </thead> <tbody> <tr> <th>Normalized sum of ratings</th> <td>1.000000</td> <td>0.451363</td> </tr> <tr> <th>Normalized by movies in genre</th> <td>0.451363</td> <td>1.000000</td> </tr> </tbody> </table> </div> <p>As you can see above, the second choice of features is very interesting. While before, we thought that the user enjoyed the Adventure, Fantasy Action and Horror genres, now we belive they enjoy IMAX movies, romances and crimes, even though they have watched less movies in that genre.</p> <p>One thing to note is that not all genres have inferred ratings for the given user. In cases where the user has not rated any movie of a particular genre, that genre will not have a rating. In our case, since MovieLens ratings start at 0.5, we use 0 to denote the absence of ratings.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">genres_with_ratings</span> <span class="o">=</span> <span class="p">(</span><span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Normalized by movies in genre</span><span class="sh">"</span><span class="p">]</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">).</span><span class="nf">sum</span><span class="p">()</span>
<span class="n">genres_without_ratings</span> <span class="o">=</span> <span class="nf">len</span><span class="p">(</span><span class="n">user_genre_preferences</span><span class="p">)</span> <span class="o">-</span> <span class="n">genres_with_ratings</span>

<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Total genres: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">user_genre_preferences</span><span class="p">)</span><span class="si">}</span><span class="se">\n</span><span class="s">Number of genres with ratings for user: </span><span class="si">{</span><span class="n">genres_with_ratings</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Total genres: 20
Number of genres with ratings for user: 17
</code></pre></div></div> <h2 id="inferring-preferences-for-unwatched-movies">Inferring preferences for unwatched movies</h2> <p>Now that we know how much the user prefers each genre, we will compute the ratings for movies that user has not watched yet.</p> <p>First, let’s get all the movies they have not watched from MovieLens. This would be the table from step 4 in the example.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># get the movies that the user has not seen
</span><span class="n">unwatched_movies</span> <span class="o">=</span> <span class="n">movies</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="o">~</span><span class="n">movies</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="nf">isin</span><span class="p">(</span><span class="n">user_ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">movieId</span><span class="sh">"</span><span class="p">])].</span><span class="nf">copy</span><span class="p">()</span>
<span class="n">unwatched_movies</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>title</th> <th>(no genres listed)</th> <th>Action</th> <th>Adventure</th> <th>Animation</th> <th>Children</th> <th>Comedy</th> <th>Crime</th> <th>Documentary</th> <th>Drama</th> <th>...</th> <th>Film-Noir</th> <th>Horror</th> <th>IMAX</th> <th>Musical</th> <th>Mystery</th> <th>Romance</th> <th>Sci-Fi</th> <th>Thriller</th> <th>War</th> <th>Western</th> </tr> <tr> <th>movieId</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>Toy Story (1995)</td> <td>0</td> <td>0</td> <td>1</td> <td>1</td> <td>1</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>3</th> <td>Grumpier Old Men (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>4</th> <td>Waiting to Exhale (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>1</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>5</th> <td>Father of the Bride Part II (1995)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>6</th> <td>Heat (1995)</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>131254</th> <td>Kein Bund für's Leben (2007)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>131256</th> <td>Feuer, Eis &amp; Dosenbier (2002)</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>131258</th> <td>The Pirates (2014)</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>131260</th> <td>Rentun Ruusu (2001)</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> <tr> <th>131262</th> <td>Innocence (2014)</td> <td>0</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>...</td> <td>0</td> <td>1</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> <td>0</td> </tr> </tbody> </table> <p>27103 rows × 21 columns</p> </div> <p>As an intermediate step, we will to propagate the user’s genre preferences to the preferences of these unwatched movies.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">movie_genre_ratings</span> <span class="o">=</span> <span class="n">unwatched_movies</span><span class="p">[</span><span class="n">genres</span><span class="p">].</span><span class="nf">multiply</span><span class="p">(</span><span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Normalized by movies in genre</span><span class="sh">"</span><span class="p">])</span>
<span class="n">movie_genre_ratings</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>(no genres listed)</th> <th>Action</th> <th>Adventure</th> <th>Animation</th> <th>Children</th> <th>Comedy</th> <th>Crime</th> <th>Documentary</th> <th>Drama</th> <th>Fantasy</th> <th>Film-Noir</th> <th>Horror</th> <th>IMAX</th> <th>Musical</th> <th>Mystery</th> <th>Romance</th> <th>Sci-Fi</th> <th>Thriller</th> <th>War</th> <th>Western</th> </tr> <tr> <th>movieId</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.000000</td> <td>3.787671</td> <td>3.65</td> <td>3.605263</td> <td>3.731707</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>3.789855</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>3</th> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>3.731707</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>3.954545</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>4</th> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>3.731707</td> <td>0.000000</td> <td>0.0</td> <td>3.767442</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>3.954545</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>5</th> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>3.731707</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>6</th> <td>0.0</td> <td>3.727273</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>0.000000</td> <td>3.809524</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>3.761905</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> <td>...</td> </tr> <tr> <th>131254</th> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>3.731707</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>131256</th> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>3.731707</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>131258</th> <td>0.0</td> <td>0.000000</td> <td>3.787671</td> <td>0.00</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>131260</th> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.00</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> <tr> <th>131262</th> <td>0.0</td> <td>0.000000</td> <td>3.787671</td> <td>0.00</td> <td>0.000000</td> <td>0.000000</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>3.789855</td> <td>0.0</td> <td>3.744444</td> <td>0.0</td> <td>0.0</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.000000</td> <td>0.0</td> <td>0.0</td> </tr> </tbody> </table> <p>27103 rows × 20 columns</p> </div> <p>We then sum these preferences <em>by movie</em> and divide by the number of genres each movie has, to get the user preferences for each unwatched movie.</p> <p>If we sort the movies by these inferred preferences, we get a list in descending order of the movies user 1 has not seen but might enjoy, based on their genres and the ratings user 1 has given to the movies they have seen.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">denominator</span> <span class="o">=</span> <span class="n">movie_genre_ratings</span> <span class="o">!=</span> <span class="mi">0</span>
<span class="n">numerator</span> <span class="o">=</span> <span class="n">movie_genre_ratings</span><span class="p">.</span><span class="nf">sum</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">content_based_ratings</span> <span class="o">=</span> <span class="n">numerator</span> <span class="o">/</span> <span class="n">denominator</span><span class="p">.</span><span class="nf">sum</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">unwatched_movies</span><span class="p">[</span><span class="sh">"</span><span class="s">content_based_rating</span><span class="sh">"</span><span class="p">]</span> <span class="o">=</span> <span class="n">content_based_ratings</span>
<span class="n">unwatched_movies</span><span class="p">[[</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">content_based_rating</span><span class="sh">"</span><span class="p">]].</span><span class="nf">sort_values</span><span class="p">(</span><span class="sh">"</span><span class="s">content_based_rating</span><span class="sh">"</span><span class="p">,</span> <span class="n">ascending</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>title</th> <th>content_based_rating</th> </tr> <tr> <th>movieId</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>4858</th> <td>Hail Columbia! (1982)</td> <td>4.25</td> </tr> <tr> <th>4861</th> <td>Mission to Mir (1997)</td> <td>4.25</td> </tr> <tr> <th>4459</th> <td>Alaska: Spirit of the Wild (1997)</td> <td>4.25</td> </tr> <tr> <th>4460</th> <td>Encounter in the Third Dimension (1999)</td> <td>4.25</td> </tr> <tr> <th>4461</th> <td>Siegfried &amp; Roy: The Magic Box (1999)</td> <td>4.25</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> </tr> <tr> <th>131108</th> <td>The Fearless Four (1997)</td> <td>NaN</td> </tr> <tr> <th>131110</th> <td>A House of Secrets: Exploring 'Dragonwyck' (2008)</td> <td>NaN</td> </tr> <tr> <th>131166</th> <td>WWII IN HD (2009)</td> <td>NaN</td> </tr> <tr> <th>131172</th> <td>Closed Curtain (2013)</td> <td>NaN</td> </tr> <tr> <th>131260</th> <td>Rentun Ruusu (2001)</td> <td>NaN</td> </tr> </tbody> </table> <p>27103 rows × 2 columns</p> </div> <p>Notice that this step already takes care of situations in which a movie belongs to a certain genre but the user has no rating for that genre. For example, this user has a rating for the Action gente, but not for Western. If movie belongs to both genres, the average will be taken only over one genre, since <code class="language-plaintext highlighter-rouge">content_based_ratings.loc[movie_id, "&lt;genre without user rating&gt;"]</code> will be equal to 0 and ignored when accounting for our denominator.</p> <p>We can also compute the alternate user-genre preferences, using normalized sums of ratings, which are highly correlated with the number of movies watched in each genre. You can see we get a different list of movies, although some movies remain in the list and the first movie is the same.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">content_based_ratings</span> <span class="o">=</span> <span class="n">unwatched_movies</span><span class="p">[</span><span class="n">genres</span><span class="p">].</span><span class="nf">multiply</span><span class="p">(</span><span class="n">user_genre_preferences</span><span class="p">[</span><span class="sh">"</span><span class="s">Normalized sum of ratings</span><span class="sh">"</span><span class="p">])</span>
<span class="n">content_based_ratings</span> <span class="o">=</span> <span class="n">content_based_ratings</span><span class="p">.</span><span class="nf">sum</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">unwatched_movies</span><span class="p">[</span><span class="sh">"</span><span class="s">content_based_rating2</span><span class="sh">"</span><span class="p">]</span> <span class="o">=</span> <span class="n">content_based_ratings</span>
<span class="n">unwatched_movies</span><span class="p">[[</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">content_based_rating2</span><span class="sh">"</span><span class="p">]].</span><span class="nf">sort_values</span><span class="p">(</span><span class="sh">"</span><span class="s">content_based_rating2</span><span class="sh">"</span><span class="p">,</span> <span class="n">ascending</span><span class="o">=</span><span class="bp">False</span><span class="p">)</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>title</th> <th>content_based_rating2</th> </tr> <tr> <th>movieId</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>81132</th> <td>Rubber (2010)</td> <td>4.783002</td> </tr> <tr> <th>49593</th> <td>She (1965)</td> <td>4.725136</td> </tr> <tr> <th>5018</th> <td>Motorama (1991)</td> <td>4.717902</td> </tr> <tr> <th>71999</th> <td>Aelita: The Queen of Mars (Aelita) (1924)</td> <td>4.687161</td> </tr> <tr> <th>72165</th> <td>Cirque du Freak: The Vampire's Assistant (2009)</td> <td>4.569620</td> </tr> <tr> <th>...</th> <td>...</td> <td>...</td> </tr> <tr> <th>100246</th> <td>Pretty Sweet (2012)</td> <td>0.000000</td> </tr> <tr> <th>99</th> <td>Heidi Fleiss: Hollywood Madam (1995)</td> <td>0.000000</td> </tr> <tr> <th>100266</th> <td>Day Is Done (2011)</td> <td>0.000000</td> </tr> <tr> <th>100287</th> <td>Head Games (2012)</td> <td>0.000000</td> </tr> <tr> <th>96842</th> <td>Behind the Burly Q: The Story of Burlesque in ...</td> <td>0.000000</td> </tr> </tbody> </table> <p>27103 rows × 2 columns</p> </div> <p>Both of the tables above are equivalent to the table presented in step 5 of the example.</p> <h2 id="discussion">Discussion</h2> <p>One disadvantage of content-based filtering is that we can only recommend an item for a user if that user has rated at least one other item that contains at least one feature in common with the item in question.</p> <p>In our case, we can only recommend movies to a user if that movie contains at least one genre in common with another movie that the user has already rated.</p> <p>The fewer features an unrated item has with rated ones, the less granular its inferred rating will be.</p> <p>The diagrams below illustrate a situation in which a user has ratings for 17 genres, computed from the ratings of movies that contain those genres. In the first example, a movie with 5 genres has 2 genres in common with rated genres for the user, so we can compute an inferred rating for the movie.</p> <p>In the second example, a movie with 5 genres has 0 genres in common with the rated genres for the user, so we cannot directly compute an inferred rating for it.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">matplotlib_venn</span> <span class="kn">import</span> <span class="n">venn2</span>
<span class="kn">import</span> <span class="n">matplotlib.pyplot</span> <span class="k">as</span> <span class="n">plt</span>

<span class="n">movie_genres_count</span> <span class="o">=</span> <span class="mi">5</span>
<span class="n">intersection</span> <span class="o">=</span> <span class="mi">2</span>
<span class="n">set1</span> <span class="o">=</span> <span class="n">genres_with_ratings</span> <span class="o">-</span> <span class="n">intersection</span>
<span class="n">set2</span> <span class="o">=</span> <span class="n">movie_genres_count</span> <span class="o">-</span> <span class="n">intersection</span>
<span class="nf">venn2</span><span class="p">(</span><span class="n">subsets</span><span class="o">=</span><span class="p">(</span><span class="n">set1</span><span class="p">,</span> <span class="n">set2</span><span class="p">,</span> <span class="n">intersection</span><span class="p">),</span> <span class="n">set_labels</span><span class="o">=</span><span class="p">(</span><span class="sh">"</span><span class="s">Features with</span><span class="se">\n</span><span class="s">user ratings</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">Movie features</span><span class="sh">"</span><span class="p">),</span> <span class="n">alpha</span><span class="o">=</span><span class="mf">0.5</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">title</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Movie that can be rated based on </span><span class="si">{</span><span class="n">intersection</span><span class="si">}</span><span class="s"> features</span><span class="sh">"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">show</span><span class="p">()</span>
<span class="nf">venn2</span><span class="p">(</span>
  <span class="n">subsets</span><span class="o">=</span><span class="p">(</span><span class="n">genres_with_ratings</span><span class="p">,</span> <span class="n">movie_genres_count</span><span class="p">,</span> <span class="mi">0</span><span class="p">),</span>
  <span class="n">set_labels</span><span class="o">=</span><span class="p">(</span><span class="sh">"</span><span class="s">Features with</span><span class="se">\n</span><span class="s">user ratings</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">Movie features</span><span class="sh">"</span><span class="p">),</span>
  <span class="n">alpha</span><span class="o">=</span><span class="mf">0.5</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">title</span><span class="p">(</span><span class="sh">"</span><span class="s">Movie that cannot be rated</span><span class="sh">"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">show</span><span class="p">()</span>

</code></pre></div></div> <p><img src="/assets/img/content-based-filtering_39_0.png" alt="png"/></p> <p><img src="/assets/img/content-based-filtering_39_1.png" alt="png"/></p> <p>Because in our example, this user has watched over 100 movies, we are able to recommend over 90% of unwatched movies to them.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">movies_with_inferred_ratings</span> <span class="o">=</span> <span class="p">(</span><span class="o">~</span><span class="n">unwatched_movies</span><span class="p">[</span><span class="sh">"</span><span class="s">content_based_rating</span><span class="sh">"</span><span class="p">].</span><span class="nf">isna</span><span class="p">()).</span><span class="nf">sum</span><span class="p">()</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Number of unwatched movies: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">unwatched_movies</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Number of unwatched movies with inferred ratings: </span><span class="si">{</span><span class="n">movies_with_inferred_ratings</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span>
  <span class="sa">f</span><span class="sh">"</span><span class="s">Percentage of unwatched movies with inferred ratings: </span><span class="si">{</span><span class="n">movies_with_inferred_ratings</span> <span class="o">/</span> <span class="nf">len</span><span class="p">(</span><span class="n">unwatched_movies</span><span class="p">)</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="o">%</span><span class="si">}</span><span class="sh">"</span>
<span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Number of unwatched movies: 27103
Number of unwatched movies with inferred ratings: 24901
Percentage of unwatched movies with inferred ratings: 91.88%
</code></pre></div></div> <p>Another disadvantage is that, depending on the number of features and technique employed in computing inferred ratings, the granularity of ratings can be very poor.</p> <p>In our case, although we inferred ratings for over 24,000 movies, over 50% of them received one of 10 ratings.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">inferred_ratings_count</span> <span class="o">=</span> <span class="n">unwatched_movies</span><span class="p">[</span><span class="sh">"</span><span class="s">content_based_rating</span><span class="sh">"</span><span class="p">].</span><span class="nf">value_counts</span><span class="p">()</span>
<span class="n">topk</span> <span class="o">=</span> <span class="mi">10</span>

<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Unique inferred ratings: </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">inferred_ratings_count</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
<span class="nf">print</span><span class="p">(</span>
  <span class="sa">f</span><span class="sh">"</span><span class="s">Percentage of unwatched movies in the top </span><span class="si">{</span><span class="n">topk</span><span class="si">}</span><span class="s"> inferred ratings: </span><span class="si">{</span><span class="p">(</span><span class="n">inferred_ratings_count</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="si">:</span><span class="n">topk</span><span class="p">].</span><span class="nf">sum</span><span class="p">()</span> <span class="o">/</span> <span class="n">movies_with_inferred_ratings</span><span class="p">)</span><span class="si">:</span><span class="p">.</span><span class="mi">2</span><span class="o">%</span><span class="si">}</span><span class="sh">"</span>
<span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Unique inferred ratings: 1182
Percentage of unwatched movies in the top 10 inferred ratings: 51.42%
</code></pre></div></div> <p>This happens because, while we have \(n\) total features to represent user taste and items (the movie genres), the current user only has ratings for a subset \(m \leq n\) of the features.</p> <p>Using a simple average over genre ratings, a movie’s inferred rating can only come from one of \(2^m-1\) possible values.</p> <p>If the number of genres of the movie is known, say \(k\), then this value is restricted to \(\binom{m}{k}\), assuming that each possible rating is different.</p> <p>The table below shows the number of possible ratings a movie may have, given the number of genres it has.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">scipy.special</span> <span class="kn">import</span> <span class="n">comb</span>

<span class="n">genres_count</span> <span class="o">=</span> <span class="n">unwatched_movies</span><span class="p">[</span><span class="n">genres</span><span class="p">].</span><span class="nf">sum</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">).</span><span class="nf">value_counts</span><span class="p">()</span>
<span class="n">possible_ratings</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="nc">DataFrame</span><span class="p">(</span>
  <span class="n">index</span><span class="o">=</span><span class="n">genres_count</span><span class="p">.</span><span class="n">index</span><span class="p">,</span>
  <span class="n">data</span><span class="o">=</span><span class="p">{</span>
    <span class="sh">"</span><span class="s">Number of Movies</span><span class="sh">"</span><span class="p">:</span> <span class="n">genres_count</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">Possible ratings</span><span class="sh">"</span><span class="p">:</span> <span class="p">[</span><span class="nf">comb</span><span class="p">(</span><span class="n">genres_with_ratings</span><span class="p">,</span> <span class="n">i</span><span class="p">)</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">genres_count</span><span class="p">.</span><span class="n">index</span><span class="p">],</span>
  <span class="p">},</span>
<span class="p">)</span>
<span class="n">possible_ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">Movies per possible rating</span><span class="sh">"</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span>
  <span class="n">possible_ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">Number of Movies</span><span class="sh">"</span><span class="p">]</span> <span class="o">/</span> <span class="n">possible_ratings</span><span class="p">[</span><span class="sh">"</span><span class="s">Possible ratings</span><span class="sh">"</span><span class="p">]</span>
<span class="p">)</span>
<span class="n">possible_ratings</span><span class="p">.</span><span class="n">index</span><span class="p">.</span><span class="n">name</span> <span class="o">=</span> <span class="sh">"</span><span class="s">Number of genres</span><span class="sh">"</span>
<span class="n">possible_ratings</span>
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>Number of Movies</th> <th>Possible ratings</th> <th>Movies per possible rating</th> </tr> <tr> <th>Number of genres</th> <th></th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>1</th> <td>10816</td> <td>17.0</td> <td>636.235294</td> </tr> <tr> <th>2</th> <td>8766</td> <td>136.0</td> <td>64.455882</td> </tr> <tr> <th>3</th> <td>5260</td> <td>680.0</td> <td>7.735294</td> </tr> <tr> <th>4</th> <td>1685</td> <td>2380.0</td> <td>0.707983</td> </tr> <tr> <th>5</th> <td>468</td> <td>6188.0</td> <td>0.075630</td> </tr> <tr> <th>6</th> <td>82</td> <td>12376.0</td> <td>0.006626</td> </tr> <tr> <th>7</th> <td>20</td> <td>19448.0</td> <td>0.001028</td> </tr> <tr> <th>8</th> <td>5</td> <td>24310.0</td> <td>0.000206</td> </tr> <tr> <th>10</th> <td>1</td> <td>19448.0</td> <td>0.000051</td> </tr> </tbody> </table> </div> <h2 id="conclusion">Conclusion</h2> <p>In this project, we have built a movie recommendation system based on content-based filtering.</p> <p>We went through the theory of content-based filtering as well as an example, then used a publicly available dataset to implement the system. We compared two ways of building user features and saw one of the downsides of content-based filtering, which is the inability of recommending new items to a user if those items don’t have intersecting features with the items the user has already rated.</p> <p>See you guys next time!</p>]]></content><author><name></name></author><category term="recommendations-systems"/><category term="python"/><category term="open-source"/><category term="recommendation-systems"/><category term="content-based-systems"/><category term="kaggle"/><summary type="html"><![CDATA[Introduction]]></summary></entry><entry><title type="html">Building text-based movie recommendation systems using the TMDB dataset</title><link href="https://douglasrizzo.github.io/blog/2025/03/text-based-movie-recs/" rel="alternate" type="text/html" title="Building text-based movie recommendation systems using the TMDB dataset"/><published>2025-03-11T00:00:00+00:00</published><updated>2025-03-11T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2025/03/text-based-movie-recs</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2025/03/text-based-movie-recs/"><![CDATA[<h2 id="introduction">Introduction</h2> <p>In this project, we will implement a text-based recommendation system for movies.</p> <p>The idea is that our recommendation engine provide a user with recommendations of new movies based on how similar the title of a movie the user has already watched is to the the titles of other movies in the database.</p> <p>We will implement two different ways of making a movie recommendation system and one way of making a movie reranking system, based solely on the title and overview of a movie a hypothetical user might enjoy. The techniques we will employ are TF-IDF and bi-encoders. The movie reranker wil be implemented using a cross-encoder.</p> <h3 id="resources">Resources</h3> <ul> <li>GitHub repository containing this project and a list of dependencies <a href="https://github.com/douglasrizzo/recsys-movies/blob/master/src/text-based-movie-recs.ipynb"><img src="https://img.shields.io/badge/github-%23121011.svg?style=for-the-badge&amp;logo=github&amp;logoColor=white" alt="GitHub"/></a></li> <li>Open this page in Google Colab <a href="https://colab.research.google.com/github/douglasrizzo/recsys-movies/blob/master/src/text-based-movie-recs.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open in Colab"/></a></li> <li><a href="https://douglasrizzo.com.br/blog/2025/03/text-based-movie-recs/">Read the contents in my website</a></li> </ul> <p>The following links instructed me on how to access a movie dataset and which libraries to use, especially the part on TF-IDF which inspired me to implement the other methods. You can check them out for more examples.</p> <ul> <li><a href="https://www.datacamp.com/tutorial/recommender-systems-python">Beginner Tutorial: Recommender Systems in Python</a></li> <li><a href="https://www.kaggle.com/code/ibtesama/getting-started-with-a-movie-recommendation-system">Getting Started with a Movie Recommendation System</a></li> </ul> <h2 id="downloading-the-dataset">Downloading the dataset</h2> <p>For this exercise, we will use The Movies Database (TMDb), a dataset containing movies and their features. It does not contain user-related information, such as how many people watched a movie or movie ratings. We will use <a href="https://www.kaggle.com/datasets/asaniczka/tmdb-movies-dataset-2023-930k-movies">a version provided by Kaggle user asaniczka</a>, which is constantly updated.</p> <p>To download it, we will use the Python package <code class="language-plaintext highlighter-rouge">kagglehub</code>.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">pathlib</span> <span class="k">as</span> <span class="n">pl</span>

<span class="kn">import</span> <span class="n">kagglehub</span>
<span class="kn">import</span> <span class="n">pandas</span> <span class="k">as</span> <span class="n">pd</span>

<span class="n">tmdb_path</span> <span class="o">=</span> <span class="nf">next</span><span class="p">(</span>
  <span class="nf">iter</span><span class="p">(</span><span class="n">pl</span><span class="p">.</span><span class="nc">Path</span><span class="p">(</span><span class="n">kagglehub</span><span class="p">.</span><span class="nf">dataset_download</span><span class="p">(</span><span class="sh">"</span><span class="s">asaniczka/tmdb-movies-dataset-2023-930k-movies</span><span class="sh">"</span><span class="p">)).</span><span class="nf">glob</span><span class="p">(</span><span class="sh">"</span><span class="s">*.csv</span><span class="sh">"</span><span class="p">))</span>
<span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Resuming download from 179306496 bytes (41578107 bytes left)...
Resuming download from https://www.kaggle.com/api/v1/datasets/download/asaniczka/tmdb-movies-dataset-2023-930k-movies?dataset_version_number=506 (179306496/220884603) bytes left.


100%|██████████| 211M/211M [00:08&lt;00:00, 4.74MB/s]

Extracting files...
</code></pre></div></div> <p>You can see in the cells below a sample of the data we will use. At the time of this project, there were over 940,000 movies available on the dataset.</p> <p>We are only interested in the title and overview of the movies, so we will drop the other columns.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">movie_metadata</span> <span class="o">=</span> <span class="n">pd</span><span class="p">.</span><span class="nf">read_csv</span><span class="p">(</span><span class="n">tmdb_path</span><span class="p">,</span> <span class="n">index_col</span><span class="o">=</span><span class="sh">"</span><span class="s">id</span><span class="sh">"</span><span class="p">)</span>
<span class="n">movie_metadata</span> <span class="o">=</span> <span class="n">movie_metadata</span><span class="p">.</span><span class="n">loc</span><span class="p">[</span><span class="o">~</span><span class="n">movie_metadata</span><span class="p">[</span><span class="sh">"</span><span class="s">overview</span><span class="sh">"</span><span class="p">].</span><span class="nf">isna</span><span class="p">(),</span> <span class="p">[</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">overview</span><span class="sh">"</span><span class="p">]]</span>
<span class="nf">print</span><span class="p">(</span><span class="n">movie_metadata</span><span class="p">.</span><span class="n">shape</span><span class="p">)</span>
<span class="n">movie_metadata</span><span class="p">.</span><span class="nf">head</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(941184, 2)
</code></pre></div></div> <div> <table> <thead> <tr style="text-align: right;"> <th></th> <th>title</th> <th>overview</th> </tr> <tr> <th>id</th> <th></th> <th></th> </tr> </thead> <tbody> <tr> <th>27205</th> <td>Inception</td> <td>Cobb, a skilled thief who commits corporate es...</td> </tr> <tr> <th>157336</th> <td>Interstellar</td> <td>The adventures of a group of explorers who mak...</td> </tr> <tr> <th>155</th> <td>The Dark Knight</td> <td>Batman raises the stakes in his war on crime. ...</td> </tr> <tr> <th>19995</th> <td>Avatar</td> <td>In the 22nd century, a paraplegic Marine is di...</td> </tr> <tr> <th>24428</th> <td>The Avengers</td> <td>When an unexpected enemy emerges and threatens...</td> </tr> </tbody> </table> </div> <p>For the purposes of our project, we will only work with a sample of 10,000 movies, since the machine learning methods we will employ can be compute or memory intensive.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">movie_metadata</span> <span class="o">=</span> <span class="n">movie_metadata</span><span class="p">.</span><span class="nf">sample</span><span class="p">(</span><span class="n">n</span><span class="o">=</span><span class="mi">10000</span><span class="p">,</span> <span class="n">random_state</span><span class="o">=</span><span class="mi">42</span><span class="p">).</span><span class="nf">sort_index</span><span class="p">()</span>
</code></pre></div></div> <h2 id="title-based-recommendations-using-tf-idf">Title-based recommendations using TF-IDF</h2> <p>The first technique we will implement is term frequency-inverse document frequency, or TF-IDF for short. It is an information retrieval technique in which a term \(t\) inside a document \(d\) is given a weight based on how frequently it appears in that document, compared to how frequently it appears in all other documents of our corpus. The intuitition is that:</p> <ul> <li>if \(t\) is very common in \(d\), it might be relevant to the context of \(d\). This value is called the <strong>term frequency</strong>.</li> <li>if \(t\) does not appear as frequently in other documents, it might be very specific to the context of \(d\) <em>in particular</em>, so it might be very relevant. This term is called the <strong>inverse document frequency</strong>.</li> </ul> <p>However, if \(t\) also appears very frequently in other documents, it might not be a very informative term. Think about the word <em>“the”</em>, which may appear very frequently in a single document, but we can also find it in many other documents of a corpus.</p> <h3 id="term-frequency">Term frequency</h3> <p>Term frequency is the relative frequency of a term within a document:</p> \[tf(t, d) = \frac{f(t, d)}{\sum_{t' \in d} f(t', d)}\] <p>Where \(t\) is a term, \(d\) is a document, \(t'\) are the other terms in \(d\) which are not \(t\) and the function \(f(t, d)\) depicts the raw number of times \(t\) appears in \(d\).</p> <p>It can be loosely interpreted as:</p> \[tf(t, d) = \frac{\text{number of times } t \text{ appears in } d}{\text{sum of the number of times all other terms in } d \text{ also appear in } d}\] <h3 id="inverse-document-frequency">Inverse document frequency</h3> <p>Inverse document frequency is a measure of how informative a given term \(t\) is within the corpus \(D\).</p> <p>If we define:</p> <ul> <li>\(\mid D \mid\) as the number of documents in the corpus \(D\) (the cardinality of set \(D\)) and</li> <li>\(D' = \{d \in D:t \in d\}\) as the set of documents in \(D\) that also contain term \(t\)</li> </ul> <p>We can then compute the inverse document frequency \(idf\) of a term \(t\) in corpus \(D\) as:</p> \[idf(t, D) = \log \frac{ \mid D \mid }{ \mid D' \mid }\] <p>Where once again \(\mid \cdot \mid\) is the notation for the cardinality of a set.</p> <p>It can be interpreted as:</p> \[idf(t, D) = \log \frac{\text{total number of documents}}{\text{number of documents in which } t \text{ appears}}\] <p>The logarithm is used to balance the magnitude of the \(idf\) function for terms that appear in too few document <em>vs</em> those that appear in too many documents. You can view a chart of the \(idf\) function for a term that appear in all documents \((\frac{ \mid D \mid }{ \mid D' \mid } = 1)\) all the way to a term that appears in 1% of the documents in a corpus \((\frac{ \mid D \mid }{ \mid D' \mid } = 100)\).</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">matplotlib.pyplot</span> <span class="k">as</span> <span class="n">plt</span>
<span class="kn">import</span> <span class="n">numpy</span> <span class="k">as</span> <span class="n">np</span>

<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">arange</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">101</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="p">.</span><span class="nf">log</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">plot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span> <span class="n">y</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">xlabel</span><span class="p">(</span><span class="sh">"</span><span class="s">$$</span><span class="se">\\</span><span class="s">frac{ \mid D \mid }{|D</span><span class="sh">'</span><span class="s">|}$$</span><span class="sh">"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">ylabel</span><span class="p">(</span><span class="sh">"</span><span class="s">$$</span><span class="se">\\</span><span class="s">log(</span><span class="se">\\</span><span class="s">frac{|D|}{|D</span><span class="sh">'</span><span class="s">|})$$</span><span class="sh">"</span><span class="p">)</span>
<span class="n">plt</span><span class="p">.</span><span class="nf">show</span><span class="p">()</span>
</code></pre></div></div> <p><img src="/assets/img/idf_chart.png" alt="png"/></p> <p>Finally, we can compute the \(tfidf\) value for a term \(t\) inside a document \(d\) relative to a corpus \(D\) as:</p> \[tfidf(t, d, D) = tf(t, d) \cdot idf(t,D)\] <h3 id="interpreting-tf-idf">Interpreting TF-IDF</h3> <ul> <li>If the relative frequency of \(t\) inside \(d\) is high, then \(tf(t, d)\) will be high</li> <li>If \(t\)’s frequency inside all other documents in \(D\) is small, them \(idf(t, D)\) will be high</li> <li>This makes \(tfidf(t, d, D)\) high, meaning that the relevance of \(t\) in \(d\) compared to the other documents in \(D\) must be high</li> </ul> <h3 id="implementing-the-recommendation-engine">Implementing the recommendation engine</h3> <p>For this exercise, we will use scikit-learn to compute the \(tfidf\) values of all words in all 10,000 titles of our movies. This will generate a \(\mid T \mid \times \mid D \mid\) matrix whose size you can see below.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">sklearn.feature_extraction.text</span> <span class="kn">import</span> <span class="n">TfidfVectorizer</span>

<span class="n">tfidf</span> <span class="o">=</span> <span class="nc">TfidfVectorizer</span><span class="p">(</span><span class="n">stop_words</span><span class="o">=</span><span class="sh">"</span><span class="s">english</span><span class="sh">"</span><span class="p">)</span>
<span class="n">tfidf_matrix</span> <span class="o">=</span> <span class="n">tfidf</span><span class="p">.</span><span class="nf">fit_transform</span><span class="p">(</span><span class="n">movie_metadata</span><span class="p">[</span><span class="sh">"</span><span class="s">overview</span><span class="sh">"</span><span class="p">])</span>
<span class="nf">print</span><span class="p">(</span><span class="n">tfidf_matrix</span><span class="p">.</span><span class="n">shape</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(10000, 35994)
</code></pre></div></div> <h3 id="computing-similarities">Computing similarities</h3> <p>In our example, each document \(d\) is a single movie title and the corresponding vector in the TF-IDF matrix can be considered a numerical feature vector representing the movie title. We can compute how similar these feature vectorsamongst each other by using similarity metrics such as the <a href="https://en.wikipedia.org/wiki/Cosine_similarity">cosine similarity</a>, which we will employ below.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">cosine_sim</span> <span class="o">=</span> <span class="p">(</span><span class="n">tfidf_matrix</span> <span class="o">*</span> <span class="n">tfidf_matrix</span><span class="p">.</span><span class="n">T</span><span class="p">).</span><span class="nf">toarray</span><span class="p">()</span>
<span class="n">cosine_sim</span><span class="p">.</span><span class="n">shape</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(10000, 10000)
</code></pre></div></div> <p>This gives us back a matrix of similarities \(S\) in which \(S_{x,y}\) denote how similar the titles of movies in position \(x\) and \(y\) are. This is a symmetric matrix \((S_{x,y} = S_{y,x})\) in which all elements in the diagonal are equal to 1 \((S_{x,x} = 1)\).</p> <h3 id="recovering-movies-with-similar-titles">Recovering movies with similar titles</h3> <p>Now, we can select a random movie from our dataset and retrieve the other movies whose titles are similar to it, according to how similar their \(tfidf\) vectors are under the cosine similarity. The function below does that.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">operator</span>


<span class="k">def</span> <span class="nf">get_recommendations</span><span class="p">(</span><span class="n">idx</span><span class="p">,</span> <span class="n">sim_matrix</span><span class="p">):</span>
  <span class="n">movie_title</span> <span class="o">=</span> <span class="n">movie_metadata</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">idx</span><span class="p">][</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">]</span>
  <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Top recommendations for </span><span class="si">{</span><span class="n">movie_title</span><span class="si">}</span><span class="s">:</span><span class="sh">"</span><span class="p">)</span>
  <span class="n">sim_scores</span> <span class="o">=</span> <span class="nf">list</span><span class="p">(</span><span class="nf">enumerate</span><span class="p">(</span><span class="n">sim_matrix</span><span class="p">[</span><span class="n">idx</span><span class="p">]))</span>
  <span class="n">sim_scores</span> <span class="o">=</span> <span class="nf">sorted</span><span class="p">(</span><span class="n">sim_scores</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">operator</span><span class="p">.</span><span class="nf">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
  <span class="n">sim_scores</span> <span class="o">=</span> <span class="n">sim_scores</span><span class="p">[</span><span class="mi">1</span><span class="p">:</span><span class="mi">31</span><span class="p">]</span>
  <span class="n">movie_indices</span> <span class="o">=</span> <span class="p">[</span><span class="n">i</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">sim_scores</span><span class="p">]</span>
  <span class="k">return</span> <span class="n">movie_metadata</span><span class="p">[</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">].</span><span class="n">iloc</span><span class="p">[</span><span class="n">movie_indices</span><span class="p">]</span>
</code></pre></div></div> <p>We can see from in the results below the subset of most similar items to the one whose title is listed. You can judge for yourself whether they are actually similar, but the usefulness of a recommendation engine that searches for movies with similar titles is questionable.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nf">print</span><span class="p">(</span><span class="nf">get_recommendations</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span> <span class="n">cosine_sim</span><span class="p">))</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Top recommendations for Megacities:
id
164535         Trilogia - Il pensiero, lo sguardo, la parola
410067                     Pasolini and the Form of the City
516906                                      Die Republikaner
529837        Villa Air Bel. Varian Fry in Marseille 1940/41
558799                  Bella Italia - Zuflucht auf Widerruf
620839                                        Leszármazottak
1368150                                             Solitudo
1170754                 ...bis zum Bundesverfassungsgericht!
1408577                        In the Mix with Jabaar Edmond
911602                                           Window Feel
428078                                        Mortal Engines
123022                                       Whispering Hope
1144526    Bubble &amp; Squeak murder:  The Killing of David ...
1365387    Freedom Film Series: A Higher Law: The Oberlin...
723978                                     Tierra de mujeres
646953                                         Fleischwochen
1325493                                      Songs in Greece
1230804                                       Experimentally
619614                   Blood Loss: Survival of the Fittest
851645                                         Telos or Bust
1162956                                       Memento Vivere
1208493                                      Floral Symphony
1364447                                             Parkside
1153924                             Soy del tiempo de Gardel
924502                                                 Norma
610049                                       The Narrow Path
235194                                My True Love, My Wound
283054                                           Naked World
319215                         The Hidden Side of the Bottom
617036                             Seven Islands and a Metro
Name: title, dtype: object
</code></pre></div></div> <h2 id="movie-recommendations-based-on-sentence-embeddings">Movie recommendations based on sentence embeddings</h2> <p>In this next part of the project, we will expand our text-based recommendation engine by incorporating information about the movie overview into our similarity search.</p> <p>When doing this, we face a fundamental problem: the size of our vocabulary (the set of all individual terms in all documents of our corpus) is very large, which may make computing tfidf prohibitive. Also, the feature vectors for all our moview would all be sparse as most movie overviews do not contain many words from our vocabulary.</p> <p>To combat this, we can use an encoder-only transformer architecture, such as BERT and its variants, trained as a bi-encoder, to encode our arbitrarily long texts into fixed-size embeddings.</p> <h3 id="encoder-only-transformers">Encoder-only transformers</h3> <p>These are neural network architectures whose only purpose is to transform text data into embeddings. Unlike <em>causal language models</em> such as GPT, who are trained for next-token prediction and thus do not always have access to the full context of the text, encoder-only models (also called <em>masked language models</em>) have access to the full context of the text in order to generate its embedding.</p> <p>These models can be trained for a multitude of tasks, such as text classification, sentiment analysis and even masked language modeling. After training ends, these models are able to generate fixed size text embeddings.</p> <pre><code class="language-mermaid">graph BT
    subgraph Causal language modeling
        direction BT
        CLM[GPT]
        You2(You) --&gt; CLM
        must2(must) --&gt; CLM
        construct --&gt; CLM
        additional2(additional) --&gt; CLM
        CLM --&gt; pylons@{ shape: stadium }

        style CLM fill:#248315
    end

    subgraph Masked language modeling
        direction BT
        MLM[BERT]
        You1(You) --&gt; MLM
        must1(must) --&gt; MLM
        MASK1["&lt;font color='red'&gt;&amp;ltMASK&amp;gt&lt;/font&gt;"] --&gt; MLM
        additional1(additional) --&gt; MLM
        pylons1(pylons) --&gt; MLM
        MLM --&gt; additional@{ shape: stadium }

        style MLM fill:#248315
    end
</code></pre> <h3 id="bi-encoders">Bi-encoders</h3> <p>A bi-encoder is a special kind of encoder-only transformer which is trained on labeled data, containing pairs of texts accompanied by a similarity score as in the example below.</p> <table> <thead> <tr> <th>Sentence 1</th> <th>Sentence 2</th> <th>Similarity</th> </tr> </thead> <tbody> <tr> <td>I love you</td> <td>I love my cat</td> <td>0.82</td> </tr> <tr> <td>I love you</td> <td>You must construct additional pylons</td> <td>0.04</td> </tr> </tbody> </table> <p>One example dataset is the Semantic Textual Similarity Benchmark (STSB). <a href="https://huggingface.co/datasets/sentence-transformers/stsb">[Hugging Face Hub]</a> <a href="https://paperswithcode.com/dataset/sts-benchmark">[Papers with Code]</a></p> <p>The bi-encoder is then trained in a siamese fashion so that the embeddings of texts with high similarity are also similar amongst themselves, whereas the embeddings of texts with low similarity have embeddings further away from each other. During inference, the model is individually applied to two pieces of texts and their output embeddings can be compared using cosine similarity.</p> <pre><code class="language-mermaid">graph TD
  subgraph Inference time
    direction BT
    AI1[Sentence A]
    AI2[BERT]
    AI3[pooling]
    AI4[u]
    BI1[Sentence B]
    BI2[BERT]
    BI3[pooling]
    BI4[v]
    CI1["cosine-sim(u,v)"]
    CI2@{ shape: stadium, label : "[-1;1]" }
    AI1 --&gt; AI2 --&gt; AI3 --&gt; AI4 --&gt; CI1
    BI1 --&gt; BI2 --&gt; BI3 --&gt; BI4 --&gt; CI1
    CI1 --&gt; CI2
  end

  subgraph Training time
    direction BT
    AT1[Sentence A]
    AT2[Bert]
    AT3[pooling]
    AT4[u]
    BT1[Sentence B]
    BT2[Bert]
    BT3[pooling]
    BT4[v]
    CT1["(u, v, |u-v|)"]
    CT2[softmax classifier]
    AT1 --&gt; AT2 --&gt; AT3 --&gt; AT4 --&gt; CT1
    BT1 --&gt; BT2 --&gt; BT3 --&gt; BT4 --&gt; CT1
    CT1 --&gt; CT2
  end
</code></pre> <p>The image above is adapted from https://arxiv.org/abs/1908.10084. They mention training their bi-encoder as a classifier using cross-entropy, but do not get into details about how they do it. Other approaches include using regression to predict the cosine similarity or contrastive learning with contrastive or triplet loss in pairs of pairs of similar/dissimilar texts or triples of anchor/similar/dissimilar texts, respectively.</p> <h4 id="advantages-of-bi-encoders">Advantages of bi-encoders</h4> <ol> <li>Embedding vector calculation is usually fast and lightweight</li> <li>Embedding vectors for each text can be stored adfter being computed and reutilized</li> <li>Comparison between embedding vectors is fast, using cosine similarity</li> </ol> <h3 id="implementing-our-recommendation-system">Implementing our recommendation system</h3> <p>For our project, we will use the <a href="https://huggingface.co/sentence-transformers/all-MiniLM-L6-v2">all-MiniLM-L6-v2</a> model, which is trained using contrastive learning on pairs of sentences.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">sentence_transformers</span> <span class="kn">import</span> <span class="n">SentenceTransformer</span>

<span class="n">model</span> <span class="o">=</span> <span class="nc">SentenceTransformer</span><span class="p">(</span><span class="sh">"</span><span class="s">all-MiniLM-L6-v2</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <p>The model is applied to the movie titles concatenated with their overviews and generate fixed-size embedding vectors of size 384. The output is a matrix of size \(\mid D \mid \times n\), where \(n\) is the dimension of the embedding vector.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">embeddings</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">encode</span><span class="p">(</span>
  <span class="p">(</span><span class="n">movie_metadata</span><span class="p">[</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">]</span> <span class="o">+</span> <span class="sh">"</span><span class="s"> </span><span class="sh">"</span> <span class="o">+</span> <span class="n">movie_metadata</span><span class="p">[</span><span class="sh">"</span><span class="s">overview</span><span class="sh">"</span><span class="p">]).</span><span class="nf">to_list</span><span class="p">(),</span> <span class="n">show_progress_bar</span><span class="o">=</span><span class="bp">True</span>
<span class="p">)</span>
<span class="nf">print</span><span class="p">(</span><span class="n">embeddings</span><span class="p">.</span><span class="n">shape</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Batches:   0%|          | 0/313 [00:00&lt;?, ?it/s]


(10000, 384)
</code></pre></div></div> <h3 id="recovering-movies">Recovering movies</h3> <p>Once again, we recover the movies that are most similar to a randomly selected one based on the similarities between their embeddings.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">top_recommendations</span> <span class="o">=</span> <span class="nf">get_recommendations</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">model</span><span class="p">.</span><span class="nf">similarity</span><span class="p">(</span><span class="n">embeddings</span><span class="p">,</span> <span class="n">embeddings</span><span class="p">))</span>
<span class="nf">print</span><span class="p">(</span><span class="n">top_recommendations</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Top recommendations for Billy Elliot:
id
38848                                A Few Days in September
1257034        Weatherday Live @ The Ukie Club Philly 8/7/23
372489                                                  1980
1270247                                    Bad Boy Fuck Club
11017                                          Billy Madison
18141                                  The Elementary School
472025                                      Dublin Oldschool
581089                                      Haunting Douglas
657923                      Neil Young - BBC In Concert 1971
1006663                                            1985-1986
521639                                           County Line
672083                                       The Winslow Boy
1310228                                             Identity
150518                                      Tenth Avenue Kid
192390                              The Hoosier Schoolmaster
8271                                               Disturbia
1087097                                              Lootin'
1175745                            Bad Kids with Saint Names
127523                                            True Blood
527130                      Unforgettable Memory of a Friend
1208250                                         Cadet School
36961                                                      G
228944                                Billy Childish Is Dead
579357                                           The Dumb Ox
1373646                                                Grown
107598                                   The Kid from Kokomo
463249                                     Say! Young Fellow
470185                                            Schoolgrlz
601619     Danny Adler: Trespassin' at King Records - The...
124487                                          Rhythm Thief
Name: title, dtype: object
</code></pre></div></div> <h3 id="cross-encoders">Cross-encoders</h3> <p>Another transformer architecture that allows us to build a text-based recommendation system is the <em>cross-encoder</em> <a href="https://arxiv.org/abs/1901.04085">[1]</a><a href="https://arxiv.org/abs/2101.08751">[2]</a>. Unlike the bi-encoder, it takes a pair of sentences as input, concatenating them and separating them by a special token, and produces an output in the range \([0; 1]\) indicating how similar they are.</p> <pre><code class="language-mermaid">graph BT
  A(Sentence A) --&gt; concat
  B(Sentence B) --&gt; concat
  concat --&gt; BERT --&gt; Classifier --&gt; Output@{shape: circle, label: "[0; 1]"}
</code></pre> <p>Due to their high computational complexity and usually better results than bi-encoders, cross-encoders are usually used in the re-ranking step of recommendation systems, in which a subset of recommendations has already been selected by previous, more lightweight methods.</p> <p><strong>Advantages of cross-encoders</strong></p> <ul> <li>Tend to have better results in computing sentence similarity than bi-encoders.</li> </ul> <p><strong>Disadvantages of cross-encoders</strong></p> <ul> <li>Computational complexity of using cross-encoders is quadratic compared to the linear complexity of bi-encoders, as every comparison between a new piece of text and texts in storage must use the cross-encoder transformer.</li> </ul> <h3 id="implementing-a-movie-reranker-using-a-cross-encoder">Implementing a movie reranker using a cross-encoder</h3> <p>The code below employs a cross-encoder to rerank the movies selected by the bi-encoder of the previous section. It returns similarity scores between the title and overview of the original movie and the pre-selected movies.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">sentence_transformers.cross_encoder</span> <span class="kn">import</span> <span class="n">CrossEncoder</span>

<span class="n">model</span> <span class="o">=</span> <span class="nc">CrossEncoder</span><span class="p">(</span><span class="sh">"</span><span class="s">cross-encoder/stsb-roberta-base</span><span class="sh">"</span><span class="p">)</span>

<span class="n">ranks</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">rank</span><span class="p">(</span>
  <span class="n">movie_metadata</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="sh">"</span><span class="s">title</span><span class="sh">"</span><span class="p">]</span> <span class="o">+</span> <span class="sh">"</span><span class="s"> </span><span class="sh">"</span> <span class="o">+</span> <span class="n">movie_metadata</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="sh">"</span><span class="s">overview</span><span class="sh">"</span><span class="p">],</span>
  <span class="n">top_recommendations</span><span class="p">,</span>
  <span class="n">show_progress_bar</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
<span class="p">)</span>
<span class="n">ranks</span> <span class="o">=</span> <span class="p">{</span><span class="n">rank</span><span class="p">[</span><span class="sh">"</span><span class="s">corpus_id</span><span class="sh">"</span><span class="p">]:</span> <span class="n">rank</span><span class="p">[</span><span class="sh">"</span><span class="s">score</span><span class="sh">"</span><span class="p">]</span> <span class="k">for</span> <span class="n">rank</span> <span class="ow">in</span> <span class="n">ranks</span><span class="p">}</span>
<span class="nf">print</span><span class="p">(</span><span class="n">pd</span><span class="p">.</span><span class="nc">Series</span><span class="p">(</span><span class="n">ranks</span><span class="p">))</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Batches:   0%|          | 0/1 [00:00&lt;?, ?it/s]


2     0.365634
26    0.360351
24    0.293843
10    0.291097
12    0.258833
9     0.257831
22    0.247428
4     0.222584
21    0.219410
5     0.211042
19    0.175163
14    0.175003
20    0.174640
27    0.173403
11    0.148287
23    0.146889
0     0.146843
13    0.145361
29    0.145283
1     0.124511
16    0.117132
25    0.108611
6     0.101460
3     0.099316
18    0.097358
17    0.080527
7     0.064563
8     0.062674
28    0.051764
15    0.049922
dtype: float32
</code></pre></div></div> <p>Finally, we produce the list of reranked movies.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">ranks_idx_sorted</span> <span class="o">=</span> <span class="nf">sorted</span><span class="p">(</span><span class="nf">zip</span><span class="p">(</span><span class="n">ranks</span><span class="p">.</span><span class="nf">keys</span><span class="p">(),</span> <span class="n">ranks</span><span class="p">.</span><span class="nf">values</span><span class="p">(),</span> <span class="n">strict</span><span class="o">=</span><span class="bp">False</span><span class="p">),</span> <span class="n">key</span><span class="o">=</span><span class="n">operator</span><span class="p">.</span><span class="nf">itemgetter</span><span class="p">(</span><span class="mi">1</span><span class="p">),</span> <span class="n">reverse</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">ranks_idx_sorted</span> <span class="o">=</span> <span class="p">[</span><span class="n">r</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="k">for</span> <span class="n">r</span> <span class="ow">in</span> <span class="n">ranks_idx_sorted</span><span class="p">]</span>
<span class="n">top_recommendations</span><span class="p">.</span><span class="n">iloc</span><span class="p">[</span><span class="n">ranks_idx_sorted</span><span class="p">]</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>id
372489                                                  1980
463249                                     Say! Young Fellow
1373646                                                Grown
521639                                           County Line
1310228                                             Identity
1006663                                            1985-1986
228944                                Billy Childish Is Dead
11017                                          Billy Madison
36961                                                      G
18141                                  The Elementary School
527130                      Unforgettable Memory of a Friend
192390                              The Hoosier Schoolmaster
1208250                                         Cadet School
470185                                            Schoolgrlz
672083                                       The Winslow Boy
579357                                           The Dumb Ox
38848                                A Few Days in September
150518                                      Tenth Avenue Kid
124487                                          Rhythm Thief
1257034        Weatherday Live @ The Ukie Club Philly 8/7/23
1087097                                              Lootin'
107598                                   The Kid from Kokomo
472025                                      Dublin Oldschool
1270247                                    Bad Boy Fuck Club
127523                                            True Blood
1175745                            Bad Kids with Saint Names
581089                                      Haunting Douglas
657923                      Neil Young - BBC In Concert 1971
601619     Danny Adler: Trespassin' at King Records - The...
8271                                               Disturbia
Name: title, dtype: object
</code></pre></div></div> <h2 id="conclusions">Conclusions</h2> <p>This project showcased two different ways of making a movie recommendations systems and one way of making a movie reranking system, based solely on the title and overview of a movie a hypothetical user might enjoy. Movies with similar titles and overviews to the original one can be recovered using techniques such as TF-IDF, bi-encoders or cross-encoders and can also be reranked using any of these techniques, especially the most precise but computationnaly expensive ones such as the cross-encoder.</p> <p>We have gone on an overview of how TF-IDF, bi-encoders and cross-encoders are trained and work and implemented everything in Python using open source packages such as scikit-learn and sentence_transformers, as well the open TMDb movies dataset, which is downloaded automatically from Kaggle use the kagglehub package.</p> <p>These techniques are obviously not constrained to movie recommendations and can be used to perform similarity search on any text corpus.</p> <p>Se you guys next time!</p>]]></content><author><name></name></author><category term="recommendations-systems"/><category term="sklearn"/><category term="python"/><category term="open-source"/><category term="recommendation-systems"/><category term="td-idf"/><category term="text-embeddings"/><category term="bi-encoders"/><category term="cross-encoders"/><category term="sentence-transformers"/><category term="kaggle"/><summary type="html"><![CDATA[A showcase of TF-IDF, bi-encoders and cross-encoders]]></summary></entry><entry><title type="html">Running a Gemma-powered question-answering chatbot locally with LangChain + Ollama</title><link href="https://douglasrizzo.github.io/blog/2024/03/local-gemma-chatbot-langchain-ollama/" rel="alternate" type="text/html" title="Running a Gemma-powered question-answering chatbot locally with LangChain + Ollama"/><published>2024-03-01T00:00:00+00:00</published><updated>2024-03-01T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2024/03/local-gemma-chatbot-langchain-ollama</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2024/03/local-gemma-chatbot-langchain-ollama/"><![CDATA[<h2 id="introduction">Introduction</h2> <p>Last week, I started my quest to build my first LLM-powered chatbot that runs locally and executes RAG on my <a href="https://obsidian.md/">Obsidian</a> document base. You can see it <a href="/blog/2024/02/llm-qa-obsidian-rag/">here</a>.</p> <p>This post is a follow-up to that one. The highlights of this one are:</p> <ol> <li>I will test the brand new <a href="https://ai.google.dev/gemma">Google Gemma</a> family of models and qualitatively compare it to a Mistral model of same size.</li> <li>The chatbot will run 100% locally in my computer with a GTX 1070, 7h gen i7 and 32 GB of RAM, using Chroma for the vector store and <a href="https://ollama.com/">Ollama</a> for the models.</li> <li>Unlike in the <a href="/blog/2024/02/llm-qa-obsidian-rag/">previous post</a>, we’ll configure the correct prompt templates for our instruction-tuned models.</li> </ol> <p>Also, since <a href="/blog/2024/02/llm-qa-obsidian-rag/">my last post</a>, I’ve refactored the code base in its current state as both a Python package and a command-line tool, which you can find in <a href="https://github.com/douglasrizzo/langsidian">this link</a>. This is what I used to run the experiments shown in this page. A sample notebook is provided <a href="https://github.com/douglasrizzo/langsidian/blob/master/2%20-%20Langsidian%20as%20a%20package.ipynb">here</a> and <a href="https://github.com/douglasrizzo/langsidian/tree/master/langsidian">the underlying code</a> is &lt; 200 lines long!</p> <h2 id="test-driving-gemma-7b">Test-driving Gemma-7b</h2> <p>A few days ago, Google released <a href="https://ai.google.dev/gemma">Gemma</a>, a family of lightweight models the same size as Mistral-7b, the one I was already using.</p> <p>My first attempt at loading Gemma-7b was through <a href="https://huggingface.co/google/gemma-7b-it">Hugging Face</a>. However, it needs extra configuration to fit in my memory, i.e. float16/bfloat16 quantization with PyTorch, or 8bit/4bit quantization with bitsandbytes. Also, the model files are huge, totalling 20 GB.</p> <p>For now, let’s familiarize ourselves with Ollama, which is simpler, and leave the Hugging Face ecosystem for later.</p> <h2 id="enter-ollama">Enter Ollama</h2> <p>It turns out a very widespread way of running models locally is through <a href="https://ollama.com/">Ollama</a>, which is very simple to install on Linux.</p> <div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-fsSL</span> https://ollama.com/install.sh | sh
</code></pre></div></div> <p>Ollama has a Docker-like interface (it was made by <a href="https://twitter.com/jmorgan">an ex-Docker employee</a>) and models can be downloaded using their names and some basic tags. Downloaded models can be executed via python using their <a href="https://pypi.org/project/ollama/">official library</a>.</p> <p>With that, I decided to stop using models from multiple libraries and frameworks and run all of them in Ollama. The commands below downloaded Mistral-7b, Gemma-7b, and a text embedding model from <a href="https://home.nomic.ai/">Nomic.AI</a>.</p> <div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ollama pull mistral:7b-instruct
ollama pull gemma:7b-instruct
ollama pull nomic-embed-text
</code></pre></div></div> <p>The model files downloaded by Ollama are considerably smaller (each 7b model fit in a single 5GB file). They also loaded into my GPU memory, alongside the embedding model.</p> <h2 id="configuring-the-correct-prompt-templates">Configuring the correct prompt templates</h2> <p>It turns out the prompt templates, especially for Instruct models, need to use the correct tokens and that is not done automatically by LangChain or any other library.</p> <p>I went after the correct templates on the Ollama website. They are shown below. Contrast with <a href="/blog/2024/02/llm-qa-obsidian-rag/#retrieval-qa-with-custom-prompt-template">my last post</a>, in which I copied an internal prompt from LangChain, which was not suitable for any specific model.</p> <p>While tweaking the contents of the prompt template, I realized how much variability in the responses I got from only minor tweaks. For example, if I told Gemma something like <em>“if you don’t know the answer, just say you don’t know and not make anything up”</em>, the model would just refuse to answer any questions, even if the information was present in the retrieved text chunks. To make the comparison fair, I also removed the same section from the mistral prompt template, which I used in the <a href="/blog/2024/02/llm-qa-obsidian-rag/#retrieval-qa-with-custom-prompt-template">previous post</a>.</p> <h3 id="mistral-prompt-template">Mistral prompt template</h3> <p>Sources: <a href="https://ollama.com/library/mistral:7b-instruct">Ollama</a> and <a href="https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.2">Hugging Face Hub</a>.</p> <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;s&gt;[INST] Use the following pieces of context to answer the question at the end. Present a well-formatted answer, using Markdown if possible. Don't go over three paragraphs when answering.
---
{context}
---
Question: {question} [/INST]
</code></pre></div></div> <h3 id="gemma-prompt-template">Gemma prompt template</h3> <p>Sources: <a href="https://huggingface.co/google/gemma-7b-it">Ollama</a> and <a href="https://ollama.com/library/gemma:7b-instruct">Hugging Face Hub</a>.</p> <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&lt;start_of_turn&gt;user
Use the following pieces of context to answer the question at the end. Present a well-formatted answer, using Markdown if possible. Don't go over three paragraphs when answering.
---
{context}
---
Question: {question}&lt;end_of_turn&gt;
&lt;start_of_turn&gt;model
</code></pre></div></div> <h2 id="tweaking-rag-parameters">Tweaking RAG parameters</h2> <p>One problem I was having was that performing maximal marginal similarity on a small number of chunks (e.g. 3) tended to result only a single helpful text chunk. To fix that I</p> <ul> <li>reduced the chunk sizes</li> <li>retrieved more chunks</li> </ul> <p>Some final tweaking that made the output of both models better was using the following parameters:</p> <ul> <li>Chunk size: 400 characters</li> <li>Chunk overlap: 50 characters</li> <li>Chunks returned by similarity for <a href="https://python.langchain.com/docs/modules/model_io/prompts/example_selector_types/mmr">MMR</a> search: 10</li> <li>Final number of chunks returned by <a href="https://python.langchain.com/docs/modules/model_io/prompts/example_selector_types/mmr">MMR</a>: 6</li> <li><a href="https://python.langchain.com/docs/modules/model_io/prompts/example_selector_types/mmr">MMR</a> \(\lambda\) (0 = maximum diversity among chunks; 1 = no diversity): 0.7</li> </ul> <h2 id="running-the-models">Running the models</h2> <p>Since my last post, I’ve refactored the code base in its current state as both a Python package and a command-line tool, which you can find in <a href="https://github.com/douglasrizzo/langsidian">this link</a>. This is what I used in the construction of this post.</p> <p>The snippet below (which is also available as a <a href="https://github.com/douglasrizzo/langsidian/blob/master/2%20-%20Langsidian%20as%20a%20package.ipynb">Jupyter Notebook</a>) showcases how to instantiate and talk to the LLM-powered Q&amp;A bot:</p> <div class="language-py highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">pathlib</span> <span class="kn">import</span> <span class="n">Path</span>
<span class="kn">from</span> <span class="n">langsidian</span> <span class="kn">import</span> <span class="n">ChatBot</span><span class="p">,</span> <span class="n">DocumentBase</span>

<span class="n">bot</span> <span class="o">=</span> <span class="nc">ChatBot</span><span class="p">(</span>
  <span class="n">docs_path</span><span class="o">=</span><span class="p">(</span><span class="n">Path</span><span class="p">.</span><span class="nf">home</span><span class="p">(</span><span class="sh">"</span><span class="s">Documents</span><span class="sh">"</span><span class="p">,</span> <span class="sh">"</span><span class="s">Obsidian</span><span class="sh">"</span><span class="p">)),</span>
  <span class="n">vectorstore_db_path</span><span class="o">=</span><span class="nc">Path</span><span class="p">(</span><span class="sh">"</span><span class="s">docs/chroma</span><span class="sh">"</span><span class="p">),</span>
  <span class="n">document_type</span><span class="o">=</span><span class="n">DocumentBase</span><span class="p">.</span><span class="n">OBSIDIAN</span><span class="p">,</span>
  <span class="n">model_type</span><span class="o">=</span><span class="sh">"</span><span class="s">mistral:7b-instruct</span><span class="sh">"</span><span class="p">,</span>
  <span class="n">embeddings</span><span class="o">=</span><span class="sh">"</span><span class="s">nomic</span><span class="sh">"</span><span class="p">,</span>
<span class="p">)</span>

<span class="n">q</span> <span class="o">=</span> <span class="sh">"</span><span class="s">What is zero-shot learning?</span><span class="sh">"</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">**Question: </span><span class="si">{</span><span class="n">q</span><span class="si">}</span><span class="s">**</span><span class="se">\n\n</span><span class="s"> Answer: </span><span class="si">{</span><span class="n">bot</span><span class="p">.</span><span class="nf">answer</span><span class="p">(</span><span class="n">q</span><span class="p">)</span><span class="si">}</span><span class="sh">"</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="sh">"</span><span class="se">\n\n</span><span class="s">---</span><span class="se">\n\n</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <p>It can also be executed as a standalone module. The document path and model name can be selected with command-line arguments:</p> <div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>python <span class="nt">-m</span> langsidian
</code></pre></div></div> <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[Prompt]: Who were the authors of the Deep Q-Network paper?
[Assistant]:  The authors of the Deep Q-Network paper were Mnih, Vaswani, Graves, et al. (2015). You can find their paper here: &lt;https://arxiv.org/abs/1312.5602&gt;.
</code></pre></div></div> <h2 id="results">Results</h2> <p>Below, I asked the same questions to both Mistral-7b-it and Gemma-7b-it, giving them access to my Obsidian document base, whose chunks are now embedded using <a href="https://blog.nomic.ai/posts/nomic-embed-text-v1">Nomic Embed</a>.</p> <p>Analyzing the output qualitatively, I found that Mistral tends to give more informative and helpful answers. It also makes better use of the information in the chunks provided by the RAG procedure, creating richer answers, whereas Gemma tends to repeat itself or cut answers short when it hits a dead-end such as in the answer for <a href="#gemma-7b-1">this question</a>.</p> <p>Also, in <a href="#gemma-7b">the first question</a>, Gemma explained terms that may have been in the context chunks recovered for RAG (such as \(a'\) and \(\pi_*\)), but they did not appear in its final answer, which would definitely confuse users in a conversation.</p> <hr/> <h3 id="question-give-me-the-equation-for-the-action-value-function-update-and-explain-its-terms">Question: Give me the equation for the action value function update and explain its terms.</h3> <h4 id="mistral-7b">Mistral-7b</h4> <p>The equation for the action-value function update using the n-step return is as follows:</p> \[Q_{t+n}(S_t, A_t) \leftarrow Q_{t+n-1}(S_t, A_t) + \alpha [G_{t:t+n} - \gamma^n Q_{t+n-1}(S_t, A_t)]\] <p>This equation is a form of the Bellman equation for the action-value function. Let’s break down its terms:</p> <ul> <li>\(Q_{t+n}\): The action-value function at time step \(t+n\) for state-action pair \((S_t, A_t)\).</li> <li>\(\alpha\): The learning rate or step size, which determines how much new information is incorporated in each update.</li> <li>\(G_{t:t+n}\): The n-step return from time step t to time step \(t+n\). It’s the total reward obtained by following policy \(\pi\) from state \(S_t\) and taking action \(A_t\), plus all the discounted future rewards, i.e., \(G_{t:t+n} = R_{t+1:t+n}+ \gamma V_{\pi}(S_{t+n})\)</li> <li>\(\gamma\): The discount factor, which is used to discount future rewards by a certain percentage to make them present values.</li> <li>\(Q_{t+n-1}\): The old estimate of the action-value function at time step \(t+n-1\) for state-action pair \((S_t, A_t)\).</li> </ul> <p>This update rule aims to minimize the difference between the current and new estimates of \(Q(S_t,A_t)\), gradually improving the estimation as more samples are collected.</p> <h4 id="gemma-7b">Gemma-7b</h4> <p><strong>Equation for Action Value Function Update:</strong></p> \[Q_{t+n}(S_t, A_t) \doteq Q_{t+n-1}(S_t, A_t) + \alpha [G_{t:t+n} - \gamma^n Q_{t+n-1}(S_t, A_t)]\] <p><strong>Explanation of Terms:</strong></p> <ul> <li><strong>\(Q_{t+n}(S_t, A_t)\):</strong> The action-value function at time \(t+n\) for state \(S_t\) and action \(A_t\).</li> <li><strong>\(Q_{t+n-1}(S_t, A_t)\):</strong> The action-value function at time \(t+n-1\) for state \(S_t\) and action \(A_t\).</li> <li><strong>\(\alpha\):</strong> The learning rate, which controls the rate of learning.</li> <li><strong>\(G_{t:t+n}\):</strong> The n-step return, which is the total reward from time \(t\) to time \(t+n\).</li> <li><strong>\(\gamma\):</strong> The discount factor, which accounts for the value of future rewards.</li> <li><strong>\(a'\):</strong> The action that is not taken at time \(t\).</li> <li><strong>\(\pi_*\):</strong> The optimal policy.</li> </ul> <p><strong>Note:</strong> This equation is for the action-value function update in Q-learning, not the state-value function update.</p> <hr/> <h3 id="question-what-is-the-architecture-of-the-deep-q-networks">Question: What is the architecture of the Deep Q-Networks?</h3> <h4 id="mistral-7b-1">Mistral-7b</h4> <p>The Deep Q-Network (DQN) architecture uses a deep neural network to approximate the Q* function in reinforce learning. The input to the network are 4 frames of 84x84 pixel screenshots from Atari 2600 games, only using the luminance values of the pixels. The network then uses three convolutional layers to learn visual representations of the game states. The output of the neural network is the Q values of all possible actions for each state, ranging from 4 to 18.</p> <p>This architecture builds upon the Q-learning algorithm, which aims to find the optimal policy by iteratively improving the Q values based on observed state-action pairs and their corresponding rewards. However, directly applying this algorithm to deep neural networks with large input spaces is infeasible due to the computational demands.</p> <p>To overcome this challenge, DQN uses experiences from multiple frames and applies a target network for more stable learning. The target network is updated periodically to match the weights of the online network, ensuring that the Q values in the target network do not change too frequently during training. Additionally, the authors use experience replay, where they store transitions in a buffer and sample them randomly to train the network, which helps in reducing correlation between consecutive samples and improving stability.</p> <p>These architectural enhancements allowed DQN to learn complex visual representations of Atari games, achieve human-level performance on several benchmark tasks, and set a new standard for deep reinforce learning research.</p> <h4 id="gemma-7b-1">Gemma-7b</h4> <p>The text describes the architecture of Deep Q-Networks, which uses a deep neural network to approximate the Q* function. The neural network has three convolution layers to learn visual representations of the game states.</p> <p>The text does not describe the architecture of the convolutional layers, therefore I cannot answer the question.</p> <hr/> <h3 id="question-what-is-the-difference-between-causal-language-modeling-and-masked-language-modeling">Question: What is the difference between causal language modeling and masked language modeling?</h3> <h4 id="mistral-7b-2">Mistral-7b</h4> <p>Causal and masked language modeling are two different methods used for pre-training language models.</p> <p>In <strong>causal language modeling</strong>, also known as autoregressive language modeling, the language model is trained to predict the next token in a sequence given the context of the previous tokens. The model has access to the entire sequence during training and prediction, and its task is to generate the next token based on the context provided. However, since there is no ground truth available during inference, this can lead to a discrepancy between training and inference, known as Exposure Bias. This issue can be addressed through techniques like Curriculum learning.</p> <p>In <strong>masked language modeling</strong>, also known as Masked Language Modeling (MLM), tokens are randomly masked at training time and the model is trained to reconstruct the original text by predicting the masked tokens. For instance, in the sentence “the teacher teaches the student”, the word “teaches” might be masked as “<MASK>". During training, the model is presented with the masked token and its context, and its task is to learn to fill in the masked token based on the context provided. BERT is an example of a masked language model. The main difference between causal and masked language modeling lies in how the models are trained and what they are optimized for: causal models predict the next token given the context, while masked models learn to fill in missing tokens based on their context.</MASK></p> <p>Sources: DeepLearning.AI Natural Language Processing Specialization, Generative AI with Large Language Models.</p> <h4 id="gemma-7b-2">Gemma-7b</h4> <p>Causal language modeling and masked language modeling are two methods for pre-training language models.</p> <p>Causal language modeling allows the model to see the first tokens of the sequence and its task is to predict the next token. Masked language modeling, on the other hand, randomly masks tokens at training time and the model is trained to reconstruct the original text by predicting the masked tokens.</p> <p>The main difference between causal language modeling and masked language modeling is that in causal language modeling, the model has access to the first tokens of the sequence and its task is to predict the next token, while in masked language modeling, the model is trained to reconstruct the original text by predicting the masked tokens.</p> <hr/> <h3 id="question-what-is-zero-shot-learning">Question: What is zero-shot learning?</h3> <h4 id="mistral-7b-3">Mistral-7b</h4> <p>Zero-shot learning is a concept used in machine learning, specifically in the context of Generative AI and Large Language Models (LLMs), to describe the capability of an LLM to predict classes it was not explicitly trained on without being given any explicit examples during training or at inference time. In other words, the model makes predictions based on its existing knowledge, rather than learning from new examples provided in real-time. This is in contrast to few-shot learning, where the model is given a few examples of the task it’s expected to perform before being presented with the actual task. Zero-shot learning requires a large and diverse dataset for the model to generalize effectively to unseen classes or concepts.</p> <p>One limitation of zero-shot learning is that it may not be as effective as few-shot learning, especially when dealing with complex tasks or rare classes. Another limitation is that it relies heavily on the quality and representativeness of the training data for making accurate predictions. However, since zero-shot learning allows models to execute new tasks without being given any explicit examples, it can be beneficial in scenarios where acquiring labeled data is difficult, costly, or time-consuming.</p> <p>Regarding your additional question: In Q-learning, importance sampling is not used because it is an off-policy reinforce learning algorithm that learns from a sequence of state-action pairs (trajectories) generated by a policy π, which may not be the optimal one. The goal is to estimate the action-value function Q(s,a), and importance sampling would introduce additional complexity without significant benefits in this context.</p> <h4 id="gemma-7b-3">Gemma-7b</h4> <p>Zero-shot learning is the capability of a model to predict classes it was not explicitly trained on. In the context of Generative AI and LLMs, zero-shot learning refers to the capability of an LLM to execute new tasks without being given any explicit examples.</p> <p>In zero-shot learning, the model is given no examples of the task it is expected to perform, and it must generalize from its previous experiences to complete the task. This contrasts with few-shot learning, which involves providing the model with a few examples of the task it is expected to perform.</p> <p>For example, if you ask a model to classify a review as positive or negative, and it has never seen a review with that sentiment before, zero-shot learning would involve the model making a generalization based on its previous experiences to determine whether the review is positive or negative.</p> <hr/> <h3 id="question-explain-to-me-the-concept-of-bucketing-in-rnns">Question: Explain to me the concept of bucketing in RNNs</h3> <h4 id="mistral-7b-4">Mistral-7b</h4> <p>Bucketing in Recurrent Neural Networks (RNNs) is a technique used for batching sequences while minimizing padding. The main goal is to process sequences of varying lengths efficiently and maintain a consistent batch size during training. Here’s a step-by-step explanation:</p> <ol> <li><strong>Divide data into buckets:</strong> Divide the input data into <code class="language-plaintext highlighter-rouge">m</code> buckets based on sequence lengths. Each bucket represents a specific range of sequence lengths.</li> <li><strong>Sample sequences from a single bucket:</strong> For each batch, sample all sequences from only one of the buckets. This ensures that most sequences in a batch have similar lengths, reducing the need for extensive padding.</li> <li><strong>Pad sequences to the largest one:</strong> Pad all sequences in the batch to match the size of the longest sequence. This guarantees that every sequence receives the same amount of processing during each time step.</li> </ol> <p>Bucketing is an essential technique when dealing with sequence data, as it helps to minimize padding and improve training efficiency. However, it might require more computational resources due to the need to process multiple buckets for generating batches over time.</p> <p>It’s important to note that this method assumes that sequences within a bucket are independent of one another. If there is any dependence between sequences in a bucket, this assumption would not hold true, and other data processing techniques might be required.</p> <h4 id="gemma-7b-4">Gemma-7b</h4> <p>Bucketing in RNNs is a technique for batching sequences in a way that minimizes padding. The idea is to group sequences of similar length into buckets and then process the buckets separately.</p> <p>The process of bucketing involves dividing the data into buckets, sampling sequences from a single bucket, and padding all sequences in a batch to the size of the largest sequence in the batch. This technique is useful for RNNs because it allows for the efficient processing of sequences of varying lengths.</p> <p>The technique is illustrated in the provided text with two images. The first image shows the process of dividing the data into buckets, and the second image shows the process of padding the sequences in a batch.</p> <hr/> <h3 id="question-what-is-a-named-entity">Question: What is a named entity?</h3> <h4 id="mistral-7b-5">Mistral-7b</h4> <p>A named entity is a real-world object that can be denoted with a proper name, examples include persons, locations, organizations, products, geographical entities, geopolitical entities, time indicators, artifacts, events, and natural phenomena. Named Entity Recognition (NER) systems are used to automatically locate named entities from unstructured text. This process is important for various applications such as improving search engine efficiency by scanning websites and storing named entities for later matching with user queries, and enhancing recommendation systems by extracting named entities from a user’s search history to identify their interests.</p> <p>For instance, in the sentence “Sharon flew to Miami on Friday,” the named entities are “Sharon” (person), “Miami” (location), and “Friday” (time indicator). NER systems can accurately identify and tag these named entities within the text. The remaining tokens that do not represent named entities are typically tagged as filler words or <code class="language-plaintext highlighter-rouge">O</code>.</p> <h4 id="gemma-7b-5">Gemma-7b</h4> <p>A named entity is a real-world object that can be denoted with a proper name. It can be abstract or have a physical existence. Examples of named entities include people, locations, organizations, and products.</p> <p>Named entities are extracted from text and are used to identify and classify named objects in a sentence. They are used in various applications, such as search engine efficiency, recommendation systems, and information extraction.</p> <p>In the text provided, the sentence “Sharon flew to Miami on Friday” would have the named entities “Sharon,” “Miami,” and “Friday.”</p> <h2 id="conclusions">Conclusions</h2> <p>On this post, I show you how I locally executed an LLM-powered Q&amp;A chatbot that performs RAG on an Obsidian, using Mistral-7b and Gemma-7b instruction fine-tuned models as well as Nomic-Embed, all provided by Ollama.</p> <p>I showed you how I did and you can:</p> <ul> <li>Install Ollama;</li> <li>Download Ollama models;</li> <li>Configure prompt templates for the instruction-tuned versions of Gemma and Mistral, and;</li> <li>Configure some search parameters to get better chunks and RAG results.</li> </ul>]]></content><author><name></name></author><category term="nlp"/><category term="llms"/><category term="python"/><category term="langchain"/><category term="ollama"/><category term="google-gemma"/><category term="mistral"/><summary type="html"><![CDATA[Introduction]]></summary></entry><entry><title type="html">Answering questions from an Obsidian database with LLMs + RAG</title><link href="https://douglasrizzo.github.io/blog/2024/02/llm-qa-obsidian-rag/" rel="alternate" type="text/html" title="Answering questions from an Obsidian database with LLMs + RAG"/><published>2024-02-19T00:00:00+00:00</published><updated>2024-02-19T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2024/02/llm-qa-obsidian-rag</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2024/02/llm-qa-obsidian-rag/"><![CDATA[<h2 id="introduction">Introduction</h2> <p>This notebook presents a proof-of-concept on how to create a question-answering bot powered by an LLM and with knowledge extracted from actual documents, more specifically, a collection of notes from Obsidian.</p> <p>I am going to run all experiments locally, using a 7th gen i7, an NVIDIA GTX 1070 and 32 GBs of RAM.</p> <p>A lot of the heavy lifting will be done by the <a href="https://www.langchain.com/">LangChain</a> package, which I am on the process of learning to use.</p> <p>On the road to building this Q&amp;A bot, we will be introduced to many concepts:</p> <ol> <li>Document loading</li> <li>Text data cleaning using regex</li> <li>Splitting of Markdown documents into text chunks</li> <li>Sentence embeddings</li> <li>Vector stores</li> <li>Similarity search using cosine similarity between embedding vectors</li> <li>maximal marginal relevance search</li> <li>Self-query retrieval</li> <li>Contextual compression retrieval</li> <li>Question-answering with retrieval augmented generation</li> <li>Question-answering with retrieval augmented generation and custom templates</li> </ol> <p>So that no one gets lost, the following diagram explains how the whole pipeline to get to our final Q&amp;A bot (and how this notebook) works:</p> <p><img src="/assets/img/langsidian.png" alt="My happy picture" style="width: 100%;"/></p> <h2 id="prerequisites">Prerequisites</h2> <ol> <li>You can find the environment.yml file to create a conda env with the necessary dependencies to run the notebook.</li> <li> <p>You should download a model from the GPT4All website and save it on <code class="language-plaintext highlighter-rouge">./models/my_little_llm.gguf</code>. The one below is the one I used.</p> <div class="language-sh highlighter-rouge"><div class="highlight"><pre class="highlight"><code>wget https://gpt4all.io/models/gguf/mistral-7b-openorca.Q4_0.gguf <span class="nt">-O</span> models/my_little_llm.gguf
</code></pre></div> </div> </li> </ol> <h2 id="loading-documents">Loading documents</h2> <p>Here I used the <code class="language-plaintext highlighter-rouge">ObsidianLoader</code> document loader and point it to the directory that contains all my notes in Markdown format.</p> <p>We can see I have ~500 text files.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">pathlib</span> <span class="kn">import</span> <span class="n">Path</span>

<span class="n">docs_path</span> <span class="o">=</span> <span class="p">(</span><span class="n">Path</span><span class="p">.</span><span class="nf">home</span><span class="p">()</span> <span class="o">/</span> <span class="sh">"</span><span class="s">Documents</span><span class="sh">"</span> <span class="o">/</span> <span class="sh">"</span><span class="s">Obsidian</span><span class="sh">"</span><span class="p">).</span><span class="nf">absolute</span><span class="p">()</span>
</code></pre></div></div> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain_community.document_loaders</span> <span class="kn">import</span> <span class="n">ObsidianLoader</span>

<span class="n">loader</span> <span class="o">=</span> <span class="nc">ObsidianLoader</span><span class="p">(</span><span class="n">docs_path</span><span class="p">,</span> <span class="n">collect_metadata</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="n">encoding</span><span class="o">=</span><span class="sh">"</span><span class="s">UTF-8</span><span class="sh">"</span><span class="p">)</span>
<span class="n">docs</span> <span class="o">=</span> <span class="n">loader</span><span class="p">.</span><span class="nf">load</span><span class="p">()</span>
<span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Loaded </span><span class="si">{</span><span class="nf">len</span><span class="p">(</span><span class="n">docs</span><span class="p">)</span><span class="si">}</span><span class="s"> docs</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Encountered non-yaml frontmatter


Loaded 499 docs
</code></pre></div></div> <p>Let’s take a peek at one of the documents. We can see it has the textual content itself, as well as some metadata. The <code class="language-plaintext highlighter-rouge">ObsidianLoader</code> includes file properties from Obsidian documents, such as tags, dates and aliases, as part of the metadata.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">docs</span><span class="p">[</span><span class="mi">7</span><span class="p">]</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Document(page_content='A method for pre-training [[language model]]s in which the model has access to the first tokens of the sequence and its task is to predict the next token.\n\nThe following examples depict how a single sequence can be turned into multiple training examples:\n\n1. `&lt;START&gt;` → `the`\n1. `&lt;START&gt; the` → `teacher`\n1. `&lt;START&gt; the teacher` → `teaches`\n1. `&lt;START&gt; the teacher teaches` → `the`\n1. `&lt;START&gt; the teacher teaches the` → `student`\n1. `&lt;START&gt; the teacher teaches the student` → `&lt;END&gt;`\n\nModels trained using this method have access to the full sequence of tokens at inference time, making them appropriate for non-generative tasks that revolve around processing a sequence of tokens as a whole, for example:\n\n- [[Sentiment Analysis]]\n- [[Named entity recognition]]\n- [[Word classification]]\n\n[[Bidirectional Encoder Representation from Transformers|BERT]] is an example of a masked language model. Example from [[Bidirectional Encoder Representation from Transformers|BERT]]: Choose 15% of the tokens at random: mask them 80% of the time, replace them with a random token 10% of the time, or keep as is 10% of the time.\n\n## Sources\n\n- [[DeepLearning.AI Natural Language Processing Specialization]]\n- [[Generative AI with Large Language Models]]', metadata={'source': 'Causal language modeling.md', 'path': '/home/dodo/Documents/Obsidian/Causal language modeling.md', 'created': 1700448369.2719378, 'last_modified': 1700448369.2719378, 'last_accessed': 1708267659.2105181, 'tags': 'area/ai/nlp/llm', 'date': '2023-11-19 23:41'})
</code></pre></div></div> <h2 id="cleaning-documents">Cleaning documents</h2> <p>Obsidian documents have some of their own Markdown flavor, like <code class="language-plaintext highlighter-rouge">[[Graph Neural Network|GNNs]]</code>, where <code class="language-plaintext highlighter-rouge">Graph Neural Network</code> is the name of a document and <code class="language-plaintext highlighter-rouge">GNNs</code> is what appears on the text. In cases like these, we want to keep only the second part.</p> <p>It also has full-on links, such as <code class="language-plaintext highlighter-rouge">[[grid world]]</code>, in which case we want to remove the double brackets.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># !pip install google-re2
</span><span class="kn">import</span> <span class="n">re2</span>

<span class="n">docus</span> <span class="o">=</span> <span class="p">[]</span>
<span class="n">insane_pattern</span> <span class="o">=</span> <span class="sa">r</span><span class="sh">"</span><span class="s">\[\[([^\]]*?)\|([^\[]*?)\]\]</span><span class="sh">"</span>
<span class="k">for</span> <span class="n">doc</span> <span class="ow">in</span> <span class="n">docs</span><span class="p">:</span>
    <span class="n">s</span> <span class="o">=</span> <span class="n">re2</span><span class="p">.</span><span class="nf">search</span><span class="p">(</span><span class="n">insane_pattern</span><span class="p">,</span> <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">s</span> <span class="ow">is</span> <span class="ow">not</span> <span class="bp">None</span><span class="p">:</span>
        <span class="n">new_doc</span> <span class="o">=</span> <span class="n">re2</span><span class="p">.</span><span class="nf">sub</span><span class="p">(</span><span class="n">insane_pattern</span><span class="p">,</span> <span class="sa">r</span><span class="sh">"</span><span class="s">\2</span><span class="sh">"</span><span class="p">,</span> <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">)</span>
        <span class="n">docus</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span>
            <span class="p">(</span>
                <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">,</span>
                <span class="n">new_doc</span><span class="p">,</span>
            <span class="p">)</span>
        <span class="p">)</span>
        <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span> <span class="o">=</span> <span class="n">new_doc</span>
    <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span> <span class="o">=</span> <span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">.</span><span class="nf">replace</span><span class="p">(</span><span class="sh">"</span><span class="s">[[</span><span class="sh">"</span><span class="p">,</span> <span class="sh">""</span><span class="p">).</span><span class="nf">replace</span><span class="p">(</span><span class="sh">"</span><span class="s">]]</span><span class="sh">"</span><span class="p">,</span> <span class="sh">""</span><span class="p">)</span>

<span class="nf">sorted</span><span class="p">(</span><span class="n">docus</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="k">lambda</span> <span class="n">x</span><span class="p">:</span> <span class="nf">len</span><span class="p">(</span><span class="n">x</span><span class="p">[</span><span class="mi">1</span><span class="p">]))[</span><span class="mi">0</span><span class="p">]</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>('- [[Intersection over Union|IoU]]', '- IoU')
</code></pre></div></div> <h2 id="splitting-documents">Splitting documents</h2> <p>This step splits the documents loaded in the previous step into smaller chunks.</p> <p>LangChain provides its own Markdown text splitter, which we are going to use.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain.text_splitter</span> <span class="kn">import</span> <span class="n">MarkdownTextSplitter</span>

<span class="n">splitter</span> <span class="o">=</span> <span class="nc">MarkdownTextSplitter</span><span class="p">(</span><span class="n">chunk_size</span><span class="o">=</span><span class="mi">400</span><span class="p">,</span> <span class="n">chunk_overlap</span><span class="o">=</span><span class="mi">50</span><span class="p">)</span>
<span class="n">splits</span> <span class="o">=</span> <span class="n">splitter</span><span class="p">.</span><span class="nf">split_documents</span><span class="p">(</span><span class="n">docs</span><span class="p">)</span>


<span class="nf">len</span><span class="p">(</span><span class="n">splits</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1510
</code></pre></div></div> <p>Let’s take a peek at a chunk. They inherit the metadata of their parent document.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">splits</span><span class="p">[</span><span class="mi">542</span><span class="p">]</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Document(page_content='# epsilon-soft policies\n\nAn $$\\epsilon$$-soft policy is a stochastic policy that always assigns a non-zero $$\\frac{\\epsilon}{|A|}$$ probability to all actions. These policies always perform some exploration.\n\nThe uniform random policy is an $$\\epsilon$$-soft policy. The epsilon-greedy policy also is.', metadata={'source': 'epsilon-soft policies.md', 'path': '/home/dodo/Documents/Obsidian/epsilon-soft policies.md', 'created': 1680669506.8282943, 'last_modified': 1680669506.8282943, 'last_accessed': 1708267660.780534, 'tags': 'area/ai/rl project/rl-spec', 'aliases': 'epsilon-soft policy', 'date': '2021-05-24 18:32'})
</code></pre></div></div> <h2 id="computing-embeddings-and-saving-them-to-a-vector-store">Computing embeddings and saving them to a vector store</h2> <p>To quickly search for text chunks, it is useful to precompute an embedding vector for each chunk and store it for future use.</p> <p>An embedding vector is a numerical vector that represents the text chunk. It allows us to compare chunks in the embedding space. Chunks with similar semantic meaning tend to have similar embedding vectors. This similarity can be computed using e.g. cosine similarity.</p> <p>My choice for embedding generator was <a href="https://www.sbert.net/">SentenceTransformers</a>, provided by Hugging Face, which runs locally.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># !pip install sentence_transformers
</span><span class="kn">from</span> <span class="n">langchain.embeddings.huggingface</span> <span class="kn">import</span> <span class="n">HuggingFaceEmbeddings</span>

<span class="n">embedding</span> <span class="o">=</span> <span class="nc">HuggingFaceEmbeddings</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/home/dodo/.anaconda3/envs/langsidian/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
  from .autonotebook import tqdm as notebook_tqdm
</code></pre></div></div> <p>Computed embedding vectors can be stored in <em>vector stores</em>. The one we will use in this project is <a href="https://docs.trychroma.com/">Chroma</a>. It is free, runs locally and is perfect for our small document base.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># !pip install chromadb
</span><span class="kn">from</span> <span class="n">langchain.vectorstores</span> <span class="kn">import</span> <span class="n">Chroma</span>

<span class="n">persist_directory</span> <span class="o">=</span> <span class="sh">"</span><span class="s">docs/chroma/</span><span class="sh">"</span>
<span class="err">!</span><span class="n">rm</span> <span class="o">-</span><span class="n">rf</span> <span class="p">.</span><span class="o">/</span><span class="n">docs</span><span class="o">/</span><span class="n">chroma</span>  <span class="c1"># remove old database files if any
</span><span class="n">vectordb</span> <span class="o">=</span> <span class="n">Chroma</span><span class="p">.</span><span class="nf">from_documents</span><span class="p">(</span>
    <span class="n">documents</span><span class="o">=</span><span class="n">splits</span><span class="p">,</span> <span class="n">embedding</span><span class="o">=</span><span class="n">embedding</span><span class="p">,</span> <span class="n">persist_directory</span><span class="o">=</span><span class="n">persist_directory</span>
<span class="p">)</span>
<span class="n">vectordb</span><span class="p">.</span><span class="n">_collection</span><span class="p">.</span><span class="nf">count</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>1510
</code></pre></div></div> <h2 id="retrieval">Retrieval</h2> <p>Retrieval is the act of retrieving text chunks from our vector store, given an input prompt.</p> <p>Basic retrieval is performed by comparing the prompt embedding with those of the text chunks. More complex retrieval techniques involve calls to an LLM.</p> <h3 id="basic-retrieval">Basic retrieval</h3> <p>Let’s first test a retrieval technique based on similarity search in the vector store. Given a prompt, the procedure should return the most similar or relevant chunks in the vector database.</p> <p>The question below will be used as a test for everything else below in the notebook. It is related to reinforcement learning, an area in which I have a few hundred documents written on Obsidian. You can find more about the question <a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#value-functions">here</a> to see if our retrieval methods actually nail the answer.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">question</span> <span class="o">=</span> <span class="sh">"</span><span class="s">What is the definition of the action value function?</span><span class="sh">"</span>
</code></pre></div></div> <p>The first example of retrieval is <em>similarity search</em>, which will convert the prompt into an embedding vector and compute the cosine similarity between the prompt embedding and the embeddings of all chunks in the vector store, returning the <em>k</em> most similar chunks.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">retrieved_docs</span> <span class="o">=</span> <span class="n">vectordb</span><span class="p">.</span><span class="nf">similarity_search</span><span class="p">(</span><span class="n">question</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="k">for</span> <span class="n">doc</span> <span class="ow">in</span> <span class="n">retrieved_docs</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="sh">"</span><span class="se">\n\n</span><span class="s">---</span><span class="se">\n\n</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>The action-value function represents the expected return from a given state after taking a specific action and later following a specific policy.

$$q_{\pi}(s,a)=\mathbb{E}_{\pi}[G_t|S_t=s,A_t=a]$$

where $$G_t$$ is the Expected sum of future rewards.

---

A value function maps states, or state-action pairs, to expected returns.

- State-value function
- Action-value function

---

The state-value function represents the expected return from a given state, possibly under a given policy.

$$v(s)=\mathbb{E}[G_t|S_t=s]$$
$$v_{\pi}(s)=\mathbb{E}_{\pi}[G_t|S_t=s]$$

where $$G_t$$ is the Expected sum of future rewards.

---

The same goes for the Action-value function.

$$\begin{align}
q_*(s,a) &amp; = \sum_{s'}\sum_r p(s',r|s,a)[r + \gamma \sum_{a'} \pi_*(a'|s') q_*(s',a')] \\
       &amp; = \sum_{s'}\sum_r p(s',r|s,a)[r + \gamma \max_{a'} q_*(s',a')]
\end{align}$$

---

Let's say we have a policy $$\pi_1$$ that has a value function $$v_{\pi_1}$$. If we use $$v_{\pi_1}$$ to evaluate states but, instead of following $$\pi_1$$, we actually always select the actions that will take us to the future state $$s'$$ with highest $$v_{\pi_1}(s')$$, we will end up with a policy $$\pi_2$$ that is equal to or better than $$\pi_1$$.

---

$$\begin{align}
v_*(s) &amp; = \sum_a \pi_*(a|s) &amp; \sum_{s'}\sum_r p(s',r|s,a)[r + \gamma v_*(s')] \\
       &amp; = \max_a &amp; \sum_{s'}\sum_r p(s',r|s,a)[r + \gamma v_*(s')]
\end{align}$$
where $$\pi_*$$ is the Optimal policy.

The same goes for the Action-value function.

---

It's a function that dictates the probability the state will find itself in an arbitrary state $$s'$$ and the agent will receive reward $$r$$, given the current state the environment finds itself in, $$s$$, and the action chosen by the agent in $$s$$, depicted as $$a$$. It is usually denoted as $$p(s',r|s,a)$$.

Some properties of this function:

---

Policy evaluation is the task of finding the state-value function $$v_{\pi}$$, given the policy $$\pi$$. ^1b9b46

---
</code></pre></div></div> <h4 id="maximal-marginal-relevance-search">Maximal marginal relevance search</h4> <p>Plain similarity search has a drawback. It tends to recover chunks which are very similar or even identical, diminishing the overall amount of information present in the retrieved chunks.</p> <p>To solve this, LangChain provides a method called maximal marginal relevance search, which works by <em>“[…] finding the examples with the embeddings that have the greatest cosine similarity with the inputs, and then iteratively adding them while penalizing them for closeness to already selected examples.”</em> <a href="https://python.langchain.com/docs/modules/model_io/prompts/example_selector_types/mmr">[source]</a></p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">retrieved_docs</span> <span class="o">=</span> <span class="n">vectordb</span><span class="p">.</span><span class="nf">max_marginal_relevance_search</span><span class="p">(</span><span class="n">question</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="mi">8</span><span class="p">)</span>
<span class="k">for</span> <span class="n">doc</span> <span class="ow">in</span> <span class="n">retrieved_docs</span><span class="p">:</span>
    <span class="nf">print</span><span class="p">(</span><span class="n">doc</span><span class="p">.</span><span class="n">page_content</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="sh">"</span><span class="se">\n</span><span class="s">---</span><span class="se">\n</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>The action-value function represents the expected return from a given state after taking a specific action and later following a specific policy.

$$q_{\pi}(s,a)=\mathbb{E}_{\pi}[G_t|S_t=s,A_t=a]$$

where $$G_t$$ is the Expected sum of future rewards.
---
A value function maps states, or state-action pairs, to expected returns.

- State-value function
- Action-value function
---
A generalization of Sarsa which employs the n-step return for the action value function,

!n-step return#^205a30 ^68659e

This estimate is then used in the following update rule for the action-value of the state-action pair at time $$t$$.

$$Q_{t+n}(S_t, A_t) \doteq Q_{t+n-1}(S_t, A_t) + \alpha [G_{t:t+n} - \gamma^n Q_{t+n-1}(S_t, A_t)]$$ ^ca04db
---
- if the agent exploits without having a good estimate of the action-value function, it will most likely be locked in suboptimal behavior, not being able to gather information from unknown transitions which might bring it more return.
---
Some properties of this function:

It maps states and actions to states and rewards, so its cardinality is $$p:S \times R \times S \times A \to [0;1]$$

It is a probability, so the sum over all possible combinations of states and rewards must be one,
$$\sum_{s' \in S} \sum_{r \in R} p(s',r|s,a) = 1, \forall s \in S, a \in A(s)$$
---
# Factored value functions in cooperative multi-agent reinforcement learning

&lt;iframe width="560" height="315" src="https://www.youtube.com/embed/W_9kcQmaWjo?start=684" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen&gt;&lt;/iframe&gt;

VDN was the first one and the one I used in my Doctorate.
---
- Exploitation: select the greedy action with relation to the action-value function.
- Exploration: select a non-greedy action.
---
Given the following MDP:

!Pasted image 20210523192818.png

The Bellman equation allows the value function to be expressed and solved as a system of linear equations: ^c06dd9

!Bellman equation for the state-value function#^a65ad4
---
</code></pre></div></div> <h3 id="llm-backed-retrieval">LLM-backed retrieval</h3> <p>Some retrieval techniques require an underlying language model to be performed. The LLM may be used to, e.g. summarize or make chunks more coherent before returning them.</p> <h4 id="instantiating-the-llm">Instantiating the LLM</h4> <p>The LLM I chose is <a href="https://huggingface.co/Open-Orca/Mistral-7B-OpenOrca">Mistral-7B-OpenOrca</a>, provided by <a href="https://gpt4all.io/index.html">GPT4All</a>.</p> <ul> <li><a href="https://mistral.ai/news/announcing-mistral-7b/">Mistral 7B</a> is the best free and open 7 billion parameter LLM. It is also small enough to run on my GPU.</li> <li>The <a href="https://huggingface.co/datasets/Open-Orca/OpenOrca">OpenOrca dataset</a> is a conversation dataset.</li> <li>According to <a href="https://mistral.ai/product/">Mistral’s product website</a>, this model has an 8k context window, which we should consider when retrieving chunks for it to process.</li> </ul> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># !pip install gpt4all
# !pip install lark
# !wget https://gpt4all.io/models/gguf/mistral-7b-openorca.Q4_0.gguf -O models/my_little_llm.gguf
# !wget https://gpt4all.io/models/gguf/nous-hermes-llama2-13b.Q4_0.gguf -O models/my_little_llm.gguf
</span><span class="kn">from</span> <span class="n">langchain_community.llms.gpt4all</span> <span class="kn">import</span> <span class="n">GPT4All</span>

<span class="n">llm</span> <span class="o">=</span> <span class="nc">GPT4All</span><span class="p">(</span><span class="n">model</span><span class="o">=</span><span class="sh">"</span><span class="s">models/my_little_llm.gguf</span><span class="sh">"</span><span class="p">,</span> <span class="n">device</span><span class="o">=</span><span class="sh">"</span><span class="s">gpu</span><span class="sh">"</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>llama.cpp: using Vulkan on NVIDIA GeForce GTX 1070
</code></pre></div></div> <h4 id="self-query-retrieval">Self-query retrieval</h4> <p>Self-query is a technique in which an LLM is specifically prompted to output a <em>structured query</em>. It also allows it to take document/chunk metadata into consideration, as long as we describe each attribute in the metadata with a textual description.</p> <p>Under the hood, self-query performs some pretty convoluted modifications to the original prompt and I advise you look at the documentation to understand what’s going on. <a href="https://python.langchain.com/docs/modules/data_connection/retrievers/self_query#constructing-from-scratch-with-lcel">[Source]</a></p> <p>As we have seen when inspecting our splits, we can see that our data includes metadata taken from the file properties of Obsidian documents. We will go ahead and described them as attributes for the self-query retriever.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain.chains.query_constructor.base</span> <span class="kn">import</span> <span class="n">AttributeInfo</span>

<span class="n">metadata_field_info</span> <span class="o">=</span> <span class="p">[</span>
    <span class="nc">AttributeInfo</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">source</span><span class="sh">"</span><span class="p">,</span>
        <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">The name of the Markdown file that contained the chunk. If you ignore the .md extension, it is the name of the article the chunk came from.</span><span class="sh">"</span><span class="p">,</span>
        <span class="nb">type</span><span class="o">=</span><span class="sh">"</span><span class="s">string</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">),</span>
    <span class="nc">AttributeInfo</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">aliases</span><span class="sh">"</span><span class="p">,</span>
        <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">Other names for the article the chunk came from, if any.</span><span class="sh">"</span><span class="p">,</span>
        <span class="nb">type</span><span class="o">=</span><span class="sh">"</span><span class="s">string</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">),</span>
    <span class="nc">AttributeInfo</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">tags</span><span class="sh">"</span><span class="p">,</span>
        <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">A series of comma-separated tags that categorize the article the chunk came from. When a tags starts with </span><span class="sh">'</span><span class="s">area</span><span class="sh">'</span><span class="s">, it denotes a broad area of knowledge. When it starts with </span><span class="sh">'</span><span class="s">project</span><span class="sh">'</span><span class="s">, it describes a specific project with beginning and end.</span><span class="sh">"</span><span class="p">,</span>
        <span class="nb">type</span><span class="o">=</span><span class="sh">"</span><span class="s">string</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">),</span>
    <span class="nc">AttributeInfo</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">authors</span><span class="sh">"</span><span class="p">,</span>
        <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">When the document summarizes a scientific paper, this attribute holds a comma-separated list of author names.</span><span class="sh">"</span><span class="p">,</span>
        <span class="nb">type</span><span class="o">=</span><span class="sh">"</span><span class="s">string</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">),</span>
    <span class="nc">AttributeInfo</span><span class="p">(</span>
        <span class="n">name</span><span class="o">=</span><span class="sh">"</span><span class="s">year</span><span class="sh">"</span><span class="p">,</span>
        <span class="n">description</span><span class="o">=</span><span class="sh">"</span><span class="s">When the document summarizes a scientific paper, this attribute contains the year of the publication.</span><span class="sh">"</span><span class="p">,</span>
        <span class="nb">type</span><span class="o">=</span><span class="sh">"</span><span class="s">integer</span><span class="sh">"</span><span class="p">,</span>
    <span class="p">),</span>
<span class="p">]</span>
<span class="n">document_content_description</span> <span class="o">=</span> <span class="sh">"</span><span class="s">A collection of study notes in Markdown format written by a single author, mostly about artificial intelligence topics.</span><span class="sh">"</span>
</code></pre></div></div> <p>The self-query retriever can also be configured to use maximal marginal relevance search, as you can see in the <code class="language-plaintext highlighter-rouge">base_retriever</code> argument below.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain.retrievers.self_query.base</span> <span class="kn">import</span> <span class="n">SelfQueryRetriever</span>

<span class="n">retriever</span> <span class="o">=</span> <span class="n">SelfQueryRetriever</span><span class="p">.</span><span class="nf">from_llm</span><span class="p">(</span>
    <span class="n">llm</span><span class="o">=</span><span class="n">llm</span><span class="p">,</span>
    <span class="n">vectorstore</span><span class="o">=</span><span class="n">vectordb</span><span class="p">,</span>
    <span class="n">document_contents</span><span class="o">=</span><span class="n">document_content_description</span><span class="p">,</span>
    <span class="n">metadata_field_info</span><span class="o">=</span><span class="n">metadata_field_info</span><span class="p">,</span>
    <span class="n">base_retriever</span><span class="o">=</span><span class="n">vectordb</span><span class="p">.</span><span class="nf">as_retriever</span><span class="p">(</span><span class="n">search_type</span><span class="o">=</span><span class="sh">"</span><span class="s">mmr</span><span class="sh">"</span><span class="p">,</span> <span class="n">k</span><span class="o">=</span><span class="mi">8</span><span class="p">),</span>
<span class="p">)</span>
</code></pre></div></div> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">retriever</span><span class="p">.</span><span class="nf">invoke</span><span class="p">(</span><span class="n">question</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>[Document(page_content='!Pasted image 20231129031306.png', metadata={'created': 1708307272.9665868, 'date': '2023-11-29 01:34', 'last_accessed': 1708307272.9699202, 'last_modified': 1708307272.9665868, 'path': '/home/dodo/Documents/Obsidian/Single linkage.md', 'source': 'Single linkage.md', 'tags': 'area/ai/ml/clustering'}),
 Document(page_content='!Pasted image 20230317051147.png', metadata={'created': 1680667926.0942817, 'date': '2023-03-17 04:33', 'last_accessed': 1708267663.323892, 'last_modified': 1680667926.0942817, 'path': '/home/dodo/Documents/Obsidian/Comparing feature vectors in NLP.md', 'source': 'Comparing feature vectors in NLP.md', 'tags': 'area/ai/nlp project/nlp-spec'}),
 Document(page_content='!Pasted image 20230325081439.png', metadata={'created': 1679742881.9000912, 'last_accessed': 1708267661.4972079, 'last_modified': 1679742881.9000912, 'path': '/home/dodo/Documents/Obsidian/Text cleaning.md', 'source': 'Text cleaning.md'}),
 Document(page_content='!_attachments/Pasted image 20210523185724.png', metadata={'created': 1680669713.8148472, 'date': '2023-04-05 01:41', 'last_accessed': 1708267662.710553, 'last_modified': 1680669713.8148472, 'path': '/home/dodo/Documents/Obsidian/Iterative policy evaluation.md', 'source': 'Iterative policy evaluation.md', 'tags': 'area/ai/rl project/rl-spec'})]
</code></pre></div></div> <p>As we can see, without more informative metadata (or better preprocessing of the text documents), the retrieved chunks are not very useful. It only retrieved chunks related to figures.</p> <h3 id="contextual-compression-retrieval">Contextual compression retrieval</h3> <p>As a final test on retrieval, we will implement a <em>“contextual compression retriever”</em>.</p> <p>From the <a href="https://python.langchain.com/docs/modules/data_connection/retrievers/contextual_compression">LangChain documentation</a>:</p> <blockquote> <p>The Contextual Compression Retriever passes queries to the base retriever, takes the initial documents and passes them through the Document Compressor. The Document Compressor takes a list of documents and shortens it by reducing the contents of documents or dropping documents altogether.</p> </blockquote> <p>In our case:</p> <ul> <li>The base retriever will be a maximal marginal similarity search.</li> <li>The compressor will be Mistral-7b-OpenOrca.</li> </ul> <p>Our hope is that the small, irrelevant chunks returned by the self-query retriever will be dropped and more relevant chunks will be summarized and returned.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain.retrievers</span> <span class="kn">import</span> <span class="n">ContextualCompressionRetriever</span>
<span class="kn">from</span> <span class="n">langchain.retrievers.document_compressors</span> <span class="kn">import</span> <span class="n">LLMChainExtractor</span>

<span class="n">compressor</span> <span class="o">=</span> <span class="n">LLMChainExtractor</span><span class="p">.</span><span class="nf">from_llm</span><span class="p">(</span><span class="n">llm</span><span class="p">)</span>
<span class="n">compression_retriever</span> <span class="o">=</span> <span class="nc">ContextualCompressionRetriever</span><span class="p">(</span>
    <span class="n">base_compressor</span><span class="o">=</span><span class="n">compressor</span><span class="p">,</span> <span class="n">base_retriever</span><span class="o">=</span><span class="n">vectordb</span><span class="p">.</span><span class="nf">as_retriever</span><span class="p">(</span><span class="n">search_type</span><span class="o">=</span><span class="sh">"</span><span class="s">mmr</span><span class="sh">"</span><span class="p">)</span>
<span class="p">)</span>
</code></pre></div></div> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">compressed_docs</span> <span class="o">=</span> <span class="n">compression_retriever</span><span class="p">.</span><span class="nf">get_relevant_documents</span><span class="p">(</span><span class="n">question</span><span class="p">)</span>
<span class="n">compressed_docs</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/home/dodo/.anaconda3/envs/langsidian/lib/python3.12/site-packages/langchain/chains/llm.py:316: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.
  warnings.warn(
/home/dodo/.anaconda3/envs/langsidian/lib/python3.12/site-packages/langchain/chains/llm.py:316: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.
  warnings.warn(
/home/dodo/.anaconda3/envs/langsidian/lib/python3.12/site-packages/langchain/chains/llm.py:316: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.
  warnings.warn(
/home/dodo/.anaconda3/envs/langsidian/lib/python3.12/site-packages/langchain/chains/llm.py:316: UserWarning: The predict_and_parse method is deprecated, instead pass an output parser directly to LLMChain.
  warnings.warn(





[Document(page_content='The action-value function represents the expected return from a given state after taking a specific action and later following a specific policy.', metadata={'created': 1680669936.852964, 'date': '2023-04-05 01:45', 'last_accessed': 1708267660.0105264, 'last_modified': 1680669936.852964, 'path': '/home/dodo/Documents/Obsidian/Action-value function.md', 'source': 'Action-value function.md', 'tags': 'area/ai/rl project/rl-spec'}),
 Document(page_content='Action-value function', metadata={'created': 1680669672.8131003, 'date': '2023-04-05 01:41', 'last_accessed': 1708267659.7238567, 'last_modified': 1680669672.8131003, 'path': '/home/dodo/Documents/Obsidian/Value functions.md', 'source': 'Value functions.md', 'tags': 'area/ai/rl project/rl-spec'}),
 Document(page_content='*NO_OUTPUT*\n\nThe definition of the action value function is not mentioned in this context.', metadata={'created': 1633628586.5949209, 'date': '2021-03-02 23:01', 'last_accessed': 1708267661.2005382, 'last_modified': 1632030179.7187316, 'path': '/home/dodo/Documents/Obsidian/Factored value functions in cooperative multi-agent reinforcement learning.md', 'source': 'Factored value functions in cooperative multi-agent reinforcement learning.md', 'tags': 'None'}),
 Document(page_content='Action-Value Function Definition: Not mentioned in the context.', metadata={'created': 1680669515.4254303, 'date': '2023-04-05 01:38', 'last_accessed': 1708267661.453874, 'last_modified': 1680669515.4254303, 'path': '/home/dodo/Documents/Obsidian/Exploration-exploitation tradeoff.md', 'source': 'Exploration-exploitation tradeoff.md', 'tags': 'area/ai/rl project/rl-spec'})]
</code></pre></div></div> <p>These results seem much better than the previous ones, but they are still just a collection of chunks. When interacting with LLMs and chatbots in general, we expect a more direct response.</p> <h2 id="question-answering-using-llms-and-rag">Question-answering using LLMs and RAG</h2> <p>In this example, we will perform retrieval augmented generation for question-answering in an Obsidian document database.</p> <p>To summarize what we already have for this step:</p> <ol> <li>Our documents have been loaded and preprocessed.</li> <li>Chunks have been split from the documents, embedded and stored in the vector store.</li> <li>An LLM has been successfully loaded into memory.</li> </ol> <h3 id="plain-retrieval-qa">Plain retrieval Q&amp;A</h3> <p>This method of Q&amp;A uses the prompt to find relevant chunks in the vector store. These chunks are called the <em>context</em> of the prompt and they are concatenated to the prompt, which is then passed directly to the LLM.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain.chains</span> <span class="kn">import</span> <span class="n">RetrievalQA</span>

<span class="n">qa_chain</span> <span class="o">=</span> <span class="n">RetrievalQA</span><span class="p">.</span><span class="nf">from_chain_type</span><span class="p">(</span>
    <span class="n">llm</span><span class="o">=</span><span class="n">llm</span><span class="p">,</span> <span class="n">retriever</span><span class="o">=</span><span class="n">vectordb</span><span class="p">.</span><span class="nf">as_retriever</span><span class="p">(</span><span class="n">search_type</span><span class="o">=</span><span class="sh">"</span><span class="s">mmr</span><span class="sh">"</span><span class="p">)</span>
<span class="p">)</span>
</code></pre></div></div> <p>We can see which arguments the chain expects by inspecting the input_keys <code class="language-plaintext highlighter-rouge">list</code>.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">qa_chain</span><span class="p">.</span><span class="n">input_keys</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>['query']
</code></pre></div></div> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">result</span> <span class="o">=</span> <span class="nf">qa_chain</span><span class="p">({</span><span class="sh">"</span><span class="s">query</span><span class="sh">"</span><span class="p">:</span> <span class="n">question</span><span class="p">})</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/home/dodo/.anaconda3/envs/langsidian/lib/python3.12/site-packages/langchain_core/_api/deprecation.py:117: LangChainDeprecationWarning: The function `__call__` was deprecated in LangChain 0.1.0 and will be removed in 0.2.0. Use invoke instead.
  warn_deprecated(
</code></pre></div></div> <p>The result of prompting the overall system can be seen below. If you remember the definition of the action-value function <a href="https://spinningup.openai.com/en/latest/spinningup/rl_intro.html#value-functions">[source]</a>, our Q&amp;A bot has pretty much nailed it!</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">result</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{'query': 'What is the definition of the action value function?',
 'result': ' The action-value function represents the expected return from a given state after taking a specific action and later following a specific policy.'}
</code></pre></div></div> <p>Under the hood, the <code class="language-plaintext highlighter-rouge">RetrievalQA</code> object uses a prompt template into which it replaces the context and the question before sending the full text prompt to the LLM. We can see it by inspecting the object’s graph.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">qa_chain</span><span class="p">.</span><span class="nf">get_graph</span><span class="p">().</span><span class="n">nodes</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>{'7eac904b44594e20852d8f0519ef0c3e': Node(id='7eac904b44594e20852d8f0519ef0c3e', data=&lt;class 'pydantic.v1.main.ChainInput'&gt;),
 '8e824ec8c0654d0db3b83b56bd66b619': Node(id='8e824ec8c0654d0db3b83b56bd66b619', data=RetrievalQA(combine_documents_chain=StuffDocumentsChain(llm_chain=LLMChain(prompt=PromptTemplate(input_variables=['context', 'question'], template="Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:"), llm=GPT4All(model='models/my_little_llm.gguf', device='gpu', client=&lt;gpt4all.gpt4all.GPT4All object at 0x776da5594320&gt;)), document_variable_name='context'), retriever=VectorStoreRetriever(tags=['Chroma', 'HuggingFaceEmbeddings'], vectorstore=&lt;langchain_community.vectorstores.chroma.Chroma object at 0x776cf1b45be0&gt;, search_type='mmr'))),
 '4b55a6602f9542fe8d583ac66c6ae722': Node(id='4b55a6602f9542fe8d583ac66c6ae722', data=&lt;class 'pydantic.v1.main.ChainOutput'&gt;)}
</code></pre></div></div> <h3 id="retrieval-qa-with-custom-prompt-template">Retrieval Q&amp;A with custom prompt template</h3> <p>The example below shows how to edit the prompt template used by the chain, albeit, in this case, with limited success. This is due to the limited performance of the LLM being used.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">langchain.prompts</span> <span class="kn">import</span> <span class="n">PromptTemplate</span>

<span class="c1"># Build prompt
</span><span class="n">template</span> <span class="o">=</span> <span class="sh">"""</span><span class="s">Use the following pieces of context to answer the question at the end. If you don</span><span class="sh">'</span><span class="s">t know the answer, just say that you don</span><span class="sh">'</span><span class="s">t know, don</span><span class="sh">'</span><span class="s">t try to make up an answer. At the end of the response, say </span><span class="se">\"</span><span class="s">over and out</span><span class="se">\"</span><span class="s">.
{context}
Question: {question}
Helpful Answer:</span><span class="sh">"""</span>
<span class="n">qa_chain_prompt</span> <span class="o">=</span> <span class="n">PromptTemplate</span><span class="p">.</span><span class="nf">from_template</span><span class="p">(</span><span class="n">template</span><span class="p">)</span>
<span class="c1"># Run chain
</span><span class="n">qa_chain</span> <span class="o">=</span> <span class="n">RetrievalQA</span><span class="p">.</span><span class="nf">from_chain_type</span><span class="p">(</span>
    <span class="n">llm</span><span class="p">,</span>
    <span class="n">retriever</span><span class="o">=</span><span class="n">vectordb</span><span class="p">.</span><span class="nf">as_retriever</span><span class="p">(</span><span class="n">search_type</span><span class="o">=</span><span class="sh">"</span><span class="s">mmr</span><span class="sh">"</span><span class="p">),</span>
    <span class="n">return_source_documents</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span>
    <span class="n">chain_type_kwargs</span><span class="o">=</span><span class="p">{</span><span class="sh">"</span><span class="s">prompt</span><span class="sh">"</span><span class="p">:</span> <span class="n">qa_chain_prompt</span><span class="p">},</span>
<span class="p">)</span>
</code></pre></div></div> <p>Let’s ask a few questions to our Q&amp;A bot and render the output as some nice Markdown.</p> <p>Note that we can also output the documents that were retrieved during RAG and used to compose the answer, but that would pollute the output too much, so I left it commented out.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">IPython.display</span> <span class="kn">import</span> <span class="n">Markdown</span>

<span class="n">questions</span> <span class="o">=</span> <span class="p">[</span>
    <span class="sh">"</span><span class="s">Given me the equation for the action value function update.</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">What is the overall architecture of the Deep Q-Networks?</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">What is the difference between causal language modelling and masked language modelling?</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">What is zero-shot learning?</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">Explain to me the concept of bucketing in RNNs.</span><span class="sh">"</span><span class="p">,</span>
    <span class="sh">"</span><span class="s">What is a named entity in the concept of NLP?</span><span class="sh">"</span><span class="p">,</span>
<span class="p">]</span>

<span class="k">for</span> <span class="n">q</span> <span class="ow">in</span> <span class="n">questions</span><span class="p">:</span>
    <span class="n">result</span> <span class="o">=</span> <span class="nf">qa_chain</span><span class="p">({</span><span class="sh">"</span><span class="s">query</span><span class="sh">"</span><span class="p">:</span> <span class="n">q</span><span class="p">})</span>

    <span class="nf">display</span><span class="p">(</span><span class="nc">Markdown</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">**Question: </span><span class="si">{</span><span class="n">result</span><span class="p">[</span><span class="sh">"</span><span class="s">query</span><span class="sh">"</span><span class="p">]</span><span class="si">}</span><span class="s">**</span><span class="se">\n\n</span><span class="s"> Answer: </span><span class="si">{</span><span class="n">result</span><span class="p">[</span><span class="sh">'</span><span class="s">result</span><span class="sh">'</span><span class="p">]</span><span class="si">}</span><span class="sh">"</span><span class="p">))</span>
    <span class="c1"># source_docs = "\n\n".join(d.page_content for d in result["source_documents"])
</span>    <span class="c1"># print(
</span>    <span class="c1">#     f"Source documents\n\n{source_docs}"
</span>    <span class="c1"># )
</span></code></pre></div></div> <p><strong>Question: Given me the equation for the action value function update.</strong></p> <p>Answer: The equation for the action-value function update is given by:</p> \[q_{\pi}(s,a) = R(s,a) + \mathbb{E} \left[ \gamma V_\pi (s') | s' \in S' \right]\] <p>where \(R(s,a)\) is the reward received when taking action a in state s and \(\gamma\) is the discount factor.</p> <p><strong>Question: What is the overall architecture of the Deep Q-Networks?</strong></p> <p>Answer: The overall architecture of a Deep Q-Network (DQN) consists of an input layer, multiple hidden layers with nonlinear activation functions, and an output layer. It uses experience replay to store past experiences for training purposes, and employs target networks to stabilize the learning process. over and out</p> <p><strong>Question: What is the difference between causal language modelling and masked language modelling?</strong></p> <p>Answer: Causal language modeling refers to a method where the model predicts the next token in a sequence based on the previous tokens. In contrast, masked language modeling involves randomly masking some tokens during training time and then trains the model to reconstruct the original text by predicting the masked tokens.</p> <p><strong>Question: What is zero-shot learning?</strong></p> <p>Answer: Zero-shot learning refers to a model’s ability to perform new tasks without being explicitly trained on those specific tasks or examples. In the context of large language models, it means that an AI can execute new tasks without needing any explicit training data for those tasks.</p> <p><strong>Question: Explain to me the concept of bucketing in RNNs.</strong></p> <p>Answer: Bucketing in RNNs refers to grouping or organizing input sequences into fixed-sized groups, called “buckets”, before processing them with an RNN model. This technique helps improve training efficiency and reduce padding by ensuring that each bucket contains a sufficient amount of randomness and variability while preventing it from being too large so as not to introduce excessive padding.</p> <p><strong>Question: What is a named entity in the concept of NLP?</strong></p> <p>Answer: In the context of Natural Language Processing (NLP), a named entity refers to a real-world object that can be denoted with a proper name. Examples are a person, location, organization, product. It can be abstract or have a physical existence.</p> <p>In some answers, the model has actually followed the instructions from the new prompt, but we need a much more powerful LLM, or the employment of techniques such as few-shot learning, to get better instruction-following results.</p> <h2 id="conclusions">Conclusions</h2> <p>This notebook presented a proof-of-concept on how to create a question-answering bot powered by an LLM and with knowledge extracted from actual documents, more specifically, a collection of notes from Obsidian.</p> <p>We were able to run all experiments locally, using a 7th gen i7, an NVIDIA GTX 1070 and 32 GBs of RAM.</p> <p>We were also introduced to many concepts on the road to building this Q&amp;A bot, such as:</p> <ol> <li>Document loading</li> <li>Text data cleaning using regex</li> <li>Splitting of Markdown documents into text chunks</li> <li>Sentence embeddings</li> <li>Vector stores</li> <li>Similarity search using cosine similarity between embedding vectors</li> <li>maximal marginal relevance search</li> <li>Self-query retrieval</li> <li>Contextual compression retrieval</li> <li>Question-answering with retrieval augmented generation</li> <li>Question-answering with retrieval augmented generation and custom templates</li> </ol> <p>In future work, let’s build an actual chatbot that remembers previous answers and can keep up a lengthier conversation.</p>]]></content><author><name></name></author><category term="nlp"/><category term="llms"/><category term="nlp"/><category term="python"/><category term="neural-networks"/><summary type="html"><![CDATA[Introduction]]></summary></entry><entry><title type="html">Configuring Visual Studio Code for LaTeX</title><link href="https://douglasrizzo.github.io/blog/2021/06/configuring-vscode-for-latex/" rel="alternate" type="text/html" title="Configuring Visual Studio Code for LaTeX"/><published>2021-06-11T00:00:00+00:00</published><updated>2021-06-11T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2021/06/configuring-vscode-for-latex</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2021/06/configuring-vscode-for-latex/"><![CDATA[<p><a href="https://code.visualstudio.com/">VS Code</a> has very poor LaTeX support out-of-the-box. Here I list useful extensions and other software that will transform VS Code into a much more power LaTeX editor. They also do not conflict with each other, which is great.</p> <h2 id="getting-it-out-of-the-way-latex-workshop">Getting it out of the way: LaTeX Workshop</h2> <p>While I have used LaTeX Workshop for a long time, I started experiencing a few issues with it that, over time, got really annoying. The main issue is simply <a href="https://github.com/James-Yu/LaTeX-Workshop/issues/1193">the Enter key not working</a>, which was then replaced by <a href="https://github.com/James-Yu/LaTeX-Workshop/issues/903">a substantial delay between pressing the Enter key and actually inserting a new line character</a>. Fixing one apparently introduced the other, so, after many tries, I just gave up on LaTeX Workshop.</p> <h2 id="what-i-use-now">What I use now</h2> <ul> <li>Code completion: <a href="https://marketplace.visualstudio.com/items?itemName=efoerster.texlab">TeXLab VS Code extension</a>. It depends on another program called <a href="https://texlab.netlify.app/">TeXLab</a>, but the extension usually installs it automatically.</li> <li>Syntax highlighting <a href="https://marketplace.visualstudio.com/items?itemName=vomout.latex-syntax">Rich LaTeX syntax highlighting (for use with Texlab)</a>.</li> <li>Grammar checking: <a href="https://marketplace.visualstudio.com/items?itemName=valentjn.vscode-ltex">LTeX</a>. Be sure to check the <a href="https://valentjn.github.io/vscode-ltex/docs/settings.html">documentation</a> to learn how to configure the extension to check different languages.</li> <li>PDF visualization: If TeXLab has not worked out for you when opening PDF files, you can use an extension called <a href="https://marketplace.visualstudio.com/items?itemName=sandcastle.vscode-open">Open</a>, which opens a file in its default application.</li> </ul> <p>The TeXLab VS Code extension also provides other useful features, as long as the appropriate programs are installed and in your Linux <code class="language-plaintext highlighter-rouge">PATH</code> (or whatever the equivalent in Mac/Windows is). These assorted programs are usually included in TeX Live, but can be installed through your distribution’s package manager, if you are on Linux.</p> <ul> <li>LaTeX formatting (with <code class="language-plaintext highlighter-rouge">latexindent</code>)</li> <li>Compilation via the F5 shortcut (with <code class="language-plaintext highlighter-rouge">latexmk</code>)</li> <li>Linting (with <code class="language-plaintext highlighter-rouge">chktex</code>)</li> <li>Opening the final PDF file with a shortcut (through the <a href="https://github.com/latex-lsp/texlab/blob/master/docs/previewing.md">forward search</a> option)</li> </ul>]]></content><author><name></name></author><category term="tools"/><category term="vscode"/><category term="tutorial"/><summary type="html"><![CDATA[VS Code has very poor LaTeX support out-of-the-box. Here I list useful extensions and other software that will transform VS Code into a much more power LaTeX editor. They also do not conflict with each other, which is great.]]></summary></entry><entry><title type="html">Resources to self-study mathematics for machine learning</title><link href="https://douglasrizzo.github.io/blog/2021/06/mathematics-self-study/" rel="alternate" type="text/html" title="Resources to self-study mathematics for machine learning"/><published>2021-06-11T00:00:00+00:00</published><updated>2021-06-11T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2021/06/mathematics-self-study</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2021/06/mathematics-self-study/"><![CDATA[<blockquote> <p>Two plus two is four, minus one, that’s three. Quick maths.</p> <p><a href="https://youtu.be/3M_5oYU-IsU?t=63">Michael Dapaah</a></p> </blockquote> <h2 id="introduction">Introduction</h2> <p>When I started my PhD, I didn’t know at first if my research would take me in a path whose foundations I was comfortable with, such as algorithms, logic and other discrete areas, or if fate would take me towards the more mathematical path. As I started to get really interested in the applications of neural networks for reinforcement learning, I realized little by little that I would not only need to remember all the mathematics I had learned before in my life, but also learn and get comfortable with some new stuff.</p> <p>In this article, I go over:</p> <ul> <li>what topics I’ve been studying;</li> <li>in which order I study them;</li> <li>what material worked for me;</li> <li>where to find them online (the free ones, at least);</li> <li>which software, online services and apps I use;</li> <li>where to find online communities to post questions and answers and to study together in real time;</li> <li>where I failed in my studies;</li> <li>some final tips;</li> <li>links to more resources.</li> </ul> <h2 id="study-areas">Study areas</h2> <h3 id="algebra-and-pre-calculus">Algebra and pre-calculus</h3> <p>I recommend the <a href="https://jamesbrennan.org/algebra/">free algebra book by James Brennan</a> and the <a href="https://www.stitz-zeager.com/">free precalculus book by Stitz and Zaeger</a>, which I found out about in the very helpful <a href="https://reddit.com/r/learnmath">/r/learnmath</a> subreddit. My recommendation would be to evaluate which topics you remember and just skim over them, while giving yourself more time over the stuff you don’t remember or have never learned.</p> <p>Personally, I made a lot of progress by just following both books until I felt I was comfortable with my knowledge. I tried not to skip anything, but I also felt like I could work fast as I had already learned most of this stuff before.</p> <h3 id="calculus">Calculus</h3> <p>To study calculus, I used the <a href="https://stewartcalculus.com/media/16_home.php">books by Stewart</a>, 8th edition. I knew I was prepared to start calculus when I had studied enough algebra to fulfill the prerequisites at the start of the book. I also worked through the two review lists available in Stewart’s website <a href="https://stewartcalculus.com/data/CALCULUS_8E/upfiles/6e_reviewofalgebra.pdf">[1]</a> <a href="https://stewartcalculus.com/data/CALCULUS_8E/upfiles/6e_reviewofanalgeom.pdf">[2]</a>. Those lists helped me to prioritize what I needed to focus on my aforementioned precalculus quest.</p> <h3 id="linear-algebra">Linear Algebra</h3> <p>I decided to start studying linear algebra alongside calculus. I had an easier time with linear algebra as I already had some familiarity with matrix operations, not only because I was already working with neural networks for quite some time, but I also implemented <a href="douglasrizzo.github.io/matrix">my own matrix class in C++</a> at one point.</p> <p>I started with a <a href="https://www.google.com.br/books/edition/Algebra_linear/M8CNGwAACAAJ?hl=en">Brazilian undergrad text book from 1986</a>, but also searched many concepts on YouTube, since I did not get the intuition behind some of them. I ended up ditching the book after getting acquainted with <a href="https://www.amazon.com/gp/product/B019EB9S4O/">Larson’s book</a>, which presented the material in a much nore contemporary fashion.</p> <h4 id="advanced-linear-algebra">Advanced Linear Algebra</h4> <p>I haven’t gotten here yet, but after learning all the basic stuff about matrices, vector spaces, linear transforms and eigenthingies, I was recommended the book <a href="https://www.amazon.com/Linear-Algebra-Right-Sheldon-Axler/dp/3319110799/">Linear Algebra Done Right</a>, by Sheldon Axler to move on to more advanced stuff.</p> <h2 id="software-and-apps">Software and apps</h2> <ul> <li><strong>Solvers:</strong> These are services that do things like simplifying expressions, solving for \(x\), finding derivatives, minima and maxima values of functions and so on. You name it, they do it. Just be careful that, sometimes, the answers are either more convoluted than they need to be, or simpler than you’d want them to be. <ul> <li><a href="https://www.wolframalpha.com/">Wolfram Alpha</a> is in this category. Instead of paying for a subscription to the website, a cheaper solution is to buy <a href="https://play.google.com/store/apps/details?id=com.wolfram.android.alpha">the smartphone app</a>, which is a one-time purchase that gives you the coveted “step-by-step solution” functionality.</li> <li>A free alternative which is equally impressive is <a href="https://math.microsoft.com/">Microsoft Math Solver</a>, which also has a more user-friendly <a href="https://play.google.com/store/apps/details?id=com.microsoft.math">mobile app</a>.</li> </ul> </li> <li><strong>Graphical calculators:</strong> you’re gonna need these ones often, to visualize functions, derivatives, systems of equations etc. I recommend the Desmos Graphical Calculator, a very famous graphical calculator, which is freely available <a href="https://www.desmos.com/calculator">online</a> and as <a href="https://play.google.com/store/apps/details?id=com.desmos.calculator">an app</a>. It only works in two dimensions, I don’t really know if there is anything fancier than that.</li> <li><strong>Actual calculators:</strong> On Linux, I use <a href="http://speedcrunch.org/">SpeedCrunch</a> for <a href="https://youtu.be/3M_5oYU-IsU?t=63">quick maths</a> or <a href="https://qalculate.github.io/">Qalculate!</a> for more symbolic stuff (with fractions, units of measurement etc). On mobile, I’d recommend <a href="https://play.google.com/store/apps/details?id=com.desmos.scientific">Desmos Scientific Calculator</a>. I know some people like to use “calculator simulators” but I haven’t had the need for that.</li> <li><strong>Linear algebra special:</strong> instead on depending on MATLAB or some other obnoxious monolithic proprietary software, you can represent systems of linear equations as matrices in Python using <a href="https://numpy.org/">NumPy</a> and manipulate/solve them using <a href="https://numpy.org/devdocs/reference/routines.linalg.html"><code class="language-plaintext highlighter-rouge">numpy.linalg</code></a>. You can load <code class="language-plaintext highlighter-rouge">.mat</code> files into Python variables using <a href="https://docs.scipy.org/doc/scipy/reference/generated/scipy.io.loadmat.html">SciPy’s <code class="language-plaintext highlighter-rouge">loadmat</code> function</a>.</li> </ul> <h2 id="online-communities">Online communities</h2> <p>It came a point in which I started having the kind of questions that I couldn’t quite google my way to the answer. When I started to look for a place to post my questions, I found the extremely active and welcoming <a href="https://reddit.com/r/learnmath">/r/learnmath</a> subreddit. The people there are really nice and welcoming of noobs and they are a lot less strict than other sites, such as the Math Stack Exchange.</p> <p>Another place I suggest people to look are Discord servers, where people gather to talk about homework. An example is <a href="https://discord.gg/USVc7XX">Homework Help</a>. There are also study servers on Discord in which people can keep you company in mute video calls. I highly recommend the <a href="https://discord.gg/s9tEhQPw8A">Study Lions</a>, but there are others.</p> <p>Overall, my advice with regards to communities is to both <strong>seek and provide help</strong>. Seeing people ask questions to which I knew the answer to made me realize how much I had actually learned in my journey, which really motivated me. Also, I could help a random stranger online, which is nice.</p> <h2 id="my-failures">My failures</h2> <p>Humble time. Since I didn’t know where to start, I decided to enroll in online university courses and let the lectures guide me. I had had a great experience with Coursera and the machine learning course by Andrew Ng, so I thought I’d have an equally positive experience with Coursera’s math courses<sup id="fnref:calc-courses"><a href="#fn:calc-courses" class="footnote" rel="footnote" role="doc-noteref">1</a></sup>.</p> <p>However, unlike the previous courses I took, I couldn’t watch the lectures or complete the assignments before or after the correct dates, which really frustrated me.</p> <p>Another problem I faced was that I just couldn’t follow the professors in some of the lectures. Sometimes, the exercises after a lesson seemed to have nothing to do with the lesson itself. Since I had no other material to follow, I felt stuck in some lessons and couldn’t meet the deadlines.</p> <h2 id="final-thoughts">Final thoughts</h2> <ul> <li> <p><strong>Don’t force it:</strong> Studying mathematics ended up becoming a hobby of mine, one that I could spend an entire day doing, after I had started. There were days that I would eat up over 20 pages of a book, a pretty decent number if you ask me, since I’d be able to end a 400 page book in 20 days (not that I did that). My main problem was, and still is, consistency. I can’t really do the whole “study everyday for 30 minutes” thing. I usually studied for the whole day, twice a week.</p> <p>I’ll admit I did not study any of the books from cover to cover and I am still working through them, but I never felt hindered or delayed by the method I chose to study mathematics. My only limitations are time, since I have other responsibilities, and motivation.</p> </li> <li> <p><strong>Find the format that is best for you:</strong> since I did very well in online AI courses <a href="https://www.coursera.org/verify/BJWU9J3F9J4X">[1]</a> <a href="http://coursera.org/verify/specialization/7YLWXWJ5GUKJ">[2]</a>, I thought the same would be true for online math courses. However, when it came to mathematics, I felt like books were a much better medium, as they present the material in both a rigorous and linear fashion, delving into the theory and definitions and following up with lots of examples and exercises which could mostly be completed with the material presented right before. Text books are also good when I just wanted to review some old algebra, in which case I am able to quicly skip to whatever concept I am interested in, while videos would be much harder to sift through.</p> </li> <li> <p><strong>YouTube is your friend:</strong> I tend to forget basic stuff very often, such as how to complete the square, trigonometric identities (<a href="https://en.wikipedia.org/wiki/List_of_trigonometric_identities">there are lots of them</a>) or the binomial theorem. In these cases, looking up a YouTube video is much faster than searching for what you need in books. Math videos usually go directly to the point and you don’t waste any time.</p> </li> </ul> <h2 id="more-resources-and-moving-forward">More resources and moving forward</h2> <p>This video my the Math Sorcerer lists books from every area of Mathematics, starting from basic logic and algebra and going all the way up to the crazy stuff.</p> <iframe width="560" height="315" src="https://www.youtube.com/embed/pTnEG_WGd2Q" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe> <p>This video by Aleph 0 has some book recommendations for undergraduate level courses in pure mathematics, with accompanying video lectures on YouTube.</p> <iframe width="560" height="315" src="https://www.youtube.com/embed/fo-alw2q-BU" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe> <hr/> <div class="footnotes" role="doc-endnotes"> <ol> <li id="fn:calc-courses"> <p>I enrolled in the UC Irvine precalculus course (which is not available on Coursera anymore, but can be found <a href="https://www.math.uci.edu/node/22608">here</a>) and later, in the University of Ohio calculus course (which also is not available anymore, but a few pointers to where the material is currently available are <a href="https://mooculus.osu.edu/lectures">[link]</a> <a href="https://www.youtube.com/user/kisonecat/playlists">[link]</a> <a href="https://www.coursera.org/instructor/jimfowler">[link]</a>). <a href="#fnref:calc-courses" class="reversefootnote" role="doc-backlink">&#8617;</a></p> </li> </ol> </div>]]></content><author><name></name></author><category term="study-guide"/><category term="mathematics"/><category term="self-study"/><summary type="html"><![CDATA[Two plus two is four, minus one, that’s three. Quick maths. Michael Dapaah]]></summary></entry><entry><title type="html">Zotero tips and tricks</title><link href="https://douglasrizzo.github.io/blog/2021/06/zotero-tips/" rel="alternate" type="text/html" title="Zotero tips and tricks"/><published>2021-06-11T00:00:00+00:00</published><updated>2021-06-11T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2021/06/zotero-tips</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2021/06/zotero-tips/"><![CDATA[<p><strong>tl;dr:</strong> <a href="https://www.zotero.org/"><strong>Zotero</strong></a> is great but it lacks good cloud sync support and a way to make a giant .bib file available for referencing. You can get the first with the <a href="http://zotfile.com/"><strong>Zotfile</strong></a> addon, pointing its PDF directory somewhere inside your cloud sync directory. You can get the second with the <a href="https://retorque.re/zotero-better-bibtex/"><strong>Better BibTeX</strong></a> addon, by exporting a <code class="language-plaintext highlighter-rouge">.bib</code> file which is always kept updated.</p> <h2 id="background">Background</h2> <p><a href="https://www.zotero.org/"><strong>Zotero</strong></a> is a great reference manager that has incorporated lots of much needed features along the years. Two things that I feel Zotero is still missing is</p> <ul> <li>good cloud sync support, so you can keep as many PDF files in your libraries without going over the measly 300 MB quota it gives;</li> <li>a central <code class="language-plaintext highlighter-rouge">.bib</code> file which can be referenced in all my projects.</li> </ul> <p>Here, I teach you how to circumvent these problems with two addons.</p> <h2 id="cloud-sync-with-zotfile">Cloud sync with Zotfile</h2> <p><a href="http://zotfile.com/"><strong>Zotfile</strong></a> is an addon that helps in managing PDF files inside Zotero. It allows for automatic and batch moving and renaming of file attachments.</p> <p>In order to sync all your PDF files among multiple computers, you can point Zotfile’s “PDF directory” setting into a folder inside your cloud sync service of choice (Mega, Dropbox, Google Drive, OneDrive etc.) and configure the addon to automatically move all new attachments to this folder. Zotero will then only keep links to these files in its database and will synchronize only these links, while the files themselves will be synchronized by your cloud sync application.</p> <h2 id="central-up-to-date-bib-database-with-better-bibtex">Central up-to-date bib database with Better BibTeX</h2> <p><a href="https://www.jabref.org/"><strong>JabRef</strong></a> introduced me to the as-of-yet unknown habit of keeping a single giant <code class="language-plaintext highlighter-rouge">.bib</code> file, which I would just link all my papers to and use the autocomplete function of my TeX editor of choice to search for entry keys.</p> <p>To emulate this behavior in Zotero, there is an addon called <a href="https://retorque.re/zotero-better-bibtex/"><strong>Better Bibtex</strong></a>. It allows me to export my entire library into a <code class="language-plaintext highlighter-rouge">.bib</code> file, which is then kept updated as I change information in my Zotero library. I actually kept two <code class="language-plaintext highlighter-rouge">.bib</code> files, one in BibTeX format for all my papers, and the other in BibLaTeX format, for my thesis.</p>]]></content><author><name></name></author><category term="tools"/><category term="zotero"/><category term="tutorial"/><summary type="html"><![CDATA[tl;dr: Zotero is great but it lacks good cloud sync support and a way to make a giant .bib file available for referencing. You can get the first with the Zotfile addon, pointing its PDF directory somewhere inside your cloud sync directory. You can get the second with the Better BibTeX addon, by exporting a .bib file which is always kept updated.]]></summary></entry><entry><title type="html">Detecting soccer balls with reduced neural networks</title><link href="https://douglasrizzo.github.io/blog/2021/02/detecting-soccer-balls-with-reduced-neural-networks/" rel="alternate" type="text/html" title="Detecting soccer balls with reduced neural networks"/><published>2021-02-21T00:00:00+00:00</published><updated>2021-02-21T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2021/02/detecting-soccer-balls-with-reduced-neural-networks</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2021/02/detecting-soccer-balls-with-reduced-neural-networks/"><![CDATA[<p>I was fortunate to have <a href="https://link.springer.com/article/10.1007/s10846-021-01336-y">published a paper</a> in the Journal of Intelligent &amp; Robotic Systems. While its <a href="https://arxiv.org/abs/2009.13684">preprint on arxiv</a> will remain there, I am allowed to host the post-review, pre-published version, which was greatly expanded, on my personal website . ou can find it below.</p> <iframe title="The Paper" width="100%" src="/assets/pdf/jint2021-aam.pdf" height="1015"></iframe>]]></content><author><name></name></author><category term="publications"/><category term="object-detection"/><category term="neural-networks"/><category term="research-paper"/><summary type="html"><![CDATA[I was fortunate to have published a paper in the Journal of Intelligent &amp; Robotic Systems. While its preprint on arxiv will remain there, I am allowed to host the post-review, pre-published version, which was greatly expanded, on my personal website . ou can find it below.]]></summary></entry><entry><title type="html">Razões para deep reinforcement learning não funcionar</title><link href="https://douglasrizzo.github.io/blog/2021/02/razoes-para-deep-reinforcement-learning-nao-funcionar/" rel="alternate" type="text/html" title="Razões para deep reinforcement learning não funcionar"/><published>2021-02-19T00:00:00+00:00</published><updated>2021-02-19T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2021/02/razoes-para-deep-reinforcement-learning-nao-funcionar</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2021/02/razoes-para-deep-reinforcement-learning-nao-funcionar/"><![CDATA[<p>Essa é uma compilação de textos que eu encontrei na internet em momentos de frustração com meu trabalho. Eu os resumi e traduzi para compartilhar com as pessoas sempre que me perguntarem porque trabalhar com DRL é uma desgraça.</p> <ul> <li><a href="#comentários-do-karpathy">Comentários do Karpathy</a></li> <li><a href="#texto-lessons-learned-reproducing-a-deep-reinforcement-learning-paper">Texto: Lessons Learned Reproducing a Deep Reinforcement Learning Paper</a></li> <li><a href="#texto-deep-reinforcement-learning-doesnt-work-yet">Texto: Deep Reinforcement Learning Doesn’t Work Yet</a></li> </ul> <h2 id="comentários-do-karpathy">Comentários do Karpathy</h2> <p>O trecho abaixo é um comentário do Andrej Karpathy, da Tesla, <a href="https://news.ycombinator.com/item?id=13519044">neste link</a>.</p> <blockquote> <p>If it makes you feel any better, I’ve been doing this for a while and it took me last ~6 weeks to get a from-scratch policy gradients implementation to work 50% of the time on a bunch of RL problems. And I also have a GPU cluster available to me, and a number of friends I get lunch with every day who’ve been in the area for the last few years. Also, what we know about good CNN design from supervised learning land doesn’t seem to apply to reinforcement learning land, because you’re mostly bottlenecked by credit assignment / supervision bitrate, not by a lack of a powerful representation. Your ResNets, batchnorms, or very deep networks have no power here. SL wants to work. Even if you screw something up you’ll usually get something non-random back. RL must be forced to work. If you screw something up or don’t tune something well enough you’re exceedingly likely to get a policy that is even worse than random. And even if it’s all well tuned you’ll get a bad policy 30% of the time, just because. Long story short your failure is more due to the difficulty of deep RL, and much less due to the difficulty of “designing neural networks”.</p> </blockquote> <h2 id="texto-lessons-learned-reproducing-a-deep-reinforcement-learning-paper">Texto: Lessons Learned Reproducing a Deep Reinforcement Learning Paper</h2> <p>Fonte: <a href="http://amid.fish/reproducing-deep-rl">http://amid.fish/reproducing-deep-rl</a></p> <ol> <li> <p>Ao trabalhar com métodos programados no computador, nós frequentemente nos deparamos com problemas cuja solução não é óbvia. Quando o método não necessita de treinamento, é mais rápido e fácil ter várias ideias do que pode solucionar um problema e testar tudo em segundos do que realmente pensar na origem do problema. No caso de um algoritmo de RL, cada novo teste leva um ou mais dias, então é necessário pensar no problema para selecionar a solução mais provável, ou encontrar uma solução melhor, mesmo que não seja óbvia.</p> </li> <li> <p>Ao reproduzir o artigo de outra pessoa:</p> <ul> <li><strong>O que você aprende:</strong> como fazer um método de DRL funcionar, melhorando nossas habilidades de <em>RL engineers</em>.</li> <li>O que você pensa que vai aprender, <strong>mas não aprende:</strong> a surgir com novas ideias relevantes de pesquisa. Isso é melhor feito através da leitura crítica de outros artigos e do conhecimento de vários termos-chave da área.</li> </ul> </li> <li> <p>Algumas dicas que o autor tentou martelar nos leitores:</p> <ul> <li>se você vai usar um método de RL, tente não implementá-lo, LOL</li> <li>tente medir tudo o que é possível durante o treinamento. Não só métricas como recompensa ou erro da rede, mas outras métricas indiretas de sucesso</li> <li>escrever um diário dos experimentos para se lembrar do que você já tentou</li> </ul> </li> <li> <p>Outro ponto interessante do relato. O autor pensou que iria levar 3 meses pra terminar a reprodução do paper, mas levou <strong>8 meses</strong>. A maior parte do tempo é desprendida fazendo o algoritmo funcionar num exemplo simples. Depois, a demora está em instrumentar testes. Seguem abaixo os tempos que o autor demorou para:</p> <ul> <li>implementar a primeira versão do método (30 horas)</li> <li>fazer ele funcionar num exemplo básico (110 horas)</li> <li>fazer ele funcionar num exemplo novo (10 horas) e finalmente</li> <li>conseguir rodar testes consistentes (60 horas).</li> </ul> </li> </ol> <h2 id="texto-deep-reinforcement-learning-doesnt-work-yet">Texto: Deep Reinforcement Learning Doesn’t Work Yet</h2> <p>Fonte: https://www.alexirpan.com/2018/02/14/rl-hard.html</p> <p>Esse artigo lista diversos motivos pra métodos de DRL não funcionarem.</p> <ul> <li><em>ineficiência de amostras:</em> necessários milhões de exemplos pro método aprender</li> <li><em>nunca é o método mais eficiente:</em> métodos especializados pra cada problema quase sempre têm resultados melhores do que DRL: e.g., algoritmos de controle para robôs humanoides</li> <li><em>criação da função de recompensa:</em> precisa ser feita por uma pessoa e é difícil criar uma função que guia o agente de maneira óbvia para o objetivo, sem ser esparsa (+1 por vencer)</li> <li><em>retorno esperado pode ter máximos locais:</em> mesmo que o código esteja correto, o agente pode convergit para comportamentos inesperados, necessitando reiniciar o treinamento todo.</li> <li><em>agente aprende por overfitting:</em> difícil realizar transferência do que é aprendido para outro ambiente ou para uma pequena mudança no mesmo ambiente</li> <li><em>sensibilidade a inícios aleatórios:</em> o gráfico abaixo é um exemplo de treinar um algoritmo de DRL a equilibrar o pêndulo invertido várias vezes. Só funcionou 70% das vezes.</li> </ul> <p><img src="https://www.alexirpan.com/public/rl-hard/pendulum_results.png" alt="Graph of Pendulum results"/></p> <p>Algumas características de problemas nos quais aplicar DRL pode ser produtivo:</p> <ul> <li>é fácil gerar experiência em quantidades ilimitadas: quanto mais dados melhor, usar um simulador rápido</li> <li>é possível trabalhar num problema simplificado: ao invés de trabalhar no problema mais complexo possível (afinal, RL resolve tudo!), é melhor simplificá-lo e ver se o método resolve esse problema simplificado. E.g., trabalhar apenas em um cenário de muitos, com apenas um tipo de agente e espaço de ações limitado</li> <li>é possível utilizar <em>self-play</em>: em um cenário competitivo, permitir que o agente controle ambos os agentes e aprenda de si próprio. Funciona bem no AlphaZero, Dota 2 e Super Smash Bros.</li> <li>é fácil definir uma recompensa da qual o agente não possa se aproveitar: +1 por ganhar, -1 por perder. Nos papers de NAS, a recompensa é a acurácia da rede gerada no dataset de validação, ou seja, exatamente o que se deseja maximizar.</li> <li> <p>se a recompensa for modelada (<em>reward shaping</em>), tentar fazê-la ser rica: no ambiente que eu trabalhei durante o doutorado (SMAC), os agentes recebiam:</p> <ul> <li>uma recompensa proporcional à quantia de dano que inferiam no adversário, num determinado ataque</li> <li>uma recompensa maior por derrotar uma unidade adversária (<em>last hit</em>)</li> <li>uma recompensa maior ainda por derrotar todas as unidades adversárias (ganhar a partida)</li> </ul> <p>o autor também aponta que, quanto menor o intervalo entre uma ação e a recompensa associada àquela ação, mais fácil para o agente aprender.</p> </li> </ul>]]></content><author><name></name></author><category term="deep-reinforcement-learning"/><category term="português"/><category term="reinforcement-learning"/><summary type="html"><![CDATA[Essa é uma compilação de textos que eu encontrei na internet em momentos de frustração com meu trabalho. Eu os resumi e traduzi para compartilhar com as pessoas sempre que me perguntarem porque trabalhar com DRL é uma desgraça.]]></summary></entry><entry><title type="html">Classificação da base de dados Iris - redes menores e regularização</title><link href="https://douglasrizzo.github.io/blog/2020/08/regularizacao-microrede/" rel="alternate" type="text/html" title="Classificação da base de dados Iris - redes menores e regularização"/><published>2020-08-19T00:00:00+00:00</published><updated>2020-08-19T00:00:00+00:00</updated><id>https://douglasrizzo.github.io/blog/2020/08/regularizacao-microrede</id><content type="html" xml:base="https://douglasrizzo.github.io/blog/2020/08/regularizacao-microrede/"><![CDATA[<h2 id="introdução">Introdução</h2> <p><a href="https://colab.research.google.com/drive/1kOaj4ogt13P0XlaoZ0wqezgEP9KCB8bf?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a></p> <p>Este notebook continua uma série na qual foram introduzidas a base de dados Iris e o método de treinamento e avaliação de redes neurais <a href="https://colab.research.google.com/drive/13r1TY_BF1AXOMH8ufDEct3E8g243sONM#scrollTo=MLs97GxwgNrs">[1]</a> e o PCA <a href="https://colab.research.google.com/drive/15vsVfH-qlJP2YBCdgS8V8uc8jjkRYCFs#scrollTo=LOpZfT9qCa3K">[2]</a>.</p> <p>No primeiro notebook, foram mencionadas duas coisas que serão testadas aqui.</p> <ol> <li>redes neurais maiores (com mais pesos treináveis) possuem maior predisposição ao <em>overfitting</em>.</li> <li>existe uma técnica, chamada <em>regularização</em>, capaz de combater o <em>overfitting</em>.</li> </ol> <p>Neste notebook, uma rede consideravelmente menor será treinada para classificar a base de dados Iris. Não só isso, como ela usará a primeira componente principal retornada pelo PCA, trabalhando tanto com menos pesos como menos dados.</p> <p>Além disso, treinaremos a rede neural original, utilizada nos notebooks anteriores, com regularização L2 e observaremos a ausência de <em>overfitting</em> quando a rede é treinada por longos períodos de tempo.</p> <h2 id="importando-pacotes-e-criando-funções">Importando pacotes e criando funções</h2> <p>As funções abaixo aplicam o PCA numa base de dados e avaliam uma rede neural, retornando as medidas para serem exibidas em gráficos posteriormente.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="n">sklearn.datasets</span> <span class="kn">import</span> <span class="n">load_iris</span>
<span class="kn">from</span> <span class="n">sklearn.model_selection</span> <span class="kn">import</span> <span class="n">train_test_split</span>
<span class="kn">from</span> <span class="n">sklearn.metrics</span> <span class="kn">import</span> <span class="n">classification_report</span><span class="p">,</span> <span class="n">confusion_matrix</span>
<span class="kn">from</span> <span class="n">sklearn.decomposition</span> <span class="kn">import</span> <span class="n">PCA</span>

<span class="kn">import</span> <span class="n">matplotlib.pyplot</span> <span class="k">as</span> <span class="n">plt</span>

<span class="kn">import</span> <span class="n">tensorflow.keras</span> <span class="k">as</span> <span class="n">keras</span>
<span class="kn">import</span> <span class="n">numpy</span> <span class="k">as</span> <span class="n">np</span>
<span class="kn">from</span> <span class="n">tensorflow.keras.models</span> <span class="kn">import</span> <span class="n">Sequential</span>
<span class="kn">from</span> <span class="n">tensorflow.keras.layers</span> <span class="kn">import</span> <span class="n">Dense</span>

<span class="k">def</span> <span class="nf">apply_PCA</span><span class="p">(</span><span class="n">X</span><span class="p">,</span> <span class="n">n_components</span><span class="p">):</span>
  <span class="n">pca</span> <span class="o">=</span> <span class="nc">PCA</span><span class="p">(</span><span class="n">n_components</span><span class="o">=</span><span class="n">n_components</span><span class="p">)</span>
  <span class="n">new_X</span> <span class="o">=</span> <span class="n">pca</span><span class="p">.</span><span class="nf">fit_transform</span><span class="p">(</span><span class="n">iris_X</span><span class="p">)</span>
  <span class="nf">print</span><span class="p">(</span><span class="sh">'</span><span class="s">Tamanho da base de dados antes: </span><span class="sh">'</span><span class="p">,</span> <span class="n">X</span><span class="p">.</span><span class="n">shape</span><span class="p">)</span>
  <span class="nf">print</span><span class="p">(</span><span class="sh">'</span><span class="s">Tamanho da base de dados depois: </span><span class="sh">'</span><span class="p">,</span> <span class="n">new_X</span><span class="p">.</span><span class="n">shape</span><span class="p">)</span>
  <span class="nf">print</span><span class="p">(</span><span class="sh">'</span><span class="s">Porcentagem da variância explicada por cada coluna:</span><span class="sh">'</span><span class="p">,</span> <span class="n">pca</span><span class="p">.</span><span class="n">explained_variance_ratio_</span><span class="p">)</span>
  <span class="nf">print</span><span class="p">(</span><span class="sh">'</span><span class="s">Variância acumulada nas colunas remanescentes:</span><span class="sh">'</span><span class="p">,</span> <span class="nf">sum</span><span class="p">(</span><span class="n">pca</span><span class="p">.</span><span class="n">explained_variance_ratio_</span><span class="p">))</span>

  <span class="k">return</span> <span class="n">new_X</span>

<span class="k">def</span> <span class="nf">evaluate_model</span><span class="p">(</span><span class="n">model</span><span class="p">,</span> <span class="n">X</span><span class="p">,</span> <span class="n">y</span><span class="p">):</span>
  <span class="n">X_train</span><span class="p">,</span> <span class="n">X_test</span><span class="p">,</span> <span class="n">y_train</span><span class="p">,</span> <span class="n">y_test</span> <span class="o">=</span> <span class="nf">train_test_split</span><span class="p">(</span><span class="n">X</span><span class="p">,</span>
                                                    <span class="n">y</span><span class="p">,</span>
                                                    <span class="n">test_size</span> <span class="o">=</span> <span class="mf">0.2</span><span class="p">,</span>
                                                    <span class="n">random_state</span><span class="o">=</span><span class="mi">123</span><span class="p">)</span>
  
  <span class="n">y_train_onehot</span> <span class="o">=</span> <span class="n">keras</span><span class="p">.</span><span class="n">utils</span><span class="p">.</span><span class="nf">to_categorical</span><span class="p">(</span><span class="n">y_train</span><span class="p">,</span> <span class="n">num_classes</span> <span class="o">=</span> <span class="mi">3</span><span class="p">)</span>
  <span class="n">y_test_onehot</span> <span class="o">=</span> <span class="n">keras</span><span class="p">.</span><span class="n">utils</span><span class="p">.</span><span class="nf">to_categorical</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">num_classes</span> <span class="o">=</span> <span class="mi">3</span><span class="p">)</span>

  <span class="n">model</span><span class="p">.</span><span class="nf">save_weights</span><span class="p">(</span><span class="sh">'</span><span class="s">weights.hdf5</span><span class="sh">'</span><span class="p">)</span>
  <span class="n">history</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train_onehot</span><span class="p">,</span> <span class="n">validation_split</span><span class="o">=</span><span class="p">.</span><span class="mi">1</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">2500</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>

  <span class="n">y_pred</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
  <span class="n">y_pred_onehot</span> <span class="o">=</span> <span class="n">y_pred</span><span class="p">.</span><span class="nf">argmax</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
  <span class="nf">print</span><span class="p">(</span><span class="nf">classification_report</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">y_pred_onehot</span><span class="p">))</span>
  
  <span class="n">v1</span> <span class="o">=</span> <span class="n">history</span><span class="p">.</span><span class="n">history</span><span class="p">[</span><span class="sh">'</span><span class="s">categorical_accuracy</span><span class="sh">'</span><span class="p">]</span>
  <span class="n">v2</span> <span class="o">=</span> <span class="n">history</span><span class="p">.</span><span class="n">history</span><span class="p">[</span><span class="sh">'</span><span class="s">loss</span><span class="sh">'</span><span class="p">]</span>
  <span class="n">v3</span> <span class="o">=</span> <span class="n">history</span><span class="p">.</span><span class="n">history</span><span class="p">[</span><span class="sh">'</span><span class="s">val_categorical_accuracy</span><span class="sh">'</span><span class="p">]</span>
  <span class="n">v4</span> <span class="o">=</span> <span class="n">history</span><span class="p">.</span><span class="n">history</span><span class="p">[</span><span class="sh">'</span><span class="s">val_loss</span><span class="sh">'</span><span class="p">]</span>

  <span class="n">model</span><span class="p">.</span><span class="nf">load_weights</span><span class="p">(</span><span class="sh">'</span><span class="s">weights.hdf5</span><span class="sh">'</span><span class="p">)</span>
  <span class="n">history</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">fit</span><span class="p">(</span><span class="n">X_train</span><span class="p">,</span> <span class="n">y_train_onehot</span><span class="p">,</span> <span class="n">epochs</span><span class="o">=</span><span class="mi">150</span><span class="p">,</span> <span class="n">verbose</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
  
  <span class="n">v5</span> <span class="o">=</span> <span class="n">history</span><span class="p">.</span><span class="n">history</span><span class="p">[</span><span class="sh">'</span><span class="s">categorical_accuracy</span><span class="sh">'</span><span class="p">]</span>
  <span class="n">v6</span> <span class="o">=</span> <span class="n">history</span><span class="p">.</span><span class="n">history</span><span class="p">[</span><span class="sh">'</span><span class="s">loss</span><span class="sh">'</span><span class="p">]</span>
  
  <span class="n">y_pred</span> <span class="o">=</span> <span class="n">model</span><span class="p">.</span><span class="nf">predict</span><span class="p">(</span><span class="n">X_test</span><span class="p">)</span>
  <span class="n">y_pred_onehot</span> <span class="o">=</span> <span class="n">y_pred</span><span class="p">.</span><span class="nf">argmax</span><span class="p">(</span><span class="n">axis</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
  <span class="nf">print</span><span class="p">(</span><span class="nf">classification_report</span><span class="p">(</span><span class="n">y_test</span><span class="p">,</span> <span class="n">y_pred_onehot</span><span class="p">))</span>

  <span class="k">return</span> <span class="n">v1</span><span class="p">,</span> <span class="n">v2</span><span class="p">,</span> <span class="n">v3</span><span class="p">,</span> <span class="n">v4</span><span class="p">,</span> <span class="n">v5</span><span class="p">,</span> <span class="n">v6</span>
</code></pre></div></div> <h3 id="preparando-os-dados">Preparando os dados</h3> <p>Usaremos o pacote <em>scikit-learn</em> para carregar a base de dados Iris. Vamos geraruma versão da base com o menor número possível de componentes principais (1).</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">iris_X</span><span class="p">,</span> <span class="n">iris_y</span> <span class="o">=</span> <span class="nf">load_iris</span><span class="p">(</span><span class="n">return_X_y</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="n">iris_X_tiny</span> <span class="o">=</span> <span class="nf">apply_PCA</span><span class="p">(</span><span class="n">iris_X</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Tamanho da base de dados antes:  (150, 4)
Tamanho da base de dados depois:  (150, 1)
Porcentagem da variância explicada por cada coluna: [0.92461872]
Variância acumulada nas colunas remanescentes: 0.9246187232017271
</code></pre></div></div> <h2 id="regularização">Regularização</h2> <p>Em termos matemáticos, o <em>overfitting</em> ocorre quando os pesos de uma rede neural assumem magnitudes (positivas ou negativas) muito altas, permitindo que as funções que essas redes neurais modelam se tornem demasiadamente complexas para a função de erro que tentam minimizar.</p> <p>Na imagem abaixo, ambas as funções azul e verde se ajustam aos dados vermelhos, porém a função azul assumiu uma forma desnecessariamente complexa. Caso um novo ponto vermelho seja adicionado, é possível que a função verde esteja mais próxima dele do que a função azul, indicando que a função verde generaliza melhor os dados observados, mesmo sendo mais simples.</p> <p><img src="https://upload.wikimedia.org/wikipedia/commons/0/02/Regularization.svg" alt="Regularização"/></p> <p>A diferença entre as duas funções está no fato da função verde ter sido regularizada. Em sua forma mais simples, a regularização é feita somando-se os pesos da rede neural à função de erro que a rede tenta minimizar. Imaginando que \(L(\theta)\) é a função de erro que usamos até agora, \(R(\theta)\) é o novo termo de regularização que incluímos.</p> <p>\[J(\theta)=L(\theta) + \lambda R(\theta)\]</p> <p>Uma regularização comumente usada é a L2, na qual somamos o quadrado dos pesos da rede neural à função de erro. Isso tem o efeito de punir demasiadamente pesos muito grandes, ignorando pesos pequenos. O termo \(\lambda\) é um coeficiente que indica o quão relevante o termo de regularização é na fórmula total do erro. Ele será utilizado na declaração da rede neural que faremos em Keras.</p> <p>\[J(\theta)=L(\theta) + \lambda \sum_w^{\theta}w^2\]</p> <p>Com a regularização, a rede neural deve alcançar o menor erro possível com os menores pesos possíveis, evitando o <em>overfitting</em>.</p> <p>As funções abaixo vão criar as rede neurais.</p> <ol> <li>A primeira foi utilizada nos tutoriais anterior e possui 4 entradas, 4 camadas e 213 pesos treináveis.</li> <li>A segunda é igual à primeira, porém com a regularização configurada nas camadas.</li> <li>A última rede possui aproximadamente 10% do tamanho da primeira, 1 entrada, 3 camadas e 23 pesos treináveis.</li> </ol> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">create_large_model</span><span class="p">(</span><span class="n">input_dim</span><span class="p">):</span>
  <span class="n">model</span> <span class="o">=</span> <span class="nc">Sequential</span><span class="p">()</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">,</span> <span class="n">input_dim</span><span class="o">=</span><span class="n">input_dim</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">6</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">softmax</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">compile</span><span class="p">(</span><span class="sh">'</span><span class="s">adam</span><span class="sh">'</span><span class="p">,</span><span class="sh">'</span><span class="s">categorical_crossentropy</span><span class="sh">'</span><span class="p">,</span> <span class="n">metrics</span><span class="o">=</span><span class="p">[</span><span class="sh">'</span><span class="s">categorical_accuracy</span><span class="sh">'</span><span class="p">])</span>

  <span class="k">return</span> <span class="n">model</span>

<span class="k">def</span> <span class="nf">create_regularized_model</span><span class="p">(</span><span class="n">input_dim</span><span class="p">):</span>
  <span class="n">model</span> <span class="o">=</span> <span class="nc">Sequential</span><span class="p">()</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">,</span> <span class="n">kernel_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">,</span> <span class="n">bias_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">,</span> <span class="n">input_dim</span><span class="o">=</span><span class="n">input_dim</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">,</span>  <span class="n">kernel_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">,</span> <span class="n">bias_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">6</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">,</span>  <span class="n">kernel_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">,</span> <span class="n">bias_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">softmax</span><span class="sh">'</span><span class="p">,</span>  <span class="n">kernel_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">,</span> <span class="n">bias_regularizer</span><span class="o">=</span><span class="sh">'</span><span class="s">l2</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">compile</span><span class="p">(</span><span class="sh">'</span><span class="s">adam</span><span class="sh">'</span><span class="p">,</span><span class="sh">'</span><span class="s">categorical_crossentropy</span><span class="sh">'</span><span class="p">,</span> <span class="n">metrics</span><span class="o">=</span><span class="p">[</span><span class="sh">'</span><span class="s">categorical_accuracy</span><span class="sh">'</span><span class="p">])</span>

  <span class="k">return</span> <span class="n">model</span>

<span class="k">def</span> <span class="nf">create_tiny_model</span><span class="p">(</span><span class="n">input_dim</span><span class="p">):</span>
  <span class="n">model</span> <span class="o">=</span> <span class="nc">Sequential</span><span class="p">()</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">,</span> <span class="n">input_dim</span><span class="o">=</span><span class="n">input_dim</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">tanh</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">add</span><span class="p">(</span><span class="nc">Dense</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="n">activation</span><span class="o">=</span><span class="sh">'</span><span class="s">softmax</span><span class="sh">'</span><span class="p">))</span>
  <span class="n">model</span><span class="p">.</span><span class="nf">compile</span><span class="p">(</span><span class="sh">'</span><span class="s">adam</span><span class="sh">'</span><span class="p">,</span><span class="sh">'</span><span class="s">categorical_crossentropy</span><span class="sh">'</span><span class="p">,</span> <span class="n">metrics</span><span class="o">=</span><span class="p">[</span><span class="sh">'</span><span class="s">categorical_accuracy</span><span class="sh">'</span><span class="p">])</span>

  <span class="k">return</span> <span class="n">model</span>

<span class="n">large_net</span> <span class="o">=</span> <span class="nf">create_large_model</span><span class="p">(</span><span class="n">iris_X</span><span class="p">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="n">reg_net</span> <span class="o">=</span> <span class="nf">create_regularized_model</span><span class="p">(</span><span class="n">iris_X</span><span class="p">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="n">tiny_net</span> <span class="o">=</span> <span class="nf">create_tiny_model</span><span class="p">(</span><span class="n">iris_X_tiny</span><span class="p">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>

<span class="n">large_net</span><span class="p">.</span><span class="nf">summary</span><span class="p">()</span>
<span class="n">tiny_net</span><span class="p">.</span><span class="nf">summary</span><span class="p">()</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Model: "sequential"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense (Dense)                (None, 10)                50        
_________________________________________________________________
dense_1 (Dense)              (None, 8)                 88        
_________________________________________________________________
dense_2 (Dense)              (None, 6)                 54        
_________________________________________________________________
dense_3 (Dense)              (None, 3)                 21        
=================================================================
Total params: 213
Trainable params: 213
Non-trainable params: 0
_________________________________________________________________
Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_8 (Dense)              (None, 3)                 6         
_________________________________________________________________
dense_9 (Dense)              (None, 2)                 8         
_________________________________________________________________
dense_10 (Dense)             (None, 3)                 9         
=================================================================
Total params: 23
Trainable params: 23
Non-trainable params: 0
_________________________________________________________________
</code></pre></div></div> <p>Vamos utilizar nossa função <code class="language-plaintext highlighter-rouge">evaluate_model()</code> para avaliar as redes. As redes maiorws serão treinadas na base original e a rede menor, na 1ª componente principal dessa base.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">acc1_large</span><span class="p">,</span> <span class="n">l1_large</span><span class="p">,</span> <span class="n">acc_v_large</span><span class="p">,</span> <span class="n">lv_large</span><span class="p">,</span> <span class="n">acc2_large</span><span class="p">,</span> <span class="n">l2_large</span> <span class="o">=</span> <span class="nf">evaluate_model</span><span class="p">(</span><span class="n">large_net</span><span class="p">,</span> <span class="n">iris_X</span><span class="p">,</span> <span class="n">iris_y</span><span class="p">)</span>
<span class="n">acc1_reg</span><span class="p">,</span> <span class="n">l1_reg</span><span class="p">,</span> <span class="n">acc_v_reg</span><span class="p">,</span> <span class="n">lv_reg</span><span class="p">,</span> <span class="n">acc2_reg</span><span class="p">,</span> <span class="n">l2_reg</span> <span class="o">=</span> <span class="nf">evaluate_model</span><span class="p">(</span><span class="n">reg_net</span><span class="p">,</span> <span class="n">iris_X</span><span class="p">,</span> <span class="n">iris_y</span><span class="p">)</span>
<span class="n">acc1_tiny</span><span class="p">,</span> <span class="n">l1_tiny</span><span class="p">,</span> <span class="n">acc_v_tiny</span><span class="p">,</span> <span class="n">lv_tiny</span><span class="p">,</span> <span class="n">acc2_tiny</span><span class="p">,</span> <span class="n">l2_tiny</span> <span class="o">=</span> <span class="nf">evaluate_model</span><span class="p">(</span><span class="n">tiny_net</span><span class="p">,</span> <span class="n">iris_X_tiny</span><span class="p">,</span> <span class="n">iris_y</span><span class="p">)</span>
</code></pre></div></div> <div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       0.75      1.00      0.86         6
           2       1.00      0.82      0.90        11

    accuracy                           0.93        30
   macro avg       0.92      0.94      0.92        30
weighted avg       0.95      0.93      0.93        30

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       1.00      0.83      0.91         6
           2       0.92      1.00      0.96        11

    accuracy                           0.97        30
   macro avg       0.97      0.94      0.96        30
weighted avg       0.97      0.97      0.97        30

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       1.00      0.83      0.91         6
           2       0.92      1.00      0.96        11

    accuracy                           0.97        30
   macro avg       0.97      0.94      0.96        30
weighted avg       0.97      0.97      0.97        30

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       1.00      0.83      0.91         6
           2       0.92      1.00      0.96        11

    accuracy                           0.97        30
   macro avg       0.97      0.94      0.96        30
weighted avg       0.97      0.97      0.97        30

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       0.67      1.00      0.80         6
           2       1.00      0.73      0.84        11

    accuracy                           0.90        30
   macro avg       0.89      0.91      0.88        30
weighted avg       0.93      0.90      0.90        30

              precision    recall  f1-score   support

           0       1.00      1.00      1.00        13
           1       0.83      0.83      0.83         6
           2       0.91      0.91      0.91        11

    accuracy                           0.93        30
   macro avg       0.91      0.91      0.91        30
weighted avg       0.93      0.93      0.93        30
</code></pre></div></div> <p>São exibidos os valores para cada rede treinada na base de treinamento por 2500 épocas e depois por 150 eṕocas. Espera-se que o desempenho das redes neurais que sofram de <em>overfitting</em> seja inferior nos valores impresso primeiro.</p> <p>Os valores podem mudar aleatoriamente, porém é possível perceber através dos valores de precisão, recall, F1-score e pela matriz de confusão que o desempenho de ambas as redes é comparável e, muitas vezes, idêntico.</p> <p>Vamos gerar gráficos das 6 medidas coletadas dos dois modelos.</p> <div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">fig</span><span class="p">,</span> <span class="n">axes</span> <span class="o">=</span> <span class="n">plt</span><span class="p">.</span><span class="nf">subplots</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span><span class="mi">2</span><span class="p">,</span> <span class="bp">False</span><span class="p">,</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">20</span><span class="p">,</span> <span class="mi">15</span><span class="p">),</span> <span class="n">squeeze</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc1_large</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc1_reg</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc1_tiny</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">set_title</span><span class="p">(</span><span class="sh">'</span><span class="s">Acurácia Treino</span><span class="sh">'</span><span class="p">)</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">l1_large</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">l1_reg</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">l1_tiny</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">set_title</span><span class="p">(</span><span class="sh">'</span><span class="s">Erro Treino</span><span class="sh">'</span><span class="p">)</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc_v_large</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc_v_reg</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc_v_tiny</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">set_title</span><span class="p">(</span><span class="sh">'</span><span class="s">Acurácia Val.</span><span class="sh">'</span><span class="p">)</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">lv_large</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">lv_reg</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">lv_tiny</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">set_title</span><span class="p">(</span><span class="sh">'</span><span class="s">Erro Val.</span><span class="sh">'</span><span class="p">)</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc2_large</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc2_reg</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">acc2_tiny</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">set_title</span><span class="p">(</span><span class="sh">'</span><span class="s">Acurácia total</span><span class="sh">'</span><span class="p">)</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">l2_large</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">l2_reg</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">plot</span><span class="p">(</span><span class="n">l2_tiny</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">set_title</span><span class="p">(</span><span class="sh">'</span><span class="s">Erro total</span><span class="sh">'</span><span class="p">)</span>

<span class="n">legenda</span> <span class="o">=</span> <span class="p">[</span><span class="sh">'</span><span class="s">Grande</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">Regularizada</span><span class="sh">'</span><span class="p">,</span> <span class="sh">'</span><span class="s">Pequena</span><span class="sh">'</span><span class="p">]</span>
<span class="n">xlabel</span> <span class="o">=</span> <span class="sh">'</span><span class="s">Épocas</span><span class="sh">'</span>

<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">legend</span><span class="p">(</span><span class="n">legenda</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">legend</span><span class="p">(</span><span class="n">legenda</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">legend</span><span class="p">(</span><span class="n">legenda</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">legend</span><span class="p">(</span><span class="n">legenda</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">legend</span><span class="p">(</span><span class="n">legenda</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">legend</span><span class="p">(</span><span class="n">legenda</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">set_xlabel</span><span class="p">(</span><span class="n">xlabel</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">set_xlabel</span><span class="p">(</span><span class="n">xlabel</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">0</span><span class="p">].</span><span class="nf">set_xlabel</span><span class="p">(</span><span class="n">xlabel</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">set_xlabel</span><span class="p">(</span><span class="n">xlabel</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">1</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">set_xlabel</span><span class="p">(</span><span class="n">xlabel</span><span class="p">)</span>
<span class="n">axes</span><span class="p">[</span><span class="mi">2</span><span class="p">][</span><span class="mi">1</span><span class="p">].</span><span class="nf">set_xlabel</span><span class="p">(</span><span class="n">xlabel</span><span class="p">)</span>

<span class="n">plt</span><span class="p">.</span><span class="nf">show</span><span class="p">()</span>
</code></pre></div></div> <p><img src="/assets/img/2020-08-19-regularizacao-microrede_output_11_0.png" alt="png"/></p> <p>Ambas as redes foram treinadas por 2500 épocas e avaliadas no conjunto de validação para constatar a presença de <em>overfitting</em> (4 primeiros gráficos). Depois, foram treinadas novamente por 150 épocas na totalidade dos dados de treinamento (2 últimos gráficos).</p> <p>O gráfico de erro no conjunto de treinamento (topo, direita) nos mostra que a rede menor leva mais épocas para aprender. Seu erro diminui lentamente. A rede regularizada não consegue diminuir seu erro tanto quanto as redes não regularizadas devido à restrição em seus pesos. Isso pode parecer ruim, mas veremos um efeito positivo da regularização a seguir.</p> <p>O gráfico de erro no conjunto de validação (centro, direita) demonstra que o erro da rede grande não-regularizada começa a crescer linearmente após aproximadamente 200 épocas. Um período de treinamento muito extenso apenas prejudica esta rede. A rede menor, apesar de ser menos afetada pelo <em>overfitting</em>, ainda demonstra aumenta do erro após muitas épocas de treinamento. Porém, este aumento é mais lento que na rede neural grande. Por último, a rede grande regularizada não demonstra aumento do erro no conjunto de validação, independente da quantidade de épocas de treinamento.</p> <p>Essa é uma característica interessante no mundo real, quando não sabemos exatamente a topologia exata da rede neural que solucionará nosso problema em questão, ou por quantas épocas de treinamento é necessário treinar o modelo.</p> <h2 id="conclusão">Conclusão</h2> <p>Este notebook demonstrou que uma rede neural consideravelmente menor que a utilizada até o momento é capaz de realizar a classificação das flores na base de dados Iris, utilizando 1/4 dos valores de entrada, 3/4 do número de camadas e aproximadamente 1/10 dos pesos treináveis.</p>]]></content><author><name></name></author><category term="machine-learning"/><category term="colab"/><category term="portugues"/><category term="keras"/><category term="neural-networks"/><category term="python"/><category term="classification"/><category term="tutorial"/><summary type="html"><![CDATA[Introdução]]></summary></entry></feed>