Below we define several wrappers for well known losses that are defined and implemented in the Pytorch library. The main idea is that we need to flatten our prediction before we pass them accordingly to the chosen loss function.
Same as whatever func is, but with flattened input and target.
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
The FlatLoss class creates a callable that will do whatever the function that we pass would do, but with flattened input and target before the operation.
This package implements several neural network architectures that can be used to build recommendation systems. Users of the library can add or define their own implementations or use the existing ones. There are two layers that every architecture should define:
33 |
34 |
user_embeddings: The user embedding matrix
35 |
item_embeddings: The item embedding matrix
36 |
37 |
Every implementation should be a subclass of torch.nn.Module.
This architecture is the simplest one to implement Collaborative Filtering. It only defines the embedding matrices for users and items and the final rating is computed by the dot product of the corresponding rows.
Modules can also contain other Modules, allowing to nest them in
66 | a tree structure. You can assign the submodules as regular attributes::
67 |
68 |
import torch.nn as nn
69 | import torch.nn.functional as F
70 |
71 | class Model(nn.Module):
72 | def __init__(self):
73 | super(Model, self).__init__()
74 | self.conv1 = nn.Conv2d(1, 20, 5)
75 | self.conv2 = nn.Conv2d(20, 20, 5)
76 |
77 | def forward(self, x):
78 | x = F.relu(self.conv1(x))
79 | return F.relu(self.conv2(x))
80 |
81 |
82 |
Submodules assigned in this way will be registered, and will have their
83 | parameters converted too when you call :meth:to, etc.
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
Arguments:
96 |
97 |
n_users (int): The number of unique users
98 |
n_items (int): The number of unique items
99 |
factors (int): The dimension of the embedding space
100 |
user_embeddings (torch.tensor): Pre-trained weights for the user embedding matrix
101 |
freeze_users (bool): True if we want to keep the user weights as is (i.e. non-trainable)
102 |
item_embeddings (torch.tensor): Pre-trained weights for the item embedding matrix
103 |
freeze_item (bool): True if we want to keep the item weights as is (i.e. non-trainable)
104 |
init (torch.nn.init): The initialization method of the embedding matrices - default: torch.nn.init.normal_
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
# initialize the model with 100 users, 50 items and a 16-dimensional embedding space
116 | model=SimpleCF(100,50,16,mean=0.,std=.1,binary=True)
117 |
118 | # predict the rating that user 3 would give to item 33
119 | model(torch.tensor([2]),torch.tensor([32]))
120 |
Recall@k is a standard information retrieval metric. For example, suppose that we computed recall@10 equal to 40% in our top-10 recommendation system. This means that 40% of the total number of the relevant items appear in the top-k results.
32 |
More formally we have:
33 | $$Recall@k = \frac{\text{number of recommended items @k that are relevant}}{\text{total number of relevant items}}$$
34 |
Precision@k is a standard information retrieval metric. For example, an interpretation of precision@k computed at 80% could be that that 80% of the total number of the recommendations made are relevant to the user.
92 |
More formally we have:
93 | $$Precision@k = \frac{\text{number of recommended items @k that are relevant}}{\text{number of recommended items @k}}$$
94 |
Computes Precision@k from the given predictions and targets sets.
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
Arguments:
124 |
125 |
predictions (list[int]): The list of recommended items
126 |
targets (list[int]): The list of relevant items
127 |
k (int): The number up to where the recall is computed - default: 10
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
predictions=(5,6,32,67,1,15,7,89,10,43)
139 | targets=(15,5,44,35,67,101,7,80,43,12)
140 |
141 | assertprecision_at_k(predictions,targets,5)==.4,'Recall@k should be equal to 2/5 = 0.4'
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 | {% endraw %}
150 |
151 |
152 |
153 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # CF STEP - Incremental Collaborative Filtering
2 | > Incremental learning for recommender systems
3 |
4 | **This repository is no longer maintained, but is being kept around for educational purposes.**
5 |
6 | CF STEP is an open-source library, written in python, that enables fast implementation of incremental learning recommender systems. The library is a by-product of the research project [CloudDBAppliance](https://clouddb.eu/).
7 |
8 | ## Install
9 |
10 | Run `pip install cf-step` to install the library in your environment.
11 |
12 | ## How to use
13 |
14 | For this example, we use the popular [movielens](https://grouplens.org/datasets/movielens/) dataset. The dataset has collected and made available rating data sets from the [MovieLens](http://movielens.org) web site. The data sets were collected over various periods of time, depending on the size of the set.
15 |
16 | First let us load the data in a pandas `DataFrame`. We assume that the reader has downloaded the 1m movielense dataset and have unziped it in the `/tmp` folder.
17 |
18 | > To avoid creating a user and movie vocabularies we turn each user and movie to a categorical feature and use the pandas convenient cat attribute to get the codes
19 |
20 | ```python
21 | # local
22 |
23 | # load the data
24 | col_names = ['user_id', 'movie_id', 'rating', 'timestamp']
25 | ratings_df = pd.read_csv('/tmp/ratings.dat', delimiter='::', names=col_names, engine='python')
26 |
27 | # transform users and movies to categorical features
28 | ratings_df['user_id'] = ratings_df['user_id'].astype('category')
29 | ratings_df['movie_id'] = ratings_df['movie_id'].astype('category')
30 |
31 | # use the codes to avoid creating separate vocabularies
32 | ratings_df['user_code'] = ratings_df['user_id'].cat.codes.astype(int)
33 | ratings_df['movie_code'] = ratings_df['movie_id'].cat.codes.astype(int)
34 |
35 | ratings_df.head()
36 | ```
37 |
38 |
39 |
40 |
41 |
42 |
55 |
56 |
57 |
58 |
59 |
user_id
60 |
movie_id
61 |
rating
62 |
timestamp
63 |
user_code
64 |
movie_code
65 |
66 |
67 |
68 |
69 |
0
70 |
1
71 |
1193
72 |
5
73 |
978300760
74 |
0
75 |
1104
76 |
77 |
78 |
1
79 |
1
80 |
661
81 |
3
82 |
978302109
83 |
0
84 |
639
85 |
86 |
87 |
2
88 |
1
89 |
914
90 |
3
91 |
978301968
92 |
0
93 |
853
94 |
95 |
96 |
3
97 |
1
98 |
3408
99 |
4
100 |
978300275
101 |
0
102 |
3177
103 |
104 |
105 |
4
106 |
1
107 |
2355
108 |
5
109 |
978824291
110 |
0
111 |
2162
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 | Using the codes we can see how many users and movies are in the dataset.
120 |
121 | ```python
122 | # local
123 | n_users = ratings_df['user_code'].max() + 1
124 | n_movies = ratings_df['movie_code'].max() + 1
125 |
126 | print(f'There are {n_users} unique users and {n_movies} unique movies in the movielens dataset.')
127 | ```
128 |
129 | There are 6040 unique users and 3706 unique movies in the movielens dataset.
130 |
131 |
132 | We will sort the data by Timestamp so as to simulate streaming events.
133 |
134 | ```python
135 | # local
136 | data_df = ratings_df.sort_values(by='timestamp')
137 | ```
138 |
139 | The `Step` model supports only positive feedback. Thus, we will consider a rating of 5 as positive feedback and discard any other. We want to identify likes with `1` and dislikes with `0`.
140 |
141 | ```python
142 | # local
143 | # more than 4 -> 1, less than 5 -> 0
144 | data_df['preference'] = np.where(data_df['rating'] > 4, 1, 0)
145 | # keep only ones and discard the others
146 | data_df_cleaned = data_df.loc[data_df['preference'] == 1]
147 |
148 | data_df_cleaned.head()
149 | ```
150 |
151 |
152 |
153 |
154 |
155 |
168 |
169 |
170 |
171 |
172 |
user_id
173 |
movie_id
174 |
rating
175 |
timestamp
176 |
user_code
177 |
movie_code
178 |
preference
179 |
180 |
181 |
182 |
183 |
999873
184 |
6040
185 |
593
186 |
5
187 |
956703954
188 |
6039
189 |
579
190 |
1
191 |
192 |
193 |
1000192
194 |
6040
195 |
2019
196 |
5
197 |
956703977
198 |
6039
199 |
1839
200 |
1
201 |
202 |
203 |
999920
204 |
6040
205 |
213
206 |
5
207 |
956704056
208 |
6039
209 |
207
210 |
1
211 |
212 |
213 |
999967
214 |
6040
215 |
3111
216 |
5
217 |
956704056
218 |
6039
219 |
2895
220 |
1
221 |
222 |
223 |
999971
224 |
6040
225 |
2503
226 |
5
227 |
956704191
228 |
6039
229 |
2309
230 |
1
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 | Following, let us initialize our model.
239 |
240 | ```python
241 | # local
242 | net = SimpleCF(n_users, n_movies, factors=128, mean=0., std=.1)
243 | objective = lambda pred, targ: targ - pred
244 | optimizer = SGD(net.parameters(), lr=0.06)
245 | device = 'cuda' if torch.cuda.is_available() else 'cpu'
246 |
247 | model = Step(net, objective, optimizer, device=device)
248 | ```
249 |
250 | Finally, let us get 20% of the data to fit the model for bootstrapping and create the Pytorch Dataset that we will use.
251 |
252 | ```python
253 | # local
254 | pct = int(data_df_cleaned.shape[0] * .2)
255 | bootstrapping_data = data_df_cleaned[:pct]
256 | ```
257 |
258 | We will create a dataset from our Dataframe. We extract four elements:
259 |
260 | * The user code
261 | * The movie code
262 | * The rating
263 | * The preference
264 |
265 | ```python
266 | # local
267 | features = ['user_code', 'movie_code', 'rating']
268 | target = ['preference']
269 |
270 | data_set = TensorDataset(torch.tensor(bootstrapping_data[features].values),
271 | torch.tensor(bootstrapping_data[target].values))
272 | ```
273 |
274 | Create the Pytorch DataLoader that we will use. Batch size should always be `1` for online training.
275 |
276 | ```python
277 | # local
278 | data_loader = DataLoader(data_set, batch_size=512, shuffle=False)
279 | ```
280 |
281 | Let us now use the *batch_fit()* method of the *Step* trainer to bootstrap our model.
282 |
283 | ```python
284 | # local
285 | model.batch_fit(data_loader)
286 | ```
287 |
288 | 100%|██████████| 89/89 [00:01<00:00, 81.00it/s]
289 |
290 |
291 | Then, to simulate streaming we get the remaining data and create a different data set.
292 |
293 | ```python
294 | # local
295 | data_df_step = data_df_cleaned.drop(bootstrapping_data.index)
296 | data_df_step = data_df_step.reset_index(drop=True)
297 | data_df_step.head()
298 |
299 | # create the DataLoader
300 | stream_data_set = TensorDataset(torch.tensor(data_df_step[features].values),
301 | torch.tensor(data_df_step[target].values))
302 | stream_data_loader = DataLoader(stream_data_set, batch_size=1, shuffle=False)
303 | ```
304 |
305 | Simulate the stream...
306 |
307 | ```python
308 | # local
309 | k = 10 # we keep only the top 10 recommendations
310 | recalls = []
311 | known_users = []
312 |
313 | with tqdm(total=len(stream_data_loader)) as pbar:
314 | for idx, (features, preferences) in enumerate(stream_data_loader):
315 | itr = idx + 1
316 |
317 | user = features[:, 0]
318 | item = features[:, 1]
319 | rtng = features[:, 2]
320 | pref = preferences
321 |
322 | if user.item() in known_users:
323 | predictions = model.predict(user, k)
324 | recall = recall_at_k(predictions.tolist(), item.tolist(), k)
325 | recalls.append(recall)
326 | model.step(user, item, rtng, pref)
327 | else:
328 | model.step(user, item, rtng, pref)
329 |
330 | known_users.append(user.item())
331 | pbar.update(1)
332 | ```
333 |
334 | 100%|██████████| 181048/181048 [15:23<00:00, 195.94it/s]
335 |
336 |
337 | Last but not least, we visualize the results of the recall@10 metric, using a moving average window of 5k elements.
338 |
339 | ```python
340 | # local
341 | avgs = moving_avg(recalls, 5000)
342 |
343 | plt.title('Recall@10')
344 | plt.xlabel('Iterations')
345 | plt.ylabel('Metric')
346 | plt.ylim(0., .1)
347 | plt.plot(avgs)
348 | plt.show()
349 | ```
350 |
351 |
352 | 
353 |
354 |
355 | Finally, save the model's weights.
356 |
357 | ```python
358 | # local
359 | model.save(os.path.join('artefacts', 'positive_step.pt'))
360 | ```
361 |
362 | ## References
363 |
364 | 1. Vinagre, J., Jorge, A. M., & Gama, J. (2014, July). Fast incremental matrix factorization for recommendation with positive-only feedback. In International Conference on User Modeling, Adaptation, and Personalization (pp. 459-470). Springer, Cham.
365 | 2. Hu, Y., Koren, Y., & Volinsky, C. (2008, December). Collaborative filtering for implicit feedback datasets. In 2008 Eighth IEEE International Conference on Data Mining (pp. 263-272). Ieee.
366 |
--------------------------------------------------------------------------------
/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 |
--------------------------------------------------------------------------------
/nbs/step.ipynb:
--------------------------------------------------------------------------------
1 | {
2 | "cells": [
3 | {
4 | "cell_type": "code",
5 | "execution_count": null,
6 | "metadata": {},
7 | "outputs": [],
8 | "source": [
9 | "# default_exp step"
10 | ]
11 | },
12 | {
13 | "cell_type": "code",
14 | "execution_count": null,
15 | "metadata": {},
16 | "outputs": [],
17 | "source": [
18 | "# hide\n",
19 | "from nbdev.showdoc import *"
20 | ]
21 | },
22 | {
23 | "cell_type": "code",
24 | "execution_count": null,
25 | "metadata": {},
26 | "outputs": [],
27 | "source": [
28 | "# export\n",
29 | "import torch\n",
30 | "import numpy as np\n",
31 | "\n",
32 | "from abc import ABCMeta\n",
33 | "from abc import abstractmethod\n",
34 | "from typing import Callable\n",
35 | "from tqdm import tqdm"
36 | ]
37 | },
38 | {
39 | "cell_type": "markdown",
40 | "metadata": {},
41 | "source": [
42 | "# Step\n",
43 | "\n",
44 | "> *Incremental Collaborative Filtering* algorithms."
45 | ]
46 | },
47 | {
48 | "cell_type": "markdown",
49 | "metadata": {},
50 | "source": [
51 | "## Step Base\n",
52 | "\n",
53 | "This class defines the interface that every `Step` module should implement. Namely, each class should implement five methods:\n",
54 | "\n",
55 | "* `batch_fit`: To support batch training\n",
56 | "* `step`: To support incremental learning\n",
57 | "* `predict`: To offer recommendations\n",
58 | "* `save`: To save the model parameters\n",
59 | "* `load`: To load the model parameters"
60 | ]
61 | },
62 | {
63 | "cell_type": "code",
64 | "execution_count": null,
65 | "metadata": {},
66 | "outputs": [],
67 | "source": [
68 | "# export\n",
69 | "class StepBase:\n",
70 | " \"\"\"Defines the interface that all step models here expose.\"\"\"\n",
71 | " __metaclass__ = ABCMeta\n",
72 | " \n",
73 | " @abstractmethod\n",
74 | " def batch_fit(self, data_loader: torch.utils.data.DataLoader, epochs: int):\n",
75 | " \"\"\"Trains the model on a batch of user-item interactions.\"\"\"\n",
76 | " pass\n",
77 | " \n",
78 | " @abstractmethod\n",
79 | " def step(self, user: torch.tensor, item: torch.tensor, \n",
80 | " rating: torch.tensor, preference: torch.tensor):\n",
81 | " \"\"\"Trains the model incrementally.\"\"\"\n",
82 | " pass\n",
83 | " \n",
84 | " @abstractmethod\n",
85 | " def predict(self, user: torch.tensor, k: int):\n",
86 | " \"\"\"Recommends the top-k items to a specific user.\"\"\"\n",
87 | " pass\n",
88 | " \n",
89 | " @abstractmethod\n",
90 | " def save(self, path: str):\n",
91 | " \"\"\"Saves the model parameters to the given path.\"\"\"\n",
92 | " pass\n",
93 | " \n",
94 | " @abstractmethod\n",
95 | " def load(self, path: str):\n",
96 | " \"\"\"Loads the model parameters from a given path.\"\"\"\n",
97 | " pass"
98 | ]
99 | },
100 | {
101 | "cell_type": "markdown",
102 | "metadata": {},
103 | "source": [
104 | "## Step\n",
105 | "\n",
106 | "The step class implements the basic *Incremental Collaborative Filtering* recommender system."
107 | ]
108 | },
109 | {
110 | "cell_type": "code",
111 | "execution_count": null,
112 | "metadata": {},
113 | "outputs": [],
114 | "source": [
115 | "# export\n",
116 | "class Step(StepBase):\n",
117 | " \"\"\"Incremental and batch training of recommender systems.\"\"\"\n",
118 | " def __init__(self, model: torch.nn.Module, objective: Callable,\n",
119 | " optimizer: Callable, conf_func: Callable = lambda x: torch.tensor(1),\n",
120 | " device: str = 'cpu'):\n",
121 | " self.model = model.to(device)\n",
122 | " self.objective = objective\n",
123 | " self.optimizer = optimizer\n",
124 | " self.conf_func = conf_func\n",
125 | " self.device = device\n",
126 | "\n",
127 | " # check if the user has provided user and item embeddings\n",
128 | " assert self.model.user_embeddings, 'User embedding matrix could not be found.'\n",
129 | " assert self.model.item_embeddings, 'Item embedding matrix could not be found.'\n",
130 | "\n",
131 | " @property\n",
132 | " def user_embeddings(self):\n",
133 | " return self.model.user_embeddings\n",
134 | "\n",
135 | " @property\n",
136 | " def item_embeddings(self):\n",
137 | " return self.model.item_embeddings\n",
138 | "\n",
139 | " def batch_fit(self, data_loader: torch.utils.data.DataLoader, epochs: int = 1):\n",
140 | " \"\"\"Trains the model on a batch of user-item interactions.\"\"\"\n",
141 | " self.model.train()\n",
142 | " for epoch in range(epochs):\n",
143 | " with tqdm(total=len(data_loader)) as pbar:\n",
144 | " for _, (features, preferences) in enumerate(data_loader):\n",
145 | " users = features[:, 0].to(self.device)\n",
146 | " items = features[:, 1].to(self.device)\n",
147 | " rtngs = features[:, 2].to(self.device)\n",
148 | " prefs = preferences.to(self.device)\n",
149 | " \n",
150 | " preds = self.model(users, items)\n",
151 | " confs = self.conf_func(rtngs)\n",
152 | " \n",
153 | " if hasattr(self.objective, 'weight'):\n",
154 | " self.objective.weight = confs\n",
155 | " \n",
156 | " loss = self.objective(preds, prefs).mean()\n",
157 | " loss.backward()\n",
158 | " \n",
159 | " self.optimizer.step()\n",
160 | " self.optimizer.zero_grad()\n",
161 | " \n",
162 | " pbar.update(1)\n",
163 | "\n",
164 | " def step(self, user: torch.tensor, item: torch.tensor, \n",
165 | " rating: torch.tensor = None, preference: torch.tensor = None):\n",
166 | " \"\"\"Trains the model incrementally.\"\"\"\n",
167 | " self.model.train()\n",
168 | " \n",
169 | " user = user.to(self.device)\n",
170 | " item = item.to(self.device)\n",
171 | " rtng = rating.to(self.device)\n",
172 | " pref = preference.to(self.device)\n",
173 | " \n",
174 | " pred = self.model(user, item)\n",
175 | " conf = self.conf_func(rtng)\n",
176 | " \n",
177 | " if hasattr(self.objective, 'weight'):\n",
178 | " self.objective.weight = conf\n",
179 | " \n",
180 | " loss = self.objective(pred, pref)\n",
181 | " loss.backward()\n",
182 | " \n",
183 | " self.optimizer.step()\n",
184 | " self.optimizer.zero_grad()\n",
185 | "\n",
186 | " def predict(self, user: torch.tensor, k:int = 10) -> torch.tensor:\n",
187 | " \"\"\"Recommends the top-k items to a specific user.\"\"\"\n",
188 | " self.model.eval()\n",
189 | " user = user.to(self.device)\n",
190 | " user_embedding = self.user_embeddings(user)\n",
191 | " item_embeddings = self.item_embeddings.weight\n",
192 | " score = item_embeddings @ user_embedding.transpose(0, 1)\n",
193 | " predictions = score.squeeze().argsort()[-k:]\n",
194 | " return predictions.cpu()\n",
195 | "\n",
196 | " def save(self, path: str):\n",
197 | " \"\"\"Saves the model parameters to the given path.\"\"\"\n",
198 | " torch.save(self.model.state_dict(), path)\n",
199 | "\n",
200 | " def load(self, path: str):\n",
201 | " \"\"\"Loads the model parameters from a given path.\"\"\"\n",
202 | " self.model.load_state_dict(torch.load(path))"
203 | ]
204 | },
205 | {
206 | "cell_type": "markdown",
207 | "metadata": {},
208 | "source": [
209 | "Arguments:\n",
210 | "\n",
211 | "* model (torch.nn.Module): The neural network architecture\n",
212 | "* objective (Callable): The objective function\n",
213 | "* optimizer (Callable): The method used to optimize the objective function. Usually a `torch.optim` loss function\n",
214 | "* conf_func (Callable): A method that converts implicit ratings to confidence scores\n",
215 | "* device (str): Either `cpu` or `gpu`"
216 | ]
217 | },
218 | {
219 | "cell_type": "code",
220 | "execution_count": null,
221 | "metadata": {},
222 | "outputs": [
223 | {
224 | "data": {
225 | "text/markdown": [
226 | "