{ "cells": [ { "cell_type": "markdown", "id": "c32513fe", "metadata": {}, "source": [ "# Most Common Recent Elements\n", "\n", "\n", "Previous counting problems have assumed a sliding window that holds the tail-end of a stream for processing. However sometimes we want to consider all the elements in the stream from the start while also distinguising between really old elements and data that is more recent. For example, we want to find out what movies are popular currently. While \"currently\" is a relatively ambiguous term, we do know that we want to discount movies that were popular decades ago, like *The Godfather*, and emphasize more recent movies like *Avengers: Endgame*. Imagine that we have a stream of movies being watched coming in according to increasing timestamp. A simple way to get the get most common movies would be to calculate the count for each movie, possibly even with some of the techniques above (i.e., counting ones). However, this will only give us an approximation and won't satisfy our preference to discount older movies. One way to do this is through the technique of Decaying Windows.\n", "\n", "## Decaying Windows\n", "\n", "In decaying windows, we exponentially decay the count for each movie by a constant $c$. $c$ will have a really small value, like $10^{-6}$ or $10^{-9}$. The value for each element is decayed by multiplying the current count by $(1-c)$ at every time step. Given a stream $a_1, a_2,...,a_t$, the exponentially decaying window of this stream is \n", "\n", "\\begin{equation}\n", "\\sum_{i=0}^{t-1}a_{t-i}(1-c)^i\n", "\\end{equation}\n", "\n", "When a new element $a_{t+1}$ is added into the stream all we need to do is:\n", "\n", "1. Multiply the current sum by $1-c$.\n", "2. Add $a_{t+1}$.\n", "\n", "In our movie example, we imagine a separate stream for each movie with a 1 each time that movie is watched, and a 0 each time another movie is watched. The decaying sum of the 1’s measures the current popularity of the movie. To save space, we can completely disregard unpopular movies by dropping movies whose count falls below a certain threshold, such as 0.5. When new data arrives at the stream we do the following:\n", "\n", "1. For each movie whose score we are currently tracking, multiply the score by $(1-c)$.\n", "2. If the data is for movie $M$, add 1 to $M$'s score if we are currently tracking it, or start tracking $M$ and initialize it with a score of 1 if we are not.\n", "3. Drop any movies we are tracking if the score is less than our threshold of 0.5.\n", "\n", "Due to the exponential decay, the sum of all scores is $\\frac{1}{c}$. There cannot be more than $\\frac{2}{c}$ movies with score of 0.5 or more, otherwise the sum of scores would be greater than $\\frac{1}{c}$. Therefore $\\frac{2}{c}$ is the maximum number of scores we would have to track.\n", "\n", "Let's provide an example using the MovieLens 100k dataset, a list of movie ratings from September 20, 1997 to April 22, 1998. First, let's map movies to their release timestamp so we can easily sort them by when they were released." ] }, { "cell_type": "code", "execution_count": 35, "id": "06f206df", "metadata": {}, "outputs": [], "source": [ "movieStream = {}\n", "movieNames = {}\n", "\n", "for line in open('ml-100k/u.item', encoding = \"ISO-8859-1\"):\n", " tokens = line.strip().split('|')\n", " movieNames[tokens[0]] = tokens[1]\n", " #print(tokens[0], tokens[1])\n", " \n", "for line in open('ml-100k/u.data'):\n", " tokens = line.strip().split()\n", " movie = tokens[1]\n", " ts = tokens[3]\n", " \n", " #handle duplicate timestamps\n", " while ts in movieStream:\n", " ts += 'a'\n", " \n", " movieStream[ts] = movie\n", "\n", "#Sort by timestamp and make it an iterator\n", "movie_list = []\n", "for key in sorted(movieStream.keys()):\n", " movie_list.append(movieStream[key])\n", " \n", "movie_iter = iter(movie_list)" ] }, { "cell_type": "markdown", "id": "1d4b5f76", "metadata": {}, "source": [ "Next we count movie rating with decaying windows. Play with the variable $c$ below by setting it to 0 to see which movies would be most popular by simple raw counts." ] }, { "cell_type": "code", "execution_count": 39, "id": "f0390878", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Titanic (1997) 67.28333046382443\n", "Contact (1997) 55.42960303711523\n", "Air Force One (1997) 54.49994366275277\n", "Star Wars (1977) 50.654564738716964\n", "Full Monty, The (1997) 49.25542831929427\n", "English Patient, The (1996) 46.814044430751856\n", "Good Will Hunting (1997) 45.61329962426032\n", "Liar Liar (1997) 44.01656947009622\n", "Scream (1996) 43.58306822429063\n", "Fargo (1996) 40.69582727523209\n" ] } ], "source": [ "scores = {}\n", "\n", "c = 0.0001\n", "\n", "n = 0\n", "\n", "for movie in movie_iter:\n", " \n", " remove = set()\n", " \n", " for key in scores:\n", " scores[key] *= (1-c)\n", " if scores[key] < 0.5 and key != movie:\n", " remove.add(key)\n", "\n", " \n", " for rem in remove:\n", " del scores[rem]\n", " \n", " if movie in scores:\n", " scores[movie] += 1\n", " else:\n", " scores[movie] = 1\n", " \n", " n += 1\n", " if n == 100000:\n", " break\n", "\n", "sortedScores = {k: v for k, v in sorted(scores.items(), reverse=True, key=lambda item: item[1])}\n", "count = 0\n", "for movie in sortedScores:\n", " print(movieNames[movie], sortedScores[movie])\n", " count += 1\n", " if count == 10:\n", " break" ] }, { "cell_type": "markdown", "id": "bd503c2f", "metadata": {}, "source": [ "We find that Titanic is the most popular movie by our method, even though by raw count it wouldn't even hit the top 10. This is because Titanic was released late 1997 so the reviews for it would be more recent.\n", "\n", "### Exercises\n", "\n", "1. What would the most popolar movie be if we weren't using decaying windows?" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.12" } }, "nbformat": 4, "nbformat_minor": 5 }