├── .gitignore ├── LICENSE ├── README.md ├── datasets ├── dataset.lua └── utils.lua ├── models └── amar.lua ├── run_amar_experiments.lua ├── train_amar_rnn.lua └── utils └── progress.lua /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Lua sources 2 | luac.out 3 | 4 | # luarocks build files 5 | *.src.rock 6 | *.zip 7 | *.tar.gz 8 | 9 | # Object files 10 | *.o 11 | *.os 12 | *.ko 13 | *.obj 14 | *.elf 15 | 16 | # Precompiled Headers 17 | *.gch 18 | *.pch 19 | 20 | # Libraries 21 | *.lib 22 | *.a 23 | *.la 24 | *.lo 25 | *.def 26 | *.exp 27 | 28 | # Shared objects (inc. Windows DLLs) 29 | *.dll 30 | *.so 31 | *.so.* 32 | *.dylib 33 | 34 | # Executables 35 | *.exe 36 | *.out 37 | *.app 38 | *.i*86 39 | *.x86_64 40 | *.hex 41 | 42 | -------------------------------------------------------------------------------- /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 | # AMAR: Ask Me Any Rating 2 | 3 | Code for the paper "Ask Me Any Rating: A Content-based Recommender System based on Recurrent Neural Networks". 4 | 5 | ## Description 6 | In this work we propose *Ask Me Any Rating (AMAR)*, a novel content-based recommender system based on deep neural networks which is able to produce top-N recommendations leveraging user and item embeddings which are learnt from textual information describing the items. 7 | 8 | A comprehensive experimental evaluation conducted on state of-the-art datasets such as *MovieLens 1M* and *DBbook* showed a significant improvement over all the baselines taken into account. 9 | 10 | ## Requirements 11 | 12 | - Lua 13 | - Torch 14 | - nn 15 | - rnn 16 | - cudnn 17 | - cunn 18 | - cutorch 19 | - optim 20 | - pl 21 | - cjson 22 | - lfs 23 | 24 | ## Usage 25 | 26 | 1. Retrieve item descriptions and save them in ".txt" files. Each file should be named as the item identifier in the used dataset (e.g., item 1 has a description file named 1.txt) 27 | 2. Create JSON configuration file for the training file that you want to use and start the training using *Torch* specifying the configuration filename with the `-config` parameter 28 | 3. Evaluate the trained model using the `run_amar_experiments.lua` program specifying the configuration filename with the `-config` parameter 29 | 30 | ## Configuration files 31 | Training and evaluation configuration files are in JSON format and are composed by specific fields. They are used in order to modify model parameters and to specify the supplementary files used to train the models or to evaluate the models. 32 | 33 | For instance, the training configuration file for the `train_amar_rnn.lua` file is composed by the following fields: 34 | - items: path of item descriptions 35 | - genres: filename of item genres (optional) 36 | - models_mapping: dictionary which associates training sets to models 37 | - rnn_unit: RNN unit identifier used in rnn package 38 | - optim_method: optimization method identifier used in optim package 39 | - training_params: parameters of the optimization method 40 | - batch_size: number of training examples in a batch 41 | - num_epochs: number of training epochs 42 | - save_after: save model each save_after epochs 43 | 44 | We report in the following code snippet a real configuration script that we used for our model: 45 | ```json 46 | { 47 | "items": "../datasets/ml1m/content/simple", 48 | "models_mapping": { 49 | "../datasets/ml1m/ratings/u1.base": "../resources/ml1m/amar/rnn/base/u1.model", 50 | "../datasets/ml1m/ratings/u2.base": "../resources/ml1m/amar/rnn/base/u2.model", 51 | "../datasets/ml1m/ratings/u3.base": "../resources/ml1m/amar/rnn/base/u3.model", 52 | "../datasets/ml1m/ratings/u4.base": "../resources/ml1m/amar/rnn/base/u4.model", 53 | "../datasets/ml1m/ratings/u5.base": "../resources/ml1m/amar/rnn/base/u5.model" 54 | }, 55 | "optim_method": "rmsprop", 56 | "training_params": { 57 | "learningRate": 1e-3, 58 | "alpha": 0.9 59 | }, 60 | "batch_size": 32, 61 | "num_epochs": 20, 62 | "save_after": 5 63 | } 64 | ``` 65 | 66 | In addition, the evaluation configuration file for the `run_amar_experiments.lua` file is in JSON format and is composed by the following fields: 67 | - items: path of items descriptions 68 | - genres: filename of items genres 69 | - models_mapping: dictionary which associates test files to models 70 | - predictions: generated predictions filename 71 | - batch_size: number of examples in a batch 72 | - topn: list of cutoff values 73 | 74 | We report in the following code snippet a real configuration script that we used for our model: 75 | ```json 76 | { 77 | "items": "../datasets/ml1m/content/simple", 78 | "models_mapping": { 79 | "../datasets/ml1m/ratings/u1.test": "../resources/ml1m/amar/rnn/base/u1.model", 80 | "../datasets/ml1m/ratings/u2.test": "../resources/ml1m/amar/rnn/base/u2.model", 81 | "../datasets/ml1m/ratings/u3.test": "../resources/ml1m/amar/rnn/base/u3.model", 82 | "../datasets/ml1m/ratings/u4.test": "../resources/ml1m/amar/rnn/base/u4.model", 83 | "../datasets/ml1m/ratings/u5.test": "../resources/ml1m/amar/rnn/base/u5.model" 84 | }, 85 | "predictions": "../experiments/results/ml1m/amar/rnn/base/predictions_%d_%d.txt", 86 | "batch_size": 32, 87 |  "topn": [10] 88 | } 89 | ``` 90 | ## Authors 91 | 92 | All the following authors have equally contributed to this project (listed in alphabetical order by surname): 93 | 94 | - Claudio Greco ([github](https://github.com/claudiogreco)) 95 | - Alessandro Suglia ([github](https://github.com/aleSuglia)) 96 | -------------------------------------------------------------------------------- /datasets/dataset.lua: -------------------------------------------------------------------------------- 1 | require "lfs"; 2 | tds = require "tds"; 3 | stringx = require "pl.stringx"; 4 | file = require "pl.file"; 5 | cjson = require "cjson"; 6 | 7 | --[[ 8 | Reads the text descriptions associated to each item from a given path. 9 | 10 | Parameters: 11 | - train_path: folder in which item descriptions are stored 12 | - extension: extension associated to each file contained in the folder 13 | Output: 14 | dictionary structure which contains the following data: 15 | items: item descriptions 16 | item2pos: dictionary which maps item ids to position in the dataset 17 | pos2item: dictionary which maps position in the dataset to item ids 18 | token2id: dictionary which maps tokens to word identifiers 19 | max_item_len: maximum number of words in a text description 20 | ]] 21 | function read_items_data(train_path, extension) 22 | local items = tds.Hash() 23 | local item2pos = tds.Hash() 24 | local pos2item = tds.Hash() 25 | local token2id = tds.Hash() 26 | local num_items = 1 27 | local num_tokens = 1 28 | local max_item_len = 0 29 | extension = extension or ".tokens" 30 | 31 | for file in lfs.dir(train_path) do 32 | if file ~= "." and file ~= ".." then 33 | local attr = lfs.attributes(train_path .. "/" .. file) 34 | 35 | if attr.mode == "file" then 36 | local item_id = string.sub(file, 0, string.find(file, extension .. "[^." .. extension .. "]*$") - 1) 37 | local item_words = tds.Vec() 38 | item2pos[item_id] = num_items 39 | pos2item[num_items] = item_id 40 | 41 | for line in io.lines(train_path .. "/" .. file) do 42 | for word in string.gmatch(line, "%S+") do 43 | if token2id[word] == nil then 44 | token2id[word] = num_tokens 45 | num_tokens = num_tokens + 1 46 | end 47 | 48 | item_words:insert(token2id[word]) 49 | end 50 | end 51 | 52 | if #item_words > max_item_len then 53 | max_item_len = #item_words 54 | end 55 | 56 | items[item_id] = item_words 57 | num_items = num_items + 1 58 | end 59 | end 60 | end 61 | 62 | return { 63 | items = items, 64 | item2pos = item2pos, 65 | pos2item = pos2item, 66 | token2id = token2id, 67 | max_item_len = max_item_len 68 | } 69 | end 70 | 71 | --[[ 72 | Loads genres metadata associated to each item. 73 | 74 | Parameters: 75 | - genres_filename: name of the file containing genres information for each item in JSON format 76 | - item2pos: maps item ids to item position in the dataset 77 | ]] 78 | function load_items_genres(genres_filename, item2pos) 79 | --[[ 80 | Genres mapping example: 81 | genre2id = {"Science fiction"=1, "Horror"=2, "Thriller"=3, "Comedy"=4, "Action"=5} 82 | 83 | Padded genres: 84 | 1 3 0 85 | 5 0 0 86 | 1 2 3 87 | 88 | Model input: {item, user, genres} -> torch.Tensor elements in the table 89 | --]] 90 | 91 | local data = cjson.decode(file.read(genres_filename)) 92 | local genre2id = tds.Hash() 93 | local id2genre = tds.Hash() 94 | local genres = tds.Hash() 95 | local num_genres = 1 96 | local max_num_genres = 0 97 | 98 | for item_id, item_genres in pairs(data) do 99 | -- item exists in mapping 100 | if item2pos[item_id] then 101 | local item = tonumber(item2pos[item_id]) 102 | local item_mapped_genres = tds.Vec() 103 | 104 | if #item_genres > max_num_genres then 105 | max_num_genres = #item_genres 106 | end 107 | 108 | for _, item_genre in pairs(item_genres) do 109 | if not genre2id[item_genre] then 110 | genre2id[item_genre] = num_genres 111 | id2genre[num_genres] = item_genre 112 | num_genres = num_genres + 1 113 | end 114 | 115 | item_mapped_genres:insert(genre2id[item_genre]) 116 | end 117 | 118 | genres[item] = item_mapped_genres 119 | end 120 | end 121 | 122 | return { 123 | genres = genres, 124 | genre2id = genre2id, 125 | id2genre = id2genre, 126 | max_num_genres = max_num_genres 127 | } 128 | end 129 | 130 | --[[ 131 | Loads ratings from the specified file in a CSV format with a given delimiter. 132 | 133 | Parameters: 134 | - ratings_filename: filename of the ratings data in the format (user_id, item_id, rating) 135 | - item2pos: maps item ids to item positions 136 | - delimiter: delimiter used by the specified rating file 137 | ]] 138 | function read_ratings_data(ratings_filename, item2pos, delimiter) 139 | local delimiter = delimiter or "," 140 | local data = file.read(ratings_filename) 141 | local file_lines = stringx.splitlines(data) 142 | local ratings = torch.Tensor(#file_lines, 3) 143 | local user2id = tds.Hash() 144 | local id2user = tds.Hash() 145 | local num_users = 1 146 | 147 | for i = 1, #file_lines do 148 | local splitted_line = stringx.split(file_lines[i], delimiter) 149 | local raw_user = tonumber(splitted_line[1]) 150 | 151 | if user2id[raw_user] == nil then 152 | user2id[raw_user] = num_users 153 | id2user[num_users] = raw_user 154 | num_users = num_users + 1 155 | end 156 | 157 | local user = user2id[raw_user] 158 | local item = tonumber(item2pos[splitted_line[2]]) 159 | local rating = tonumber(splitted_line[3]) 160 | 161 | ratings[i][1] = user 162 | ratings[i][2] = item 163 | ratings[i][3] = rating 164 | end 165 | 166 | return { 167 | ratings = ratings, 168 | user2id = user2id, 169 | id2user = id2user 170 | } 171 | end 172 | 173 | --[[ 174 | Pads item description according to the maximum number of tokens in the item descriptions. 175 | ]] 176 | function pad_items_data(items_data) 177 | local data = torch.Tensor(#items_data["items"], items_data["max_item_len"]):zero() 178 | 179 | for item_id, tokens in pairs(items_data["items"]) do 180 | for i, token in pairs(tokens) do 181 | data[items_data["item2pos"][item_id]][i] = token 182 | end 183 | end 184 | 185 | return data 186 | end 187 | 188 | --[[ 189 | Pads item genres according to the maximum number of genres associated to each item 190 | ]] 191 | function pad_genres_data(genres_data) 192 | local data = torch.Tensor(#genres_data["genres"], genres_data["max_num_genres"]):zero() 193 | 194 | for item_pos, genres in pairs(genres_data["genres"]) do 195 | for i, genre in pairs(genres) do 196 | data[item_pos][i] = genre 197 | end 198 | end 199 | 200 | return data 201 | end 202 | -------------------------------------------------------------------------------- /datasets/utils.lua: -------------------------------------------------------------------------------- 1 | local tds = require "tds"; 2 | 3 | --[[ 4 | Adds padding values to the input sequences according to the max_sequence_len parameter. 5 | 6 | Parameters: 7 | - sequences: list of tensors to be padded 8 | - max_sequence_len: maximum number of element that each sequence should have 9 | ]] 10 | function pad_sequences(sequences, max_sequence_len) 11 | local data = torch.Tensor(#sequences, max_sequence_len):zero() 12 | 13 | for i = 1, #sequences do 14 | if sequences[i]:dim() == 1 then 15 | for j = 1, sequences[i]:size(1) do 16 | data[i][j] = sequences[i][j] 17 | end 18 | end 19 | end 20 | 21 | return data 22 | end 23 | 24 | --[[ 25 | Loads the dense continuous representation from a specific embeddings filename which 26 | represents embeddings in a specific type, such as GloVe or Word2Vec. 27 | 28 | Parameters: 29 | - embeddings_filename: filename of the embeddings 30 | - embedding_type: embedding type identifier: {"word2vec", "glove"} 31 | ]] 32 | function load_embeddings(embeddings_filename, embeddings_type) 33 | function load_word2vec_embeddings(embeddings_filename) 34 | file = torch.DiskFile(embeddings_filename, "r") 35 | local max_w = 50 36 | 37 | function readStringv2(file) 38 | local str = {} 39 | 40 | for i = 1, max_w do 41 | local char = file:readChar() 42 | 43 | if char == 32 or char == 10 or char == 0 then 44 | break 45 | else 46 | str[#str + 1] = char 47 | end 48 | end 49 | 50 | str = torch.CharStorage(str) 51 | return str:string() 52 | end 53 | 54 | -- reading header 55 | file:ascii() 56 | num_words = file:readInt() 57 | embedding_size = file:readInt() 58 | local embeddings = tds.Hash() 59 | 60 | -- reading content 61 | file:binary() 62 | for i = 1, num_words do 63 | local word = readStringv2(file) 64 | local word_embedding = file:readFloat(embedding_size) 65 | word_embedding = torch.FloatTensor(word_embedding) 66 | 67 | local norm = torch.norm(word_embedding, 2) 68 | 69 | -- normalize word embedding 70 | if norm ~= 0 then 71 | word_embedding:div(norm) 72 | end 73 | 74 | embeddings[word] = word_embedding 75 | end 76 | 77 | return { 78 | embeddings = embeddings, 79 | embedding_size = embedding_size 80 | } 81 | end 82 | 83 | function load_glove_embeddings(embeddings_filename) 84 | local embeddings = tds.Hash() 85 | local delimiter = " " 86 | local data = file.read(embeddings_filename) 87 | local file_lines = stringx.splitlines(data) 88 | local embedding_size = #stringx.split(file_lines[1], delimiter) - 1 89 | 90 | for i = 1, #file_lines do 91 | local splitted_line = stringx.split(file_lines[i], delimiter) 92 | local word = splitted_line[1] 93 | local word_embedding = torch.Tensor(embedding_size) 94 | 95 | for j = 2, #splitted_line do 96 | word_embedding[j - 1] = tonumber(splitted_line[j]) 97 | end 98 | 99 | local norm = torch.norm(word_embedding, 2) 100 | 101 | -- normalize word embedding 102 | if norm ~= 0 then 103 | word_embedding:div(norm) 104 | end 105 | 106 | embeddings[word] = word_embedding 107 | end 108 | 109 | return { 110 | embeddings = embeddings, 111 | embedding_size = embedding_size 112 | } 113 | end 114 | 115 | if embeddings_type == "word2vec" then 116 | return load_word2vec_embeddings(embeddings_filename) 117 | elseif embeddings_type == "glove" then 118 | return load_glove_embeddings(embeddings_filename) 119 | else 120 | error("Invalid embedding type!") 121 | end 122 | end 123 | -------------------------------------------------------------------------------- /models/amar.lua: -------------------------------------------------------------------------------- 1 | require "rnn"; 2 | require "cunn"; 3 | require "cudnn"; 4 | 5 | function build_model_amar_mean(items_data, ratings_data, genres_data, batch_size) 6 | local item_embeddings_size = 10 7 | local user_embeddings_size = 10 8 | local genre_embeddings_size = 10 9 | local hidden_dense_layer_size = item_embeddings_size + user_embeddings_size 10 | local num_tokens = #items_data["token2id"] 11 | local num_users = #ratings_data["user2id"] 12 | local lookup_table = nn.LookupTableMaskZero(num_tokens + 1, item_embeddings_size) 13 | 14 | local items_model = nn.Sequential() 15 | :add(lookup_table) 16 | :add(nn.Mean(2)) 17 | 18 | local users_model = nn.Sequential() 19 | :add(nn.LookupTable(num_users, user_embeddings_size)) 20 | 21 | local full_model = nn.Sequential() -- {item, user} 22 | 23 | local parallel_table = nn.ParallelTable() 24 | :add(items_model) 25 | :add(users_model) 26 | 27 | if genres_data then 28 | print("-- Initializing model for genre features") 29 | hidden_dense_layer_size = hidden_dense_layer_size + genre_embeddings_size 30 | local genres_model = nn.Sequential() 31 | :add(nn.LookupTableMaskZero(#genres_data["genre2id"] + 1, genre_embeddings_size)) 32 | :add(nn.Mean(2)) 33 | 34 | parallel_table:add(genres_model) 35 | end 36 | 37 | full_model:add(parallel_table) 38 | :add(nn.JoinTable(2)) 39 | :add(nn.Linear(hidden_dense_layer_size, 1)) 40 | :add(cudnn.Sigmoid()) 41 | 42 | return full_model 43 | end 44 | 45 | function build_model_amar_rnn(items_data, ratings_data, genres_data, batch_size, rnn_unit_id) 46 | local item_embeddings_size = 10 47 | local user_embeddings_size = 10 48 | local genre_embeddings_size = 10 49 | local hidden_dense_layer_size = item_embeddings_size + user_embeddings_size 50 | local num_tokens = #items_data["token2id"] 51 | local num_users = #ratings_data["user2id"] 52 | local lookup_table = nn.LookupTableMaskZero(num_tokens + 1, item_embeddings_size) 53 | 54 | if rnn_unit_id == "LSTM" then 55 | rnn_unit = nn.LSTM(item_embeddings_size, item_embeddings_size) 56 | elseif rnn_unit_id == "FastLSTM" then 57 | rnn_unit = nn.FastLSTM(item_embeddings_size, item_embeddings_size) 58 | elseif rnn_unit_id == "GRU" then 59 | rnn_unit = nn.GRU(item_embeddings_size, item_embeddings_size) 60 | else 61 | error("Invalid RNN unit identifier!") 62 | end 63 | 64 | local items_model = nn.Sequential() 65 | :add(lookup_table) 66 | :add(nn.SplitTable(2)) 67 | :add(nn.Sequencer(rnn_unit)) 68 | -- average over rows of tensors in the table 69 | :add(nn.JoinTable(1)) 70 | :add(nn.View(1, batch_size, item_embeddings_size)) 71 | :add(nn.Mean(1)) 72 | :add(nn.View(batch_size, item_embeddings_size)) 73 | 74 | local users_model = nn.Sequential() 75 | :add(nn.LookupTable(num_users, user_embeddings_size)) 76 | 77 | local full_model = nn.Sequential() -- {item, user} 78 | 79 | local parallel_table = nn.ParallelTable() 80 | :add(items_model) 81 | :add(users_model) 82 | 83 | if genres_data then 84 | print("-- Initializing model for genre features") 85 | hidden_dense_layer_size = hidden_dense_layer_size + genre_embeddings_size 86 | local genres_model = nn.Sequential() 87 | :add(nn.LookupTableMaskZero(#genres_data["genre2id"] + 1, genre_embeddings_size)) 88 | :add(nn.Mean(2)) 89 | 90 | parallel_table:add(genres_model) 91 | end 92 | 93 | full_model:add(parallel_table) 94 | :add(nn.JoinTable(2)) 95 | :add(nn.Linear(hidden_dense_layer_size, 1)) 96 | :add(cudnn.Sigmoid()) 97 | 98 | return full_model 99 | end 100 | 101 | function build_model_amar_rnn_fast(items_data, ratings_data, genres_data, batch_size) 102 | local item_embeddings_size = 10 103 | local user_embeddings_size = 10 104 | local genre_embeddings_size = 10 105 | local hidden_dense_layer_size = item_embeddings_size + user_embeddings_size 106 | local num_tokens = #items_data["token2id"] 107 | local num_users = #ratings_data["user2id"] 108 | local lookup_table = nn.LookupTableMaskZero(num_tokens, item_embeddings_size) 109 | 110 | local items_model = nn.Sequential() 111 | :add(lookup_table) 112 | :add(nn.SeqLSTM(item_embeddings_size, item_embeddings_size)) 113 | :add(nn.Mean(2)) 114 | 115 | local users_model = nn.Sequential() 116 | :add(nn.LookupTable(num_users, user_embeddings_size)) 117 | 118 | local full_model = nn.Sequential() -- {item, user} 119 | 120 | local parallel_table = nn.ParallelTable() 121 | :add(items_model) 122 | :add(users_model) 123 | 124 | if genres_data then 125 | print("-- Initializing model for genre features") 126 | hidden_dense_layer_size = hidden_dense_layer_size + genre_embeddings_size 127 | local genres_model = nn.Sequential() 128 | :add(nn.LookupTableMaskZero(#genres_data["genre2id"] + 1, genre_embeddings_size)) 129 | :add(nn.Mean(2)) 130 | 131 | parallel_table:add(genres_model) 132 | end 133 | 134 | full_model:add(parallel_table) 135 | :add(nn.JoinTable(2)) 136 | :add(nn.Linear(hidden_dense_layer_size, 1)) 137 | :add(cudnn.Sigmoid()) 138 | 139 | return full_model 140 | end 141 | 142 | function build_model_amar_cnn(items_data, ratings_data, genres_data, batch_size, max_item_len, num_filters, filter_size) 143 | local item_embeddings_size = 10 144 | local user_embeddings_size = 10 145 | local genre_embeddings_size = 10 146 | local hidden_dense_layer_size = num_filters + user_embeddings_size 147 | local num_tokens = #items_data["token2id"] 148 | local num_users = #ratings_data["user2id"] 149 | local lookup_table = nn.LookupTableMaskZero(num_tokens + 1, item_embeddings_size) 150 | 151 | local items_model = nn.Sequential() 152 | :add(lookup_table) 153 | :add(nn.Padding(1, -(num_filters-1), 2, 0)) 154 | :add(nn.Padding(1, (num_filters-1), 2, 0)) 155 | :add(cudnn.TemporalConvolution(item_embeddings_size, num_filters, filter_size)) 156 | :add(cudnn.ReLU()) 157 | :add(nn.TemporalMaxPooling(max_item_len+2*(num_filters-1)-filter_size+1)) 158 | :add(nn.Squeeze(2)) 159 | --:add(nn.Dropout(0.5)) () 160 | 161 | local users_model = nn.Sequential() 162 | :add(nn.LookupTable(num_users, user_embeddings_size)) 163 | 164 | local full_model = nn.Sequential() -- {item, user} 165 | 166 | local parallel_table = nn.ParallelTable() 167 | :add(items_model) 168 | :add(users_model) 169 | 170 | if genres_data then 171 | print("-- Initializing model for genre features") 172 | hidden_dense_layer_size = hidden_dense_layer_size + genre_embeddings_size 173 | local genres_model = nn.Sequential() 174 | :add(nn.LookupTableMaskZero(#genres_data["genre2id"] + 1, genre_embeddings_size)) 175 | :add(nn.Mean(2)) 176 | 177 | parallel_table:add(genres_model) 178 | end 179 | 180 | full_model:add(parallel_table) 181 | :add(nn.JoinTable(2)) 182 | :add(nn.Linear(hidden_dense_layer_size, 1)) 183 | :add(cudnn.Sigmoid()) 184 | 185 | return full_model 186 | end 187 | 188 | -------------------------------------------------------------------------------- /run_amar_experiments.lua: -------------------------------------------------------------------------------- 1 | require "datasets/dataset.lua"; 2 | require "xlua"; 3 | require "cutorch"; 4 | require "cunn"; 5 | require "cudnn"; 6 | require "rnn"; 7 | data = require "pl.data"; 8 | cjson = require "cjson"; 9 | stringx = require "pl.stringx"; 10 | require "string"; 11 | require "lfs"; 12 | 13 | title = "### AMAR (Ask Me Any Rating) evaluator ###" 14 | 15 | print(title) 16 | 17 | --[[ 18 | We expect to find in the JSON file the following parameters: 19 | - items: path of items descriptions 20 | - genres: filename of items genres 21 | - models_mapping: dictionary which associates test files to models 22 | - predictions: generated predictions filename 23 | - batch_size: number of examples in a batch 24 | - topn: list of cutoff values 25 | --]] 26 | 27 | cmd = torch.CmdLine() 28 | cmd:text() 29 | cmd:text(title) 30 | cmd:text() 31 | cmd:text("Options:") 32 | cmd:option("-config", "", "Filename of JSON training parameters") 33 | cmd:text() 34 | 35 | params = cmd:parse(arg) 36 | 37 | local conf_data = cjson.decode(file.read(params.config)) 38 | 39 | print("-- Loading items data: "..conf_data["items"]) 40 | items_data = read_items_data(conf_data["items"]) 41 | 42 | print("-- Padding items data") 43 | items_data["items"] = pad_items_data(items_data) 44 | 45 | test_filenames = conf_data["tests"] 46 | model_filenames = conf_data["models"] 47 | batch_size = conf_data["batch_size"] 48 | 49 | if conf_data["genres"] then 50 | print("-- Loading genres data: ".. conf_data["genres"]) 51 | genres_data = load_items_genres(conf_data["genres"], items_data["item2pos"]) 52 | 53 | print("-- Padding genres data") 54 | genres_data["genres"] = pad_genres_data(genres_data) 55 | end 56 | 57 | for num_folds=1, #test_filenames do 58 | test_filename = test_filenames[num_folds] 59 | model_filename = model_filenames[num_folds] 60 | 61 | print("-- Loading test data: "..test_filename) 62 | local test_data = read_ratings_data(test_filename, items_data["item2pos"], "\t") 63 | 64 | print("-- Loading model: "..model_filename) 65 | model = torch.load(model_filename) 66 | 67 | local indices = torch.range(1, test_data["ratings"]:size(1)):long():split(batch_size) 68 | local predictions = {} 69 | 70 | for t, v in ipairs(indices) do 71 | xlua.progress(t, #indices) 72 | 73 | curr_users_batch = test_data["ratings"]:index(1, v)[{ {}, { 1 } }]:cuda() 74 | curr_items_ids_batch = test_data["ratings"]:index(1, v)[{ {}, { 2 } }]:long() 75 | local curr_items_ids_batch = torch.reshape(curr_items_ids_batch, v:size(1)) 76 | curr_items_batch = items_data["items"]:index(1, curr_items_ids_batch):cuda() 77 | 78 | if t == #indices then 79 | last_batch_size = v:size(1) 80 | curr_users_batch = torch.cat(curr_users_batch, torch.zeros(batch_size-v:size(1), 1):cuda(), 1) 81 | curr_items_batch = torch.cat(curr_items_batch, torch.zeros(batch_size-v:size(1), items_data["max_item_len"]):cuda(), 1) 82 | end 83 | 84 | local curr_users_batch = torch.reshape(curr_users_batch, batch_size) 85 | 86 | -- model inputs 87 | local inputs = {curr_items_batch, curr_users_batch} 88 | 89 | 90 | if conf_data["genres"] then 91 | -- genres ids 92 | local curr_genres_batch = genres_data["genres"]:index(1, curr_items_ids_batch):cuda() 93 | table.insert(inputs, curr_genres_batch) 94 | end 95 | 96 | local targets = model:forward(inputs) 97 | 98 | if last_batch_size ~= nil then 99 | -- remove useless predictions used for batch padding 100 | targets = targets[{{1, last_batch_size}, {}}] 101 | end 102 | 103 | for index = 1, targets:size(1) do 104 | local real_user_id = test_data["id2user"][curr_users_batch[index]] 105 | if predictions[real_user_id] == nil then 106 | predictions[real_user_id] = {} 107 | end 108 | table.insert(predictions[real_user_id], { 109 | items_data["pos2item"][curr_items_ids_batch[index]], 110 | targets[index][1] 111 | }) 112 | end 113 | 114 | end 115 | 116 | local function cmp_ratings(r1, r2) 117 | return r1[2] > r2[2] 118 | end 119 | 120 | for _, topn in pairs(conf_data["topn"]) do 121 | print("Evaluating predictions for topn: "..topn) 122 | local results = {} 123 | 124 | for user, user_predictions in pairs(predictions) do 125 | 126 | table.sort(user_predictions, cmp_ratings) 127 | local n = 1 128 | for _, pair in pairs(user_predictions) do 129 | local item = pair[1] 130 | local rating = pair[2] 131 | table.insert(results, { user, item, rating }) 132 | if n >= topn then 133 | break 134 | end 135 | n = n + 1 136 | end 137 | end 138 | predictions_filename = string.format(conf_data["predictions"], topn, num_folds) 139 | 140 | print("Writing predictions: "..predictions_filename) 141 | data.write(results, predictions_filename) 142 | end 143 | 144 | model = nil 145 | collectgarbage() 146 | end 147 | -------------------------------------------------------------------------------- /train_amar_rnn.lua: -------------------------------------------------------------------------------- 1 | require "optim"; 2 | require "cutorch"; 3 | require "cunn"; 4 | require "cudnn"; 5 | file = require "pl.file"; 6 | cjson = require "cjson"; 7 | require "models/amar.lua" 8 | require "datasets/dataset.lua"; 9 | require "datasets/utils.lua"; 10 | require "utils/progress.lua"; 11 | 12 | torch.setdefaulttensortype("torch.FloatTensor") 13 | cutorch.setDevice(1) 14 | torch.manualSeed(12345) 15 | cutorch.manualSeed(12345) 16 | 17 | function round(num, idp) 18 | local mult = 10 ^ (idp or 0) 19 | return math.floor(num * mult + 0.5) / mult 20 | end 21 | 22 | local title = "### AMAR (Ask Me Any Rating) RNN trainer ###" 23 | 24 | print(title) 25 | 26 | --[[ 27 | JSON configuration file parameters: 28 | - items: path of item descriptions 29 | - genres: filename of item genres (optional) 30 | - models_mapping: dictionary which associates training sets to models 31 | - rnn_unit: RNN unit identifier used in rnn package 32 | - optim_method: optimization method identifier used in optim package 33 | - training_params: parameters of the optimization method 34 | - batch_size: number of training examples in a batch 35 | - num_epochs: number of training epochs 36 | - save_after: save model each save_after epochs 37 | --]] 38 | 39 | local cmd = torch.CmdLine() 40 | cmd:text() 41 | cmd:text(title) 42 | cmd:text() 43 | cmd:text("Options:") 44 | cmd:option("-config", "", "Filename of JSON training parameters") 45 | cmd:text() 46 | 47 | local params = cmd:parse(arg) 48 | 49 | local conf_data = cjson.decode(file.read(params.config)) 50 | 51 | print("-- Loading items data: "..conf_data["items"]) 52 | local items_data = read_items_data(conf_data["items"]) 53 | 54 | print("-- Padding items data") 55 | items_data["items"] = pad_items_data(items_data) 56 | 57 | local genres_data 58 | 59 | if conf_data["genres"] then 60 | print("-- Loading genres data: "..conf_data["genres"]) 61 | genres_data = load_items_genres(conf_data["genres"], items_data["item2pos"]) 62 | 63 | print("-- Padding genres data") 64 | genres_data["genres"] = pad_genres_data(genres_data) 65 | end 66 | 67 | local rnn_unit_id = conf_data["rnn_unit"] 68 | 69 | local optim_method_id = conf_data["optim_method"] 70 | local optim_method 71 | 72 | if optim_method_id == "sgd" then 73 | optim_method = optim.sgd 74 | elseif optim_method_id == "adadelta" then 75 | optim_method = optim.adadelta 76 | elseif optim_method_id == "adagrad" then 77 | optim_method = optim.adagrad 78 | elseif optim_method_id == "adam" then 79 | optim_method = optim.adam 80 | elseif optim_method_id == "rmsprop" then 81 | optim_method = optim.rmsprop 82 | else 83 | print("Invalid training method: "..optim_method_id) 84 | end 85 | 86 | local batch_size = conf_data["batch_size"] 87 | local num_epochs = conf_data["num_epochs"] 88 | 89 | local coeff_l2 = conf_data["training_params"]["coeff_l2"] 90 | 91 | if coeff_l2 then 92 | print("-- Using L2 regularization using coefficient "..coeff_l2) 93 | end 94 | 95 | for train_filename, model_filename in pairs(conf_data["models_mapping"]) do 96 | local training_params = {} 97 | 98 | for k, v in pairs(conf_data["training_params"]) do 99 | training_params[k] = v 100 | end 101 | 102 | print("-- Loading ratings data: "..train_filename) 103 | local ratings_data = read_ratings_data(train_filename, items_data["item2pos"], "\t") 104 | local num_examples = ratings_data["ratings"]:size(1) 105 | 106 | print("Dataset stats:") 107 | print("Number of items:\t"..items_data["items"]:size(1)) 108 | print("Vocabulary size:\t"..#items_data["token2id"]) 109 | print("Number of users:\t"..#ratings_data["user2id"]) 110 | print("Number of ratings:\t"..num_examples) 111 | 112 | print("-- Building model: "..model_filename) 113 | local model = build_model_amar_rnn_fast(items_data, ratings_data, genres_data, batch_size) 114 | model = cudnn.convert(model, cudnn) 115 | model = model:cuda() 116 | 117 | local criterion = nn.BCECriterion() 118 | criterion = criterion:cuda() 119 | 120 | -- get model parameters 121 | local params, grad_params = model:getParameters() 122 | 123 | local cost_per_epoch = {} 124 | 125 | print("-- Training model with "..rnn_unit_id.." unit using "..optim_method_id) 126 | for e = 1, num_epochs do 127 | -- shuffle and split training examples in batches 128 | local indices = torch.randperm(num_examples):long():split(batch_size) 129 | 130 | -- remove last element so that all the batches have equal size 131 | indices[#indices] = nil 132 | 133 | print("==> doing epoch on training data:") 134 | print("==> online epoch # "..e.." [batchSize = "..batch_size.."]") 135 | 136 | local average_cost = 0 137 | 138 | for t, v in ipairs(indices) do 139 | -- items positions 140 | local curr_items_ids_batch = torch.reshape(ratings_data["ratings"]:index(1, v)[{ {}, { 2 } }]:long(), batch_size) 141 | 142 | -- items descriptions 143 | local curr_items_batch = items_data["items"]:index(1, curr_items_ids_batch):cuda() 144 | 145 | -- users ids 146 | local curr_users_batch = torch.reshape(ratings_data["ratings"]:index(1, v)[{ {}, { 1 } }]:cuda(), batch_size) 147 | 148 | -- model inputs 149 | local inputs = { curr_items_batch, curr_users_batch } 150 | 151 | if conf_data["genres"] then 152 | -- genres ids 153 | local curr_genres_batch = genres_data["genres"]:index(1, curr_items_ids_batch):cuda() 154 | table.insert(inputs, curr_genres_batch) 155 | end 156 | 157 | -- model targets 158 | local targets = ratings_data["ratings"]:index(1, v)[{ {}, { 3 } }]:cuda() 159 | 160 | -- callback that does a single batch optimization step 161 | local batch_optimize = function(x) 162 | -- get new parameters 163 | if x ~= params then 164 | params:copy(x) 165 | end 166 | 167 | -- reset gradients 168 | grad_params:zero() 169 | 170 | -- backward propagation 171 | local outputs = model:forward(inputs) 172 | local f = criterion:forward(outputs, targets) 173 | local df_do = criterion:backward(outputs, targets) 174 | model:backward(inputs, df_do) 175 | 176 | if coeff_l2 then 177 | -- L2 regularization 178 | f = f + coeff_l2 * torch.norm(params, 2) ^ 2 / 2 179 | grad_params:add(params:mul(coeff_l2)) 180 | end 181 | 182 | -- return f and df/dX 183 | return f, grad_params 184 | end 185 | 186 | -- optimize on current mini-batch 187 | local _, fs = optim_method(batch_optimize, params, training_params) 188 | 189 | -- evaluate current loss function value 190 | local current_cost = fs[1] 191 | average_cost = average_cost + current_cost 192 | 193 | -- show custom progress bar 194 | progress(t, #indices, round(current_cost, 2)) 195 | end 196 | 197 | -- evaluate average cost per epoch 198 | average_cost = round(average_cost / #indices, 4) 199 | print("Average cost per epoch: "..average_cost) 200 | table.insert(cost_per_epoch, average_cost) 201 | 202 | if e >= 15 and e % conf_data["save_after"] == 0 then 203 | print("Saving current model...") 204 | torch.save(model_filename..".e"..e, model) 205 | end 206 | end 207 | 208 | -- save experiment data 209 | print("Saving experiment data...") 210 | local experiment_data = {} 211 | 212 | experiment_data["training_params"] = {} 213 | 214 | for k, v in pairs(conf_data["training_params"]) do 215 | if k ~= "tmp" and k ~= "m" then 216 | experiment_data["training_params"][k] = v 217 | end 218 | end 219 | 220 | experiment_data["optim_method"] = optim_method_id 221 | experiment_data["batch_size"] = batch_size 222 | experiment_data["num_epochs"] = num_epochs 223 | experiment_data["cost_per_epoch"] = cost_per_epoch 224 | file.write(model_filename..".params", cjson.encode(experiment_data)) 225 | end 226 | -------------------------------------------------------------------------------- /utils/progress.lua: -------------------------------------------------------------------------------- 1 | do 2 | local function getTermLength() 3 | if sys.uname() == 'windows' then return 80 end 4 | local tputf = io.popen('tput cols', 'r') 5 | local w = tonumber(tputf:read('*a')) 6 | local rc = {tputf:close()} 7 | if rc[3] == 0 then return w 8 | else return 80 end 9 | end 10 | 11 | local barDone = true 12 | local previous = -1 13 | local tm = '' 14 | local timer 15 | local times 16 | local indices 17 | local termLength = math.min(getTermLength(), 120) 18 | function progress(current, goal, cost) 19 | -- defaults: 20 | local barLength = termLength - 64 21 | local smoothing = 100 22 | local maxfps = 10 23 | 24 | -- Compute percentage 25 | local percent = math.floor(((current) * barLength) / goal) 26 | 27 | -- start new bar 28 | if (barDone and ((previous == -1) or (percent < previous))) then 29 | barDone = false 30 | previous = -1 31 | tm = '' 32 | timer = torch.Timer() 33 | times = {timer:time().real} 34 | indices = {current} 35 | else 36 | io.write('\r') 37 | end 38 | 39 | --if (percent ~= previous and not barDone) then 40 | if (not barDone) then 41 | previous = percent 42 | -- print bar 43 | io.write(' [') 44 | for i=1,barLength do 45 | if (i < percent) then io.write('=') 46 | elseif (i == percent) then io.write('>') 47 | else io.write('.') end 48 | end 49 | io.write('] ') 50 | for i=1,termLength-barLength-4 do io.write(' ') end 51 | for i=1,termLength-barLength-4 do io.write('\b') end 52 | -- time stats 53 | local elapsed = timer:time().real 54 | local step = (elapsed-times[1]) / (current-indices[1]) 55 | if current==indices[1] then step = 0 end 56 | local remaining = math.max(0,(goal - current)*step) 57 | table.insert(indices, current) 58 | table.insert(times, elapsed) 59 | if #indices > smoothing then 60 | indices = table.splice(indices) 61 | times = table.splice(times) 62 | end 63 | -- Print remaining time when running or total time when done. 64 | if (percent < barLength) then 65 | tm = ' ETA: ' .. formatTime(remaining) 66 | else 67 | tm = ' Tot: ' .. formatTime(elapsed) 68 | end 69 | tm = tm .. ' | Step: ' .. formatTime(step) 70 | io.write(tm) 71 | io.write(' | Cost: ' .. cost) 72 | -- go back to center of bar, and print progress 73 | for i=1,5+#tm+barLength/2 do io.write('\b') end 74 | io.write(' ', current, '/', goal, ' ') 75 | -- reset for next bar 76 | if (percent == barLength) then 77 | barDone = true 78 | io.write('\n') 79 | end 80 | -- flush 81 | io.write('\r') 82 | io.flush() 83 | end 84 | end 85 | end 86 | 87 | function formatTime(seconds) 88 | -- decompose: 89 | local floor = math.floor 90 | local days = floor(seconds / 3600/24) 91 | seconds = seconds - days*3600*24 92 | local hours = floor(seconds / 3600) 93 | seconds = seconds - hours*3600 94 | local minutes = floor(seconds / 60) 95 | seconds = seconds - minutes*60 96 | local secondsf = floor(seconds) 97 | seconds = seconds - secondsf 98 | local millis = floor(seconds*1000) 99 | 100 | -- string 101 | local f = '' 102 | local i = 1 103 | if days > 0 then f = f .. days .. 'D' i=i+1 end 104 | if hours > 0 and i <= 2 then f = f .. hours .. 'h' i=i+1 end 105 | if minutes > 0 and i <= 2 then f = f .. minutes .. 'm' i=i+1 end 106 | if secondsf > 0 and i <= 2 then f = f .. secondsf .. 's' i=i+1 end 107 | if millis > 0 and i <= 2 then f = f .. millis .. 'ms' i=i+1 end 108 | if f == '' then f = '0ms' end 109 | 110 | -- return formatted time 111 | return f 112 | end 113 | --------------------------------------------------------------------------------