In [1]:
from __future__ import division, print_function
%matplotlib inline
from importlib import reload # Python 3
import utils; reload(utils)
from utils import *
from keras.layers.merge import dot, add, concatenate
In [2]:
path = "data/ml-latest-small/" # from https://grouplens.org/datasets/movielens/
#path = "data/ml-20m/"
model_path = path + 'models/'
if not os.path.exists(model_path): os.mkdir(model_path)
batch_size=64
#batch_size=1
We're working with the movielens data, which contains one rating per row, like this:
In [3]:
ratings = pd.read_csv(path+'ratings.csv')
ratings.head()
Out[3]:
In [4]:
len(ratings)
Out[4]:
Just for display purposes, let's read in the movie names too.
In [5]:
movie_names = pd.read_csv(path+'movies.csv').set_index('movieId')['title'].to_dict
In [6]:
users = ratings.userId.unique()
movies = ratings.movieId.unique()
In [7]:
# userId and movieId become ditionary elements with values ranging from 0 to max len
userid2idx = {o:i for i,o in enumerate(users)}
movieid2idx = {o:i for i,o in enumerate(movies)}
We update the movie and user ids so that they are contiguous integers, which we want when using embeddings.
In [8]:
ratings.movieId = ratings.movieId.apply(lambda x: movieid2idx[x])
ratings.userId = ratings.userId.apply(lambda x: userid2idx[x])
In [9]:
user_min, user_max, movie_min, movie_max = (ratings.userId.min(),
ratings.userId.max(), ratings.movieId.min(), ratings.movieId.max())
user_min, user_max, movie_min, movie_max
Out[9]:
In [10]:
n_users = ratings.userId.nunique()
n_movies = ratings.movieId.nunique()
n_users, n_movies
Out[10]:
This is the number of latent factors in each embedding.
In [11]:
n_factors = 50
In [12]:
np.random.seed = 42
Randomly split into training and validation.
In [13]:
msk = np.random.rand(len(ratings)) < 0.8
trn = ratings[msk]
val = ratings[~msk]
We create a crosstab of the most popular movies and most movie-addicted users which we'll copy into Excel for creating a simple example. This isn't necessary for any of the modeling below however.
In [14]:
g=ratings.groupby('userId')['rating'].count()
topUsers=g.sort_values(ascending=False)[:15]
In [15]:
g=ratings.groupby('movieId')['rating'].count()
topMovies=g.sort_values(ascending=False)[:15]
In [16]:
top_r = ratings.join(topUsers, rsuffix='_r', how='inner', on='userId')
In [17]:
top_r = top_r.join(topMovies, rsuffix='_r', how='inner', on='movieId')
In [23]:
pd.crosstab(top_r.userId, top_r.movieId, top_r.rating, aggfunc=np.sum)
Out[23]:
The most basic model is a dot product of a movie embedding and a user embedding. Let's see how well that works:
In [18]:
user_in = Input(shape=(1,), dtype='int64', name='user_in')
u = Embedding(input_dim=n_users, output_dim=n_factors, input_length=1, embeddings_regularizer=l2(1e-4))(user_in)
movie_in = Input(shape=(1,), dtype='int64', name='movie_in')
m = Embedding(input_dim=n_movies, output_dim=n_factors, input_length=1, embeddings_regularizer=l2(1e-4))(movie_in)
In [19]:
x = dot([u, m], axes=2)
x = Flatten()(x)
model = Model([user_in, movie_in], x)
model.compile(Adam(0.001), loss='mse')
In [20]:
model.summary()
In [22]:
user_in
Out[22]:
In [23]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=1,
validation_data=([val.userId, val.movieId], val.rating))
Out[23]:
In [39]:
model.optimizer.lr=0.01
In [40]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=3,
validation_data=([val.userId, val.movieId], val.rating))
Out[40]:
In [41]:
model.optimizer.lr=0.001
In [42]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=6,
validation_data=([val.userId, val.movieId], val.rating))
Out[42]:
The best benchmarks are a bit over 0.9, so this model doesn't seem to be working that well...
The problem is likely to be that we don't have bias terms - that is, a single bias for each user and each movie representing how positive or negative each user is, and how good each movie is. We can add that easily by simply creating an embedding with one output for each movie and each user, and adding it to our output.
In [24]:
def embedding_input(name, n_in, n_out, reg):
inp = Input(shape=(1,), dtype='int64', name=name)
return inp, Embedding(input_dim=n_in, output_dim=n_out, input_length=1, embeddings_regularizer=l2(reg))(inp)
In [25]:
user_in, u = embedding_input('user_in', n_users, n_factors, 1e-4)
movie_in, m = embedding_input('movie_in', n_movies, n_factors, 1e-4)
In [26]:
def create_bias(inp, n_in):
x = Embedding(input_dim=n_in, output_dim=1, input_length=1)(inp)
return Flatten()(x)
In [27]:
ub = create_bias(user_in, n_users)
mb = create_bias(movie_in, n_movies)
In [28]:
x = dot([u, m], axes=2)
x = Flatten()(x)
x = add([x, ub])
x = add([x, mb])
model = Model([user_in, movie_in], x)
model.compile(Adam(0.001), loss='mse')
In [29]:
model.summary()
In [48]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=1,
validation_data=([val.userId, val.movieId], val.rating))
Out[48]:
In [49]:
model.optimizer.lr=0.01
In [50]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=6,
validation_data=([val.userId, val.movieId], val.rating))
Out[50]:
In [30]:
model.optimizer.lr=0.001
In [52]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=10,
validation_data=([val.userId, val.movieId], val.rating))
Out[52]:
In [53]:
model.fit([trn.userId, trn.movieId], trn.rating, batch_size=batch_size, epochs=5,
validation_data=([val.userId, val.movieId], val.rating))
Out[53]:
This result is quite a bit better than the best benchmarks that we could find with a quick google search - so looks like a great approach!
In [54]:
model.save_weights(model_path+'bias.h5')
In [55]:
model.load_weights(model_path+'bias.h5')
We can use the model to generate predictions by passing a pair of ints - a user id and a movie id. For instance, this predicts that user #3 would really enjoy movie #6.
In [56]:
model.predict([np.array([3]), np.array([6])])
Out[56]:
To make the analysis of the factors more interesting, we'll restrict it to the top 2000 most popular movies.
In [31]:
g=ratings.groupby('movieId')['rating'].count()
topMovies=g.sort_values(ascending=False)[:2000]
topMovies = np.array(topMovies.index)
First, we'll look at the movie bias term. We create a 'model' - which in keras is simply a way of associating one or more inputs with one more more outputs, using the functional API. Here, our input is the movie id (a single id), and the output is the movie bias (a single float).
In [58]:
get_movie_bias = Model(movie_in, mb)
movie_bias = get_movie_bias.predict(topMovies)
movie_ratings = [(b[0], movie_names()[movies[i]]) for i,b in zip(topMovies,movie_bias)]
Now we can look at the top and bottom rated movies. These ratings are corrected for different levels of reviewer sentiment, as well as different types of movies that different reviewers watch.
In [59]:
sorted(movie_ratings, key=itemgetter(0))[:15]
Out[59]:
In [60]:
sorted(movie_ratings, key=itemgetter(0), reverse=True)[:15]
Out[60]:
We can now do the same thing for the embeddings.
In [32]:
get_movie_emb = Model(movie_in, m)
movie_emb = np.squeeze(get_movie_emb.predict([topMovies]))
movie_emb.shape
Out[32]:
In [33]:
get_movie_emb.predict([topMovies]).shape
Out[33]:
Because it's hard to interpret 50 embeddings, we use PCA to simplify them down to just 3 vectors.
In [62]:
from sklearn.decomposition import PCA
pca = PCA(n_components=3)
movie_pca = pca.fit(movie_emb.T).components_
In [63]:
fac0 = movie_pca[0]
In [64]:
movie_comp = [(f, movie_names()[movies[i]]) for f,i in zip(fac0, topMovies)]
Here's the 1st component. It seems to be 'critically acclaimed' or 'classic'.
In [65]:
sorted(movie_comp, key=itemgetter(0), reverse=True)[:10]
Out[65]:
In [66]:
sorted(movie_comp, key=itemgetter(0))[:10]
Out[66]:
In [67]:
fac1 = movie_pca[1]
In [68]:
movie_comp = [(f, movie_names()[movies[i]]) for f,i in zip(fac1, topMovies)]
The 2nd is 'hollywood blockbuster'.
In [69]:
sorted(movie_comp, key=itemgetter(0), reverse=True)[:10]
Out[69]:
In [70]:
sorted(movie_comp, key=itemgetter(0))[:10]
Out[70]:
In [71]:
fac2 = movie_pca[2]
In [72]:
movie_comp = [(f, movie_names()[movies[i]]) for f,i in zip(fac2, topMovies)]
The 3rd is 'violent vs happy'.
In [73]:
sorted(movie_comp, key=itemgetter(0), reverse=True)[:10]
Out[73]:
In [74]:
sorted(movie_comp, key=itemgetter(0))[:10]
Out[74]:
We can draw a picture to see how various movies appear on the map of these components. This picture shows the 1st and 3rd components.
In [75]:
# The following would be for Python 2 only
# reload(sys)
# sys.setdefaultencoding('utf8')
In [76]:
start=50; end=100
X = fac0[start:end]
Y = fac2[start:end]
plt.figure(figsize=(15,15))
plt.scatter(X, Y)
for i, x, y in zip(topMovies[start:end], X, Y):
plt.text(x,y,movie_names()[movies[i]], color=np.random.rand(3)*0.7, fontsize=14)
plt.show()
Rather than creating a special purpose architecture (like our dot-product with bias earlier), it's often both easier and more accurate to use a standard neural network. Let's try it! Here, we simply concatenate the user and movie embeddings into a single vector, which we feed into the neural net.
In [34]:
user_in, u = embedding_input('user_in', n_users, n_factors, 1e-4)
movie_in, m = embedding_input('movie_in', n_movies, n_factors, 1e-4)
In [35]:
x = concatenate([u, m], axis=2)
x = Flatten()(x)
x = Dropout(0.3)(x)
x = Dense(70, activation='relu')(x)
x = Dropout(0.75)(x)
x = Dense(1)(x)
nn = Model([user_in, movie_in], x)
nn.compile(Adam(0.001), loss='mse')
In [36]:
nn.summary()
In [79]:
nn.fit([trn.userId, trn.movieId], trn.rating, batch_size=64, epochs=8,
validation_data=([val.userId, val.movieId], val.rating))
Out[79]:
This improves on our already impressive accuracy even further!