├── .gitignore ├── LICENSE ├── data.py ├── metrics.py ├── readme.md ├── triplet_keras.ipynb └── triplet_movielens.py /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | *.zip 3 | *.pyc 4 | .ipynb_checkpoints/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2016 Maciej Kula 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /data.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import itertools 4 | import os 5 | import zipfile 6 | 7 | import numpy as np 8 | 9 | import requests 10 | 11 | import scipy.sparse as sp 12 | 13 | 14 | def _get_movielens_path(): 15 | """ 16 | Get path to the movielens dataset file. 17 | """ 18 | 19 | return os.path.join(os.path.dirname(os.path.abspath(__file__)), 20 | 'movielens.zip') 21 | 22 | 23 | def _download_movielens(dest_path): 24 | """ 25 | Download the dataset. 26 | """ 27 | 28 | url = 'http://files.grouplens.org/datasets/movielens/ml-100k.zip' 29 | req = requests.get(url, stream=True) 30 | 31 | print('Downloading MovieLens data') 32 | 33 | with open(dest_path, 'wb') as fd: 34 | for chunk in req.iter_content(): 35 | fd.write(chunk) 36 | 37 | 38 | def _get_raw_movielens_data(): 39 | """ 40 | Return the raw lines of the train and test files. 41 | """ 42 | 43 | path = _get_movielens_path() 44 | 45 | if not os.path.isfile(path): 46 | _download_movielens(path) 47 | 48 | with zipfile.ZipFile(path) as datafile: 49 | return (datafile.read('ml-100k/ua.base').decode().split('\n'), 50 | datafile.read('ml-100k/ua.test').decode().split('\n')) 51 | 52 | 53 | def _parse(data): 54 | """ 55 | Parse movielens dataset lines. 56 | """ 57 | 58 | for line in data: 59 | 60 | if not line: 61 | continue 62 | 63 | uid, iid, rating, timestamp = [int(x) for x in line.split('\t')] 64 | 65 | yield uid, iid, rating, timestamp 66 | 67 | 68 | def _build_interaction_matrix(rows, cols, data): 69 | 70 | mat = sp.lil_matrix((rows, cols), dtype=np.int32) 71 | 72 | for uid, iid, rating, timestamp in data: 73 | # Let's assume only really good things are positives 74 | if rating >= 4.0: 75 | mat[uid, iid] = 1.0 76 | 77 | return mat.tocoo() 78 | 79 | 80 | def _get_movie_raw_metadata(): 81 | """ 82 | Get raw lines of the genre file. 83 | """ 84 | 85 | path = _get_movielens_path() 86 | 87 | if not os.path.isfile(path): 88 | _download_movielens(path) 89 | 90 | with zipfile.ZipFile(path) as datafile: 91 | return datafile.read('ml-100k/u.item').decode(errors='ignore').split('\n') 92 | 93 | 94 | def get_movielens_item_metadata(use_item_ids): 95 | """ 96 | Build a matrix of genre features (no_items, no_features). 97 | 98 | If use_item_ids is True, per-item feeatures will also be used. 99 | """ 100 | 101 | features = {} 102 | genre_set = set() 103 | 104 | for line in _get_movie_raw_metadata(): 105 | 106 | if not line: 107 | continue 108 | 109 | splt = line.split('|') 110 | item_id = int(splt[0]) 111 | 112 | genres = [idx for idx, val in 113 | zip(range(len(splt[5:])), splt[5:]) 114 | if int(val) > 0] 115 | 116 | if use_item_ids: 117 | # Add item-specific features too 118 | genres.append(item_id) 119 | 120 | for genre_id in genres: 121 | genre_set.add(genre_id) 122 | 123 | features[item_id] = genres 124 | 125 | mat = sp.lil_matrix((len(features) + 1, 126 | len(genre_set)), 127 | dtype=np.int32) 128 | 129 | for item_id, genre_ids in features.items(): 130 | for genre_id in genre_ids: 131 | mat[item_id, genre_id] = 1 132 | 133 | return mat 134 | 135 | 136 | def get_dense_triplets(uids, pids, nids, num_users, num_items): 137 | 138 | user_identity = np.identity(num_users) 139 | item_identity = np.identity(num_items) 140 | 141 | return user_identity[uids], item_identity[pids], item_identity[nids] 142 | 143 | 144 | def get_triplets(mat): 145 | 146 | return mat.row, mat.col, np.random.randint(mat.shape[1], size=len(mat.row)) 147 | 148 | 149 | def get_movielens_data(): 150 | """ 151 | Return (train_interactions, test_interactions). 152 | """ 153 | 154 | train_data, test_data = _get_raw_movielens_data() 155 | 156 | uids = set() 157 | iids = set() 158 | 159 | for uid, iid, rating, timestamp in itertools.chain(_parse(train_data), 160 | _parse(test_data)): 161 | uids.add(uid) 162 | iids.add(iid) 163 | 164 | rows = max(uids) + 1 165 | cols = max(iids) + 1 166 | 167 | return (_build_interaction_matrix(rows, cols, _parse(train_data)), 168 | _build_interaction_matrix(rows, cols, _parse(test_data))) 169 | -------------------------------------------------------------------------------- /metrics.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | from sklearn.metrics import roc_auc_score 4 | 5 | 6 | def predict(model, uid, pids): 7 | 8 | user_vector = model.get_layer('user_embedding').get_weights()[0][uid] 9 | item_matrix = model.get_layer('item_embedding').get_weights()[0][pids] 10 | 11 | scores = (np.dot(user_vector, 12 | item_matrix.T)) 13 | 14 | return scores 15 | 16 | 17 | def precision_at_k(model, ground_truth, k, user_features=None, item_features=None): 18 | """ 19 | Measure precision at k for model and ground truth. 20 | 21 | Arguments: 22 | - lightFM instance model 23 | - sparse matrix ground_truth (no_users, no_items) 24 | - int k 25 | 26 | Returns: 27 | - float precision@k 28 | """ 29 | 30 | ground_truth = ground_truth.tocsr() 31 | 32 | no_users, no_items = ground_truth.shape 33 | 34 | pid_array = np.arange(no_items, dtype=np.int32) 35 | 36 | precisions = [] 37 | 38 | for user_id, row in enumerate(ground_truth): 39 | uid_array = np.empty(no_items, dtype=np.int32) 40 | uid_array.fill(user_id) 41 | predictions = model.predict(uid_array, pid_array, 42 | user_features=user_features, 43 | item_features=item_features, 44 | num_threads=4) 45 | 46 | top_k = set(np.argsort(-predictions)[:k]) 47 | true_pids = set(row.indices[row.data == 1]) 48 | 49 | if true_pids: 50 | precisions.append(len(top_k & true_pids) / float(k)) 51 | 52 | return sum(precisions) / len(precisions) 53 | 54 | 55 | def full_auc(model, ground_truth): 56 | """ 57 | Measure AUC for model and ground truth on all items. 58 | 59 | Returns: 60 | - float AUC 61 | """ 62 | 63 | ground_truth = ground_truth.tocsr() 64 | 65 | no_users, no_items = ground_truth.shape 66 | 67 | pid_array = np.arange(no_items, dtype=np.int32) 68 | 69 | scores = [] 70 | 71 | for user_id, row in enumerate(ground_truth): 72 | 73 | predictions = predict(model, user_id, pid_array) 74 | 75 | true_pids = row.indices[row.data == 1] 76 | 77 | grnd = np.zeros(no_items, dtype=np.int32) 78 | grnd[true_pids] = 1 79 | 80 | if len(true_pids): 81 | scores.append(roc_auc_score(grnd, predictions)) 82 | 83 | return sum(scores) / len(scores) 84 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # Recommendations in Keras using triplet loss 2 | 3 | _Note_: a much richer set of neural network recommender models is available as [Spotlight](https://github.com/maciejkula/spotlight). 4 | 5 | Along the lines of BPR [1]. 6 | 7 | [1] Rendle, Steffen, et al. "BPR: Bayesian personalized ranking from implicit feedback." Proceedings of the Twenty-Fifth Conference on Uncertainty in Artificial Intelligence. AUAI Press, 2009. 8 | 9 | This is implemented (more efficiently) in LightFM (https://github.com/lyst/lightfm). See the MovieLens example (https://github.com/lyst/lightfm/blob/master/examples/movielens/example.ipynb) for results comparable to this notebook. 10 | 11 | ## Set up the architecture 12 | A simple dense layer for both users and items: this is exactly equivalent to latent factor matrix when multiplied by binary user and item indices. There are three inputs: users, positive items, and negative items. In the triplet objective we try to make the positive item rank higher than the negative item for that user. 13 | 14 | Because we want just one single embedding for the items, we use shared weights for the positive and negative item inputs (a siamese architecture). 15 | 16 | This is all very simple but could be made arbitrarily complex, with more layers, conv layers and so on. I expect we'll be seeing a lot of papers doing just that. 17 | 18 | 19 | 20 | ```python 21 | """ 22 | Triplet loss network example for recommenders 23 | """ 24 | 25 | from __future__ import print_function 26 | 27 | import numpy as np 28 | 29 | from keras import backend as K 30 | from keras.models import Model 31 | from keras.layers import Embedding, Flatten, Input, merge 32 | from keras.optimizers import Adam 33 | 34 | import data 35 | import metrics 36 | 37 | 38 | def identity_loss(y_true, y_pred): 39 | 40 | return K.mean(y_pred - 0 * y_true) 41 | 42 | 43 | def bpr_triplet_loss(X): 44 | 45 | positive_item_latent, negative_item_latent, user_latent = X 46 | 47 | # BPR loss 48 | loss = 1.0 - K.sigmoid( 49 | K.sum(user_latent * positive_item_latent, axis=-1, keepdims=True) - 50 | K.sum(user_latent * negative_item_latent, axis=-1, keepdims=True)) 51 | 52 | return loss 53 | 54 | 55 | def build_model(num_users, num_items, latent_dim): 56 | 57 | positive_item_input = Input((1, ), name='positive_item_input') 58 | negative_item_input = Input((1, ), name='negative_item_input') 59 | 60 | # Shared embedding layer for positive and negative items 61 | item_embedding_layer = Embedding( 62 | num_items, latent_dim, name='item_embedding', input_length=1) 63 | 64 | user_input = Input((1, ), name='user_input') 65 | 66 | positive_item_embedding = Flatten()(item_embedding_layer( 67 | positive_item_input)) 68 | negative_item_embedding = Flatten()(item_embedding_layer( 69 | negative_item_input)) 70 | user_embedding = Flatten()(Embedding( 71 | num_users, latent_dim, name='user_embedding', input_length=1)( 72 | user_input)) 73 | 74 | loss = merge( 75 | [positive_item_embedding, negative_item_embedding, user_embedding], 76 | mode=bpr_triplet_loss, 77 | name='loss', 78 | output_shape=(1, )) 79 | 80 | model = Model( 81 | input=[positive_item_input, negative_item_input, user_input], 82 | output=loss) 83 | model.compile(loss=identity_loss, optimizer=Adam()) 84 | 85 | return model 86 | ``` 87 | 88 | Using Theano backend. 89 | 90 | 91 | ## Load and transform data 92 | We're going to load the Movielens 100k dataset and create triplets of (user, known positive item, randomly sampled negative item). 93 | 94 | The success metric is AUC: in this case, the probability that a randomly chosen known positive item from the test set is ranked higher for a given user than a ranomly chosen negative item. 95 | 96 | 97 | ```python 98 | latent_dim = 100 99 | num_epochs = 10 100 | 101 | # Read data 102 | train, test = data.get_movielens_data() 103 | num_users, num_items = train.shape 104 | 105 | # Prepare the test triplets 106 | test_uid, test_pid, test_nid = data.get_triplets(test) 107 | 108 | model = build_model(num_users, num_items, latent_dim) 109 | 110 | # Print the model structure 111 | print(model.summary()) 112 | 113 | # Sanity check, should be around 0.5 114 | print('AUC before training %s' % metrics.full_auc(model, test)) 115 | ``` 116 | 117 | ____________________________________________________________________________________________________ 118 | Layer (type) Output Shape Param # Connected to 119 | ==================================================================================================== 120 | positive_item_input (InputLayer) (None, 1) 0 121 | ____________________________________________________________________________________________________ 122 | negative_item_input (InputLayer) (None, 1) 0 123 | ____________________________________________________________________________________________________ 124 | user_input (InputLayer) (None, 1) 0 125 | ____________________________________________________________________________________________________ 126 | item_embedding (Embedding) (None, 1, 100) 168300 positive_item_input[0][0] 127 | negative_item_input[0][0] 128 | ____________________________________________________________________________________________________ 129 | user_embedding (Embedding) (None, 1, 100) 94400 user_input[0][0] 130 | ____________________________________________________________________________________________________ 131 | flatten_7 (Flatten) (None, 100) 0 item_embedding[0][0] 132 | ____________________________________________________________________________________________________ 133 | flatten_8 (Flatten) (None, 100) 0 item_embedding[1][0] 134 | ____________________________________________________________________________________________________ 135 | flatten_9 (Flatten) (None, 100) 0 user_embedding[0][0] 136 | ____________________________________________________________________________________________________ 137 | loss (Merge) (None, 1) 0 flatten_7[0][0] 138 | flatten_8[0][0] 139 | flatten_9[0][0] 140 | ==================================================================================================== 141 | Total params: 262700 142 | ____________________________________________________________________________________________________ 143 | None 144 | AUC before training 0.50247407966 145 | 146 | 147 | ## Run the model 148 | Run for a couple of epochs, checking the AUC after every epoch. 149 | 150 | 151 | ```python 152 | for epoch in range(num_epochs): 153 | 154 | print('Epoch %s' % epoch) 155 | 156 | # Sample triplets from the training data 157 | uid, pid, nid = data.get_triplets(train) 158 | 159 | X = { 160 | 'user_input': uid, 161 | 'positive_item_input': pid, 162 | 'negative_item_input': nid 163 | } 164 | 165 | model.fit(X, 166 | np.ones(len(uid)), 167 | batch_size=64, 168 | nb_epoch=1, 169 | verbose=0, 170 | shuffle=True) 171 | 172 | print('AUC %s' % metrics.full_auc(model, test)) 173 | ``` 174 | 175 | Epoch 0 176 | AUC 0.905896400776 177 | Epoch 1 178 | AUC 0.908241780938 179 | Epoch 2 180 | AUC 0.909650205748 181 | Epoch 3 182 | AUC 0.910820451523 183 | Epoch 4 184 | AUC 0.912184845152 185 | Epoch 5 186 | AUC 0.912632057958 187 | Epoch 6 188 | AUC 0.91326604222 189 | Epoch 7 190 | AUC 0.913786881853 191 | Epoch 8 192 | AUC 0.914638438854 193 | Epoch 9 194 | AUC 0.915375014253 195 | 196 | 197 | The AUC is in the low-90s. At some point we start overfitting, so it would be a good idea to stop early or add some regularization. 198 | -------------------------------------------------------------------------------- /triplet_keras.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Recommendations in Keras using triplet loss\n", 8 | "Along the lines of BPR [1]. \n", 9 | "\n", 10 | "[1] Rendle, Steffen, et al. \"BPR: Bayesian personalized ranking from implicit feedback.\" Proceedings of the Twenty-Fifth Conference on Uncertainty in Artificial Intelligence. AUAI Press, 2009.\n", 11 | "\n", 12 | "This is implemented (more efficiently) in LightFM (https://github.com/lyst/lightfm). See the MovieLens example (https://github.com/lyst/lightfm/blob/master/examples/movielens/example.ipynb) for results comparable to this notebook.\n", 13 | "\n", 14 | "## Set up the architecture\n", 15 | "A simple dense layer for both users and items: this is exactly equivalent to latent factor matrix when multiplied by binary user and item indices. There are three inputs: users, positive items, and negative items. In the triplet objective we try to make the positive item rank higher than the negative item for that user.\n", 16 | "\n", 17 | "Because we want just one single embedding for the items, we use shared weights for the positive and negative item inputs (a siamese architecture).\n", 18 | "\n", 19 | "This is all very simple but could be made arbitrarily complex, with more layers, conv layers and so on. I expect we'll be seeing a lot of papers doing just that.\n" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": 1, 25 | "metadata": { 26 | "collapsed": false 27 | }, 28 | "outputs": [ 29 | { 30 | "name": "stderr", 31 | "output_type": "stream", 32 | "text": [ 33 | "Using Theano backend.\n" 34 | ] 35 | } 36 | ], 37 | "source": [ 38 | "\"\"\"\n", 39 | "Triplet loss network example for recommenders\n", 40 | "\"\"\"\n", 41 | "\n", 42 | "from __future__ import print_function\n", 43 | "\n", 44 | "import numpy as np\n", 45 | "\n", 46 | "from keras import backend as K\n", 47 | "from keras.models import Model\n", 48 | "from keras.layers import Embedding, Flatten, Input, merge\n", 49 | "from keras.optimizers import Adam\n", 50 | "\n", 51 | "import data\n", 52 | "import metrics\n", 53 | "\n", 54 | "\n", 55 | "def identity_loss(y_true, y_pred):\n", 56 | "\n", 57 | " return K.mean(y_pred - 0 * y_true)\n", 58 | "\n", 59 | "\n", 60 | "def bpr_triplet_loss(X):\n", 61 | "\n", 62 | " positive_item_latent, negative_item_latent, user_latent = X\n", 63 | "\n", 64 | " # BPR loss\n", 65 | " loss = 1.0 - K.sigmoid(\n", 66 | " K.sum(user_latent * positive_item_latent, axis=-1, keepdims=True) -\n", 67 | " K.sum(user_latent * negative_item_latent, axis=-1, keepdims=True))\n", 68 | "\n", 69 | " return loss\n", 70 | "\n", 71 | "\n", 72 | "def build_model(num_users, num_items, latent_dim):\n", 73 | "\n", 74 | " positive_item_input = Input((1, ), name='positive_item_input')\n", 75 | " negative_item_input = Input((1, ), name='negative_item_input')\n", 76 | "\n", 77 | " # Shared embedding layer for positive and negative items\n", 78 | " item_embedding_layer = Embedding(\n", 79 | " num_items, latent_dim, name='item_embedding', input_length=1)\n", 80 | "\n", 81 | " user_input = Input((1, ), name='user_input')\n", 82 | "\n", 83 | " positive_item_embedding = Flatten()(item_embedding_layer(\n", 84 | " positive_item_input))\n", 85 | " negative_item_embedding = Flatten()(item_embedding_layer(\n", 86 | " negative_item_input))\n", 87 | " user_embedding = Flatten()(Embedding(\n", 88 | " num_users, latent_dim, name='user_embedding', input_length=1)(\n", 89 | " user_input))\n", 90 | "\n", 91 | " loss = merge(\n", 92 | " [positive_item_embedding, negative_item_embedding, user_embedding],\n", 93 | " mode=bpr_triplet_loss,\n", 94 | " name='loss',\n", 95 | " output_shape=(1, ))\n", 96 | "\n", 97 | " model = Model(\n", 98 | " input=[positive_item_input, negative_item_input, user_input],\n", 99 | " output=loss)\n", 100 | " model.compile(loss=identity_loss, optimizer=Adam())\n", 101 | "\n", 102 | " return model" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "metadata": {}, 108 | "source": [ 109 | "## Load and transform data\n", 110 | "We're going to load the Movielens 100k dataset and create triplets of (user, known positive item, randomly sampled negative item).\n", 111 | "\n", 112 | "The success metric is AUC: in this case, the probability that a randomly chosen known positive item from the test set is ranked higher for a given user than a ranomly chosen negative item." 113 | ] 114 | }, 115 | { 116 | "cell_type": "code", 117 | "execution_count": 6, 118 | "metadata": { 119 | "collapsed": false 120 | }, 121 | "outputs": [ 122 | { 123 | "name": "stdout", 124 | "output_type": "stream", 125 | "text": [ 126 | "____________________________________________________________________________________________________\n", 127 | "Layer (type) Output Shape Param # Connected to \n", 128 | "====================================================================================================\n", 129 | "positive_item_input (InputLayer) (None, 1) 0 \n", 130 | "____________________________________________________________________________________________________\n", 131 | "negative_item_input (InputLayer) (None, 1) 0 \n", 132 | "____________________________________________________________________________________________________\n", 133 | "user_input (InputLayer) (None, 1) 0 \n", 134 | "____________________________________________________________________________________________________\n", 135 | "item_embedding (Embedding) (None, 1, 100) 168300 positive_item_input[0][0] \n", 136 | " negative_item_input[0][0] \n", 137 | "____________________________________________________________________________________________________\n", 138 | "user_embedding (Embedding) (None, 1, 100) 94400 user_input[0][0] \n", 139 | "____________________________________________________________________________________________________\n", 140 | "flatten_7 (Flatten) (None, 100) 0 item_embedding[0][0] \n", 141 | "____________________________________________________________________________________________________\n", 142 | "flatten_8 (Flatten) (None, 100) 0 item_embedding[1][0] \n", 143 | "____________________________________________________________________________________________________\n", 144 | "flatten_9 (Flatten) (None, 100) 0 user_embedding[0][0] \n", 145 | "____________________________________________________________________________________________________\n", 146 | "loss (Merge) (None, 1) 0 flatten_7[0][0] \n", 147 | " flatten_8[0][0] \n", 148 | " flatten_9[0][0] \n", 149 | "====================================================================================================\n", 150 | "Total params: 262700\n", 151 | "____________________________________________________________________________________________________\n", 152 | "None\n", 153 | "AUC before training 0.50247407966\n" 154 | ] 155 | } 156 | ], 157 | "source": [ 158 | "latent_dim = 100\n", 159 | "num_epochs = 10\n", 160 | "\n", 161 | "# Read data\n", 162 | "train, test = data.get_movielens_data()\n", 163 | "num_users, num_items = train.shape\n", 164 | "\n", 165 | "# Prepare the test triplets\n", 166 | "test_uid, test_pid, test_nid = data.get_triplets(test)\n", 167 | "\n", 168 | "model = build_model(num_users, num_items, latent_dim)\n", 169 | "\n", 170 | "# Print the model structure\n", 171 | "print(model.summary())\n", 172 | "\n", 173 | "# Sanity check, should be around 0.5\n", 174 | "print('AUC before training %s' % metrics.full_auc(model, test))" 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "metadata": {}, 180 | "source": [ 181 | "## Run the model\n", 182 | "Run for a couple of epochs, checking the AUC after every epoch." 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": 8, 188 | "metadata": { 189 | "collapsed": false 190 | }, 191 | "outputs": [ 192 | { 193 | "name": "stdout", 194 | "output_type": "stream", 195 | "text": [ 196 | "Epoch 0\n", 197 | "AUC 0.905896400776\n", 198 | "Epoch 1\n", 199 | "AUC 0.908241780938\n", 200 | "Epoch 2\n", 201 | "AUC 0.909650205748\n", 202 | "Epoch 3\n", 203 | "AUC 0.910820451523\n", 204 | "Epoch 4\n", 205 | "AUC 0.912184845152\n", 206 | "Epoch 5\n", 207 | "AUC 0.912632057958\n", 208 | "Epoch 6\n", 209 | "AUC 0.91326604222\n", 210 | "Epoch 7\n", 211 | "AUC 0.913786881853\n", 212 | "Epoch 8\n", 213 | "AUC 0.914638438854\n", 214 | "Epoch 9\n", 215 | "AUC 0.915375014253\n" 216 | ] 217 | } 218 | ], 219 | "source": [ 220 | "for epoch in range(num_epochs):\n", 221 | "\n", 222 | " print('Epoch %s' % epoch)\n", 223 | "\n", 224 | " # Sample triplets from the training data\n", 225 | " uid, pid, nid = data.get_triplets(train)\n", 226 | "\n", 227 | " X = {\n", 228 | " 'user_input': uid,\n", 229 | " 'positive_item_input': pid,\n", 230 | " 'negative_item_input': nid\n", 231 | " }\n", 232 | "\n", 233 | " model.fit(X,\n", 234 | " np.ones(len(uid)),\n", 235 | " batch_size=64,\n", 236 | " nb_epoch=1,\n", 237 | " verbose=0,\n", 238 | " shuffle=True)\n", 239 | "\n", 240 | " print('AUC %s' % metrics.full_auc(model, test))" 241 | ] 242 | }, 243 | { 244 | "cell_type": "markdown", 245 | "metadata": {}, 246 | "source": [ 247 | "The AUC is in the low-90s. At some point we start overfitting, so it would be a good idea to stop early or add some regularization." 248 | ] 249 | } 250 | ], 251 | "metadata": { 252 | "kernelspec": { 253 | "display_name": "Python 2", 254 | "language": "python", 255 | "name": "python2" 256 | }, 257 | "language_info": { 258 | "codemirror_mode": { 259 | "name": "ipython", 260 | "version": 2 261 | }, 262 | "file_extension": ".py", 263 | "mimetype": "text/x-python", 264 | "name": "python", 265 | "nbconvert_exporter": "python", 266 | "pygments_lexer": "ipython2", 267 | "version": "2.7.8" 268 | } 269 | }, 270 | "nbformat": 4, 271 | "nbformat_minor": 0 272 | } 273 | -------------------------------------------------------------------------------- /triplet_movielens.py: -------------------------------------------------------------------------------- 1 | """ 2 | Triplet loss network example for recommenders 3 | """ 4 | 5 | from __future__ import print_function 6 | 7 | import numpy as np 8 | 9 | from keras import backend as K 10 | from keras.models import Model 11 | from keras.layers import Embedding, Flatten, Input, merge 12 | from keras.optimizers import Adam 13 | 14 | import data 15 | import metrics 16 | 17 | 18 | def identity_loss(y_true, y_pred): 19 | 20 | return K.mean(y_pred - 0 * y_true) 21 | 22 | 23 | def bpr_triplet_loss(X): 24 | 25 | positive_item_latent, negative_item_latent, user_latent = X 26 | 27 | # BPR loss 28 | loss = 1.0 - K.sigmoid( 29 | K.sum(user_latent * positive_item_latent, axis=-1, keepdims=True) - 30 | K.sum(user_latent * negative_item_latent, axis=-1, keepdims=True)) 31 | 32 | return loss 33 | 34 | 35 | def build_model(num_users, num_items, latent_dim): 36 | 37 | positive_item_input = Input((1, ), name='positive_item_input') 38 | negative_item_input = Input((1, ), name='negative_item_input') 39 | 40 | # Shared embedding layer for positive and negative items 41 | item_embedding_layer = Embedding( 42 | num_items, latent_dim, name='item_embedding', input_length=1) 43 | 44 | user_input = Input((1, ), name='user_input') 45 | 46 | positive_item_embedding = Flatten()(item_embedding_layer( 47 | positive_item_input)) 48 | negative_item_embedding = Flatten()(item_embedding_layer( 49 | negative_item_input)) 50 | user_embedding = Flatten()(Embedding( 51 | num_users, latent_dim, name='user_embedding', input_length=1)( 52 | user_input)) 53 | 54 | loss = merge( 55 | [positive_item_embedding, negative_item_embedding, user_embedding], 56 | mode=bpr_triplet_loss, 57 | name='loss', 58 | output_shape=(1, )) 59 | 60 | model = Model( 61 | input=[positive_item_input, negative_item_input, user_input], 62 | output=loss) 63 | model.compile(loss=identity_loss, optimizer=Adam()) 64 | 65 | return model 66 | 67 | 68 | if __name__ == '__main__': 69 | 70 | latent_dim = 100 71 | num_epochs = 10 72 | 73 | # Read data 74 | train, test = data.get_movielens_data() 75 | num_users, num_items = train.shape 76 | 77 | # Prepare the test triplets 78 | test_uid, test_pid, test_nid = data.get_triplets(test) 79 | 80 | model = build_model(num_users, num_items, latent_dim) 81 | 82 | # Print the model structure 83 | print(model.summary()) 84 | 85 | # Sanity check, should be around 0.5 86 | print('AUC before training %s' % metrics.full_auc(model, test)) 87 | 88 | for epoch in range(num_epochs): 89 | 90 | print('Epoch %s' % epoch) 91 | 92 | # Sample triplets from the training data 93 | uid, pid, nid = data.get_triplets(train) 94 | 95 | X = { 96 | 'user_input': uid, 97 | 'positive_item_input': pid, 98 | 'negative_item_input': nid 99 | } 100 | 101 | model.fit(X, 102 | np.ones(len(uid)), 103 | batch_size=64, 104 | nb_epoch=1, 105 | verbose=0, 106 | shuffle=True) 107 | 108 | print('AUC %s' % metrics.full_auc(model, test)) 109 | --------------------------------------------------------------------------------