├── .gitignore ├── LICENSE ├── README.md ├── common.py ├── knn_recsys.py ├── knn_recsys_ratings.py ├── lr_hashing_recsys.py ├── random_popularity_dataset.py └── topn_recsys.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | -------------------------------------------------------------------------------- /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 {yyyy} {name of copyright owner} 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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rec-sys-experiments 2 | Some experiments with recommendation systems. 3 | 4 | The script `lr_hashing_recsys.py` is a proof-of-concept for a recommendation system built with Logistic Regression and feature hashing. 5 | 6 | The script `knn_recsys.py` implements a simple nearest-neighbors recommendation system. 7 | -------------------------------------------------------------------------------- /common.py: -------------------------------------------------------------------------------- 1 | from collections import defaultdict 2 | from collections import namedtuple 3 | import csv 4 | 5 | import matplotlib 6 | matplotlib.use("PDF") 7 | import matplotlib.pyplot as plt 8 | import numpy as np 9 | 10 | class GrowingHistogram(object): 11 | def __init__(self, bin_width): 12 | self.bin_width = float(bin_width) 13 | self.bins = defaultdict(int) 14 | 15 | def accumulate(self, value): 16 | bin_idx = int(np.floor(value / self.bin_width)) 17 | self.bins[bin_idx] += 1 18 | 19 | def histogram(self): 20 | offset_idx = 0 21 | n_bins = max(self.bins.iterkeys()) + 1 22 | min_idx = min(self.bins.iterkeys) 23 | 24 | if min_idx < 0: 25 | offset_idx += np.abs(min_idx) 26 | n_bins += np.abs(min_idx) 27 | 28 | counts = [0] * n_bins 29 | lowerbounds = [0.] * (n_bins + 1) 30 | 31 | for bin_idx, count in self.bins.iteritems(): 32 | idx = offset_idx + bin_idx 33 | counts[idx] = count 34 | lowerbounds[idx] = bin_idx * self.bin_width 35 | 36 | lowerbounds[-1] = n_bins * self.bin_width 37 | 38 | return counts, lowerbounds 39 | 40 | def read_ratings(flname): 41 | Rating = namedtuple("Rating", ["user_id", "movie_id", "rating", "timestamp"]) 42 | with open(flname) as fl: 43 | for ln in fl: 44 | user_id, movie_id, rating, timestamp = ln.strip().split("::") 45 | yield Rating(user_id=int(user_id) - 1, 46 | movie_id=int(movie_id) - 1, 47 | rating=float(rating), 48 | timestamp=int(timestamp)) 49 | 50 | 51 | def plot_correlation(flname, title, x_label, y_label, dataset): 52 | """ 53 | Scatter plot with line of best fit 54 | 55 | dataset - tuple of (x_values, y_values) 56 | """ 57 | plt.clf() 58 | plt.hold(True) 59 | plt.scatter(dataset[0], dataset[1], alpha=0.7, color="k") 60 | xs = np.array(dataset[0]) 61 | ys = np.array(dataset[1]) 62 | A = np.vstack([xs, np.ones(len(xs))]).T 63 | m, c = np.linalg.lstsq(A, ys)[0] 64 | plt.plot(xs, m*xs + c, "c-") 65 | plt.xlabel(x_label, fontsize=16) 66 | plt.ylabel(y_label, fontsize=16) 67 | plt.xlim([0.25, max(dataset[0])]) 68 | plt.ylim([10., max(dataset[1])]) 69 | plt.title(title, fontsize=18) 70 | plt.savefig(flname, DPI=200) 71 | 72 | def plot_histogram(flname, title, x_label, datasets): 73 | """ 74 | Histogram 75 | 76 | dataset - list tuples of (frequencies, bins, style) 77 | """ 78 | plt.clf() 79 | plt.hold(True) 80 | max_bin = 0 81 | for frequencies, bins, style in datasets: 82 | xs = [] 83 | ys = [] 84 | max_bin = max(max_bin, max(bins)) 85 | for i, f in enumerate(frequencies): 86 | xs.append(bins[i]) 87 | xs.append(bins[i+1]) 88 | ys.append(f) 89 | ys.append(f) 90 | plt.plot(xs, ys, style) 91 | plt.xlabel(x_label, fontsize=16) 92 | plt.ylabel("Occurrences", fontsize=16) 93 | plt.xlim([0, max_bin + 1]) 94 | plt.title(title, fontsize=18) 95 | plt.savefig(flname, DPI=200) 96 | 97 | def plot_aucs_nnzs(flname, model_bits, aucs, nzs): 98 | fig, ax1 = plt.subplots() 99 | ax1.plot(model_bits, aucs, 'c-') 100 | ax1.set_xlabel('Hashed Features (log_2)', fontsize=16) 101 | # Make the y-axis label and tick labels match the line color. 102 | ax1.set_ylabel('AUC', color='c', fontsize=16) 103 | for tl in ax1.get_yticklabels(): 104 | tl.set_color('c') 105 | 106 | ax2 = ax1.twinx() 107 | ax2.plot(model_bits, nzs, 'k-') 108 | ax2.set_ylabel('Non-zero Weights', color='k', fontsize=16) 109 | for tl in ax2.get_yticklabels(): 110 | tl.set_color('k') 111 | 112 | fig.subplots_adjust(right=0.8) 113 | fig.savefig(flname, DPI=200) 114 | -------------------------------------------------------------------------------- /knn_recsys.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2016 Ronald J. Nowling 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | 17 | import argparse 18 | from collections import defaultdict 19 | import random 20 | 21 | from sklearn.neighbors import NearestNeighbors 22 | from sklearn.metrics import roc_auc_score 23 | 24 | import numpy as np 25 | import scipy.sparse as sp 26 | 27 | from common import read_ratings 28 | 29 | def create_training_sets(ratings, n_training, n_testing): 30 | print "Creating user movie-interaction lists" 31 | 32 | user_interactions = defaultdict(set) 33 | max_movie_id = 0 34 | for r in ratings: 35 | user_interactions[r.user_id].add(r.movie_id) 36 | max_movie_id = max(max_movie_id, r.movie_id) 37 | 38 | 39 | user_interactions = list(user_interactions.values()) 40 | sampled_indices = random.sample(xrange(len(user_interactions)), n_training + n_testing) 41 | 42 | users = [] 43 | movies = [] 44 | interactions = [] 45 | for new_user_id, idx in enumerate(sampled_indices[:n_training]): 46 | users.extend([new_user_id] * len(user_interactions[idx])) 47 | movies.extend(user_interactions[idx]) 48 | interactions.extend([1.] * len(user_interactions[idx])) 49 | 50 | n_movies = max_movie_id + 1 51 | training_matrix = sp.coo_matrix((interactions, (users, movies)), 52 | shape=(n_training, n_movies)).tocsr() 53 | 54 | users = [] 55 | movies = [] 56 | interactions = [] 57 | for new_user_id, idx in enumerate(sampled_indices[n_training:]): 58 | users.extend([new_user_id] * len(user_interactions[idx])) 59 | movies.extend(user_interactions[idx]) 60 | interactions.extend([1.] * len(user_interactions[idx])) 61 | 62 | n_movies = max_movie_id + 1 63 | testing_matrix = sp.coo_matrix((interactions, (users, movies)), 64 | shape=(n_testing, n_movies)).tocsr() 65 | 66 | print training_matrix.shape, testing_matrix.shape 67 | 68 | return training_matrix, testing_matrix 69 | 70 | def train_and_score(metric, training, testing, ks): 71 | print "Training and scoring" 72 | scores = [] 73 | knn = NearestNeighbors(metric=metric, algorithm="brute") 74 | knn.fit(training) 75 | for k in ks: 76 | print "Evaluating for", k, "neighbors" 77 | neighbor_indices = knn.kneighbors(testing, 78 | n_neighbors=k, 79 | return_distance=False) 80 | 81 | all_predicted_scores = [] 82 | all_labels = [] 83 | for user_id in xrange(testing.shape[0]): 84 | user_row = testing[user_id, :] 85 | 86 | _, interaction_indices = user_row.nonzero() 87 | interacted = set(interaction_indices) 88 | non_interacted = set(xrange(testing.shape[1])) - interacted 89 | 90 | n_samples = min(len(non_interacted), len(interacted)) 91 | sampled_interacted = random.sample(interacted, n_samples) 92 | sampled_non_interacted = random.sample(non_interacted, n_samples) 93 | 94 | indices = list(sampled_interacted) 95 | indices.extend(sampled_non_interacted) 96 | labels = [1] * n_samples 97 | labels.extend([0] * n_samples) 98 | 99 | neighbors = training[neighbor_indices[user_id, :], :] 100 | predicted_scores = neighbors.mean(axis=0) 101 | for idx in indices: 102 | all_predicted_scores.append(predicted_scores[0, idx]) 103 | all_labels.extend(labels) 104 | 105 | print len(all_labels), len(all_predicted_scores) 106 | 107 | auc = roc_auc_score(all_labels, all_predicted_scores) 108 | 109 | print "k", k, "AUC", auc 110 | 111 | def parseargs(): 112 | parser = argparse.ArgumentParser() 113 | 114 | parser.add_argument("--ratings-fl", 115 | type=str, 116 | required=True, 117 | help="Ratings file") 118 | 119 | parser.add_argument("--training", 120 | type=int, 121 | default=10000, 122 | help="Number of training samples") 123 | 124 | parser.add_argument("--testing", 125 | type=int, 126 | default=1000, 127 | help="Number of testing samples") 128 | 129 | parser.add_argument("--metric", 130 | type=str, 131 | choices=["euclidean", "cosine"], 132 | default="euclidean", 133 | help="Distance metric") 134 | 135 | parser.add_argument("--ks", 136 | type=int, 137 | nargs="+", 138 | required=True, 139 | help="Number of neigbhors") 140 | 141 | 142 | return parser.parse_args() 143 | 144 | 145 | if __name__ == "__main__": 146 | args = parseargs() 147 | 148 | ratings = read_ratings(args.ratings_fl) 149 | 150 | training, testing = create_training_sets(ratings, args.training, args.testing) 151 | 152 | train_and_score(args.metric, 153 | training, 154 | testing, 155 | args.ks) 156 | 157 | 158 | 159 | -------------------------------------------------------------------------------- /knn_recsys_ratings.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2018 Ronald J. Nowling 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | 17 | import argparse 18 | from collections import defaultdict 19 | import random 20 | 21 | from sklearn.neighbors import NearestNeighbors 22 | from sklearn.metrics import mean_squared_error 23 | from sklearn.preprocessing import Imputer 24 | 25 | import numpy as np 26 | import scipy.sparse as sp 27 | 28 | def read_ratings(flname): 29 | user_ids = [] 30 | movie_ids = [] 31 | ratings = [] 32 | with open(flname) as fl: 33 | # skip header 34 | next(fl) 35 | 36 | for ln in fl: 37 | user_id, movie_id, rating, timestamp = ln.strip().split(",") 38 | user_ids.append(int(user_id)) 39 | movie_ids.append(int(movie_id)) 40 | ratings.append(float(rating)) 41 | 42 | n_movies = max(movie_ids) + 1 43 | n_users = max(user_ids) + 1 44 | 45 | ratings_matrix = np.zeros((n_users, 46 | n_movies)) 47 | 48 | for user_id, movie_id, rating in zip(user_ids, movie_ids, ratings): 49 | ratings_matrix[user_id, movie_id] = rating 50 | 51 | return ratings_matrix 52 | 53 | def parseargs(): 54 | parser = argparse.ArgumentParser() 55 | 56 | parser.add_argument("--ratings-fl", 57 | type=str, 58 | required=True, 59 | help="Ratings file") 60 | 61 | parser.add_argument("--k", 62 | type=int, 63 | required=True, 64 | help="Number of neigbhors") 65 | 66 | return parser.parse_args() 67 | 68 | 69 | if __name__ == "__main__": 70 | args = parseargs() 71 | 72 | # read ratings 73 | print "Reading ratings" 74 | ratings_matrix = read_ratings(args.ratings_fl) 75 | 76 | n_users = ratings_matrix.shape[0] 77 | n_movies = ratings_matrix.shape[1] 78 | n_training_users = int(0.8 * n_users) 79 | 80 | # split test / train 81 | print "Splitting test / train" 82 | train_ids = random.sample(xrange(n_users), 83 | n_training_users) 84 | test_ids = set(xrange(n_users)) - set(train_ids) 85 | test_ids = list(test_ids) 86 | n_test_users = len(test_ids) 87 | 88 | training_matrix = ratings_matrix[train_ids, :] 89 | testing_matrix = ratings_matrix[test_ids, :] 90 | true_ratings = testing_matrix.copy() 91 | 92 | # impute unknown ratings 93 | print "Imputing values" 94 | imputer = Imputer(missing_values=0) 95 | training_imputed_matrix = imputer.fit_transform(training_matrix) 96 | testing_imputed_matrix = imputer.transform(testing_matrix) 97 | 98 | # imputing culls columns with zero values so we need 99 | # to chop down the original matrices 100 | selected_columns = [] 101 | for movie_id in xrange(n_movies): 102 | if not np.isnan(imputer.statistics_[movie_id]): 103 | selected_columns.append(movie_id) 104 | 105 | training_matrix = training_matrix[:, selected_columns] 106 | testing_matrix = testing_matrix[:, selected_columns] 107 | true_ratings = true_ratings[:, selected_columns] 108 | 109 | n_remaining_movies = training_matrix.shape[1] 110 | 111 | # perform predictions 112 | print "Performing kNN search" 113 | knn = NearestNeighbors() 114 | knn.fit(training_imputed_matrix) 115 | 116 | # returns n_test_users x k matrix 117 | neighbor_indices = knn.kneighbors(testing_imputed_matrix, 118 | n_neighbors=args.k, 119 | return_distance=False) 120 | 121 | # compute average ratings for each user 122 | print "Computing average ratings" 123 | predicted_ratings = np.zeros((n_test_users, 124 | n_remaining_movies)) 125 | 126 | for user_id in xrange(n_test_users): 127 | neighbors = neighbor_indices[user_id, :] 128 | predicted_ratings[user_id, :] = np.average(training_imputed_matrix[neighbors, :], axis=0) 129 | 130 | # compute RMSE only for movies that have been rated 131 | print "Computing RMSE" 132 | squared_error = 0.0 133 | n = 0 134 | for user_id in xrange(n_test_users): 135 | nonzero_ratings = [] 136 | for movie_id in xrange(n_remaining_movies): 137 | if true_ratings[user_id, movie_id] > 0.0: 138 | nonzero_ratings.append(movie_id) 139 | 140 | squared_error += np.sum((true_ratings[user_id, nonzero_ratings] - predicted_ratings[user_id, nonzero_ratings]) ** 2) 141 | n += len(nonzero_ratings) 142 | 143 | rmse = np.sqrt(squared_error / n) 144 | 145 | print "Root Mean-Squared Error:", rmse 146 | -------------------------------------------------------------------------------- /lr_hashing_recsys.py: -------------------------------------------------------------------------------- 1 | """ 2 | Proof of concept for a recommendation system implemented using Logistic Regression and feature hashing. You'll need to download one of the MovieLens datasets from http://grouplens.org/datasets/movielens/. 3 | 4 | Copyright 2016 Ronald J. Nowling 5 | 6 | Licensed under the Apache License, Version 2.0 (the "License"); 7 | you may not use this file except in compliance with the License. 8 | You may obtain a copy of the License at 9 | 10 | http://www.apache.org/licenses/LICENSE-2.0 11 | 12 | Unless required by applicable law or agreed to in writing, software 13 | distributed under the License is distributed on an "AS IS" BASIS, 14 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | See the License for the specific language governing permissions and 16 | limitations under the License. 17 | """ 18 | 19 | import argparse 20 | from collections import defaultdict 21 | from datetime import date 22 | import random 23 | 24 | from sklearn.feature_extraction import FeatureHasher 25 | from sklearn.linear_model import SGDClassifier 26 | from sklearn.metrics import roc_curve 27 | from sklearn.metrics import roc_auc_score 28 | from sklearn.metrics import confusion_matrix 29 | 30 | import numpy as np 31 | import scipy.sparse as sp 32 | 33 | from common import read_ratings 34 | from common import plot_aucs_nnzs 35 | 36 | def create_training_sets(ratings): 37 | print "Creating user movie-interaction lists" 38 | user_movies = defaultdict(set) 39 | max_movie_id = 0 40 | for r in ratings: 41 | user_movies[r.user_id].add(r.movie_id) 42 | max_movie_id = max(max_movie_id, r.movie_id) 43 | 44 | 45 | training_set = [] 46 | test_set = [] 47 | for user_id, movie_ids in user_movies.iteritems(): 48 | if random.random() >= 0.5: 49 | training_set.append((user_id, movie_ids)) 50 | else: 51 | test_set.append((user_id, movie_ids)) 52 | 53 | return max_movie_id, training_set, test_set 54 | 55 | def generate_features(max_movie_id, seen_movies): 56 | all_movie_ids = set(range(0, max_movie_id + 1)) 57 | seen_pairs = [] 58 | unseen_pairs = [] 59 | 60 | # positive examples 61 | for movie_id1 in seen_movies: 62 | movie_pairs = dict() 63 | for movie_id2 in seen_movies: 64 | # product with itself will always be 1 when the label is 1 65 | # and so will result in model overfitting 66 | if movie_id1 != movie_id2: 67 | movie_pairs["%s_%s" % (movie_id1, movie_id2)] = 1. 68 | seen_pairs.append(movie_pairs) 69 | 70 | # negative_examples 71 | unseen_movies = all_movie_ids - seen_movies 72 | for movie_id1 in random.sample(unseen_movies, len(seen_movies)): 73 | movie_pairs = dict() 74 | for movie_id2 in seen_movies: 75 | movie_pairs["%s_%s" % (movie_id1, movie_id2)] = 1. 76 | unseen_pairs.append(movie_pairs) 77 | 78 | labels = np.hstack([np.ones(len(seen_pairs)), np.zeros(len(unseen_pairs))]) 79 | 80 | return labels, (seen_pairs, unseen_pairs) 81 | 82 | 83 | def train_and_score(max_movie_id, training, testset, model_sizes): 84 | extractors = dict() 85 | models = dict() 86 | 87 | print "Creating models" 88 | for model_size in model_sizes: 89 | extractors[model_size] = FeatureHasher(n_features=2**model_size) 90 | models[model_size] = SGDClassifier(loss="log", penalty="L2") 91 | 92 | print "Training" 93 | for i, (user_id, seen_movies) in enumerate(training): 94 | print "Training on user", i, user_id 95 | labels, (seen_pairs, unseen_pairs) = generate_features(max_movie_id, seen_movies) 96 | for model_size, extractor in extractors.iteritems(): 97 | seen_features = extractor.transform(seen_pairs) 98 | unseen_features = extractor.transform(unseen_pairs) 99 | features = sp.vstack([seen_features, unseen_features]) 100 | model = models[model_size] 101 | model.partial_fit(features, labels, classes=[0, 1]) 102 | 103 | print "Testing" 104 | all_labels = [] 105 | all_predicted_labels = defaultdict(list) 106 | all_predicted_prob = defaultdict(list) 107 | for i, (user_id, seen_movies) in enumerate(testset): 108 | print "Testing on user", i, user_id 109 | labels, (seen_pairs, unseen_pairs) = generate_features(max_movie_id, seen_movies) 110 | all_labels.extend(labels) 111 | 112 | for model_size, extractor in extractors.iteritems(): 113 | seen_features = extractor.transform(seen_pairs) 114 | unseen_features = extractor.transform(unseen_pairs) 115 | features = sp.vstack([seen_features, unseen_features]) 116 | 117 | model = models[model_size] 118 | predicted_labels = model.predict(features) 119 | predicted_prob = model.predict_proba(features) 120 | all_predicted_labels[model_size].extend(predicted_labels) 121 | # Probabilities for positive class 122 | all_predicted_prob[model_size].extend(predicted_prob[:, 1]) 123 | 124 | print "Scoring" 125 | aucs = [] 126 | nnz_features = [] 127 | for model_size, model in models.iteritems(): 128 | pred_log_prob = all_predicted_prob[model_size] 129 | auc = roc_auc_score(all_labels, pred_log_prob) 130 | cm = confusion_matrix(all_labels, all_predicted_labels[model_size]) 131 | print "Model size", model_size, "auc", auc 132 | print cm 133 | print 134 | aucs.append(auc) 135 | nnz_features.append(np.count_nonzero(model.coef_)) 136 | 137 | return aucs, nnz_features 138 | 139 | 140 | def parseargs(): 141 | parser = argparse.ArgumentParser() 142 | 143 | parser.add_argument("--ratings-fl", 144 | type=str, 145 | required=True, 146 | help="Ratings file") 147 | 148 | parser.add_argument("--figures-dir", 149 | type=str, 150 | required=True, 151 | help="Directory for outputting figures") 152 | 153 | parser.add_argument("--model-bits", 154 | type=int, 155 | nargs="+", 156 | help="Model sizes in terms of bits") 157 | 158 | return parser.parse_args() 159 | 160 | 161 | if __name__ == "__main__": 162 | args = parseargs() 163 | 164 | ratings = read_ratings(args.ratings_fl) 165 | max_movie_id, training, test = create_training_sets(ratings) 166 | 167 | training = random.sample(training, 1000) 168 | test = random.sample(test, 100) 169 | 170 | aucs, nnzs = train_and_score(max_movie_id, training, test, args.model_bits) 171 | 172 | plot_aucs_nnzs(args.figures_dir + "/lr_hashing_auc_nnzs.png", 173 | args.model_bits, 174 | aucs, 175 | nnzs) 176 | -------------------------------------------------------------------------------- /random_popularity_dataset.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2016 Ronald J. Nowling 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | 17 | import argparse 18 | from collections import defaultdict 19 | import random 20 | 21 | from sklearn.neighbors import NearestNeighbors 22 | from sklearn.metrics import roc_auc_score 23 | 24 | import numpy as np 25 | import scipy.sparse as sp 26 | 27 | from common import read_ratings 28 | 29 | def accumulate_rating_counts(ratings): 30 | movie_interactions = defaultdict(int) 31 | max_user_id = 0 32 | for r in ratings: 33 | movie_interactions[r.movie_id] += 1 34 | max_user_id = max(max_user_id, r.user_id) 35 | 36 | return max_user_id, movie_interactions 37 | 38 | def generate_dataset(max_user_id, movie_interactions): 39 | for m, count in movie_interactions.iteritems(): 40 | interacting_users = random.sample(xrange(max_user_id + 1), count) 41 | for u in interacting_users: 42 | yield (u + 1, m + 1, 1.0, 1) 43 | 44 | def parseargs(): 45 | parser = argparse.ArgumentParser() 46 | 47 | parser.add_argument("--input-ratings-fl", 48 | type=str, 49 | required=True, 50 | help="Input ratings file") 51 | 52 | parser.add_argument("--output-ratings-fl", 53 | type=str, 54 | required=True, 55 | help="Output ratings file") 56 | 57 | return parser.parse_args() 58 | 59 | 60 | if __name__ == "__main__": 61 | args = parseargs() 62 | 63 | input_ratings = read_ratings(args.input_ratings_fl) 64 | max_user_id, interaction_counts = accumulate_rating_counts(input_ratings) 65 | 66 | with open(args.output_ratings_fl, "w") as output_fl: 67 | for t in generate_dataset(max_user_id, interaction_counts): 68 | line_contents = "::".join(map(str, t)) 69 | output_fl.write(line_contents) 70 | output_fl.write("\n") 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /topn_recsys.py: -------------------------------------------------------------------------------- 1 | """ 2 | Copyright 2016 Ronald J. Nowling 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and 14 | limitations under the License. 15 | """ 16 | 17 | import argparse 18 | from collections import defaultdict 19 | import random 20 | 21 | from sklearn.neighbors import NearestNeighbors 22 | from sklearn.metrics import roc_auc_score 23 | 24 | import numpy as np 25 | import scipy.sparse as sp 26 | 27 | from common import read_ratings 28 | 29 | def create_training_sets(ratings, n_training, n_testing): 30 | print "Creating user movie-interaction lists" 31 | 32 | user_interactions = defaultdict(set) 33 | max_movie_id = 0 34 | for r in ratings: 35 | user_interactions[r.user_id].add(r.movie_id) 36 | max_movie_id = max(max_movie_id, r.movie_id) 37 | 38 | 39 | user_interactions = list(user_interactions.values()) 40 | sampled_indices = random.sample(xrange(len(user_interactions)), n_training + n_testing) 41 | 42 | users = [] 43 | movies = [] 44 | interactions = [] 45 | for new_user_id, idx in enumerate(sampled_indices[:n_training]): 46 | users.extend([new_user_id] * len(user_interactions[idx])) 47 | movies.extend(user_interactions[idx]) 48 | interactions.extend([1.] * len(user_interactions[idx])) 49 | 50 | n_movies = max_movie_id + 1 51 | training_matrix = sp.coo_matrix((interactions, (users, movies)), 52 | shape=(n_training, n_movies)).tocsr() 53 | 54 | users = [] 55 | movies = [] 56 | interactions = [] 57 | for new_user_id, idx in enumerate(sampled_indices[n_training:]): 58 | users.extend([new_user_id] * len(user_interactions[idx])) 59 | movies.extend(user_interactions[idx]) 60 | interactions.extend([1.] * len(user_interactions[idx])) 61 | 62 | n_movies = max_movie_id + 1 63 | testing_matrix = sp.coo_matrix((interactions, (users, movies)), 64 | shape=(n_testing, n_movies)).tocsr() 65 | 66 | print training_matrix.shape, testing_matrix.shape 67 | 68 | return training_matrix, testing_matrix 69 | 70 | def train_and_score(training, testing): 71 | print "Training and scoring" 72 | n_users = training.shape[0] 73 | predicted_scores = training.sum(axis=0) / float(n_users) 74 | print predicted_scores.shape 75 | 76 | all_predicted_scores = [] 77 | all_labels = [] 78 | for user_id in xrange(testing.shape[0]): 79 | user_row = testing[user_id, :] 80 | 81 | _, interaction_indices = user_row.nonzero() 82 | interacted = set(interaction_indices) 83 | non_interacted = set(xrange(testing.shape[1])) - interacted 84 | 85 | n_samples = min(len(non_interacted), len(interacted)) 86 | sampled_interacted = random.sample(interacted, n_samples) 87 | sampled_non_interacted = random.sample(non_interacted, n_samples) 88 | 89 | indices = list(sampled_interacted) 90 | indices.extend(sampled_non_interacted) 91 | labels = [1] * n_samples 92 | labels.extend([0] * n_samples) 93 | 94 | for idx in indices: 95 | all_predicted_scores.append(predicted_scores[0, idx]) 96 | all_labels.extend(labels) 97 | 98 | print len(all_labels), len(all_predicted_scores) 99 | 100 | auc = roc_auc_score(all_labels, all_predicted_scores) 101 | 102 | print "AUC", auc 103 | 104 | def parseargs(): 105 | parser = argparse.ArgumentParser() 106 | 107 | parser.add_argument("--ratings-fl", 108 | type=str, 109 | required=True, 110 | help="Ratings file") 111 | 112 | parser.add_argument("--training", 113 | type=int, 114 | default=10000, 115 | help="Number of training samples") 116 | 117 | parser.add_argument("--testing", 118 | type=int, 119 | default=1000, 120 | help="Number of testing samples") 121 | 122 | return parser.parse_args() 123 | 124 | 125 | if __name__ == "__main__": 126 | args = parseargs() 127 | 128 | ratings = read_ratings(args.ratings_fl) 129 | 130 | training, testing = create_training_sets(ratings, args.training, args.testing) 131 | 132 | train_and_score(training, 133 | testing) 134 | 135 | 136 | 137 | --------------------------------------------------------------------------------