├── .gitignore ├── C_code_TCTR ├── Makefile ├── corpus.cpp ├── corpus.h ├── ctr ├── ctr-condor ├── ctr.cpp ├── ctr.h ├── data.cpp ├── data.h ├── main.cpp ├── opt.cpp ├── opt.h ├── utils.cpp └── utils.h ├── LICENSE ├── README.md ├── __init__.py ├── lib ├── Probabilistic_Matrix_Factorization.py ├── Rocchio_CTR_JS_run.sh ├── Rocchio_CTR_LDA-profiles_run.sh ├── Rocchio_CTR_run.sh ├── Rocchio_LDA_run.sh ├── __init__.py ├── ce_temporal.py ├── lda_topics_gensim.py ├── lda_topics_sklearn.py ├── pub_rec.py ├── rocchio_based_recommender.py └── time-aware_rec.py ├── running ├── MF_time-aware_experiment.sh ├── TCTR_experiment.sh ├── TMF_experiment.sh ├── ctr_time-aware_experiment.sh ├── ctr_time-ignorant_experiment.sh ├── evaluation_run.sh ├── evaluation_temporal_run.sh └── generate_lda_topics.sh └── util ├── __init__.py ├── evaluation_metrics.py ├── files_utils.py ├── similarity_metrics.py └── utils.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 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | .idea/ 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # dotenv 83 | .env 84 | 85 | # virtualenv 86 | .venv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | .spyproject 93 | 94 | # Rope project settings 95 | .ropeproject 96 | 97 | # mkdocs documentation 98 | /site 99 | 100 | # mypy 101 | .mypy_cache/ 102 | -------------------------------------------------------------------------------- /C_code_TCTR/Makefile: -------------------------------------------------------------------------------- 1 | CC = g++ -Wall 2 | #CC = g++ -ansi -Wall -pedantic 3 | #CFLAGS = -g -Wall -O3 -ffast-math -DHAVE_INLINE -DGSL_RANGE_CHECK_OFF 4 | # CFLAGS = -g -Wall 5 | LDFLAGS = -lgsl -lm -lgslcblas 6 | export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/home/alzoghba/gsl/lib/ 7 | GSL_INCLUDE = /home/alzoghba/gsl/include 8 | GSL_LIB = /home/alzoghba/gsl/lib 9 | 10 | GSL_INCLUDE_MAC = /usr/local/include/ 11 | GSL_LIB_MAC = /usr/local/lib/ 12 | 13 | LSOURCE = main.cpp utils.cpp corpus.cpp ctr.cpp data.cpp opt.cpp 14 | LHEADER = utils.h corpus.h ctr.h data.h opt.h 15 | 16 | mac: $(LSOURCE) $(HEADER) 17 | $(CC) -I$(GSL_INCLUDE_MAC) -L$(GSL_LIB_MAC) $(LSOURCE) -o ctr $(LDFLAGS) 18 | 19 | mac-d: $(LSOURCE) $(HEADER) 20 | $(CC) -g -I$(GSL_INCLUDE_MAC) -L$(GSL_LIB_MAC) $(LSOURCE) -o ctr $@ $(LDFLAGS) 21 | 22 | linux: $(LSOURCE) $(HEADER) 23 | $(CC) -I$(GSL_INCLUDE) -L$(GSL_LIB) $(LSOURCE) -o ctr-condor $(LDFLAGS) 24 | 25 | linux-d: $(LSOURCE) $(HEADER) 26 | $(CC) -g -I$(GSL_INCLUDE) -L$(GSL_LIB_MAC) $(LSOURCE) -o ctr-condor $@ $(LDFLAGS) 27 | 28 | clean: 29 | -rm -f ctr 30 | clean-d: 31 | -rm -f ctr -------------------------------------------------------------------------------- /C_code_TCTR/corpus.cpp: -------------------------------------------------------------------------------- 1 | #include "corpus.h" 2 | #include 3 | #include 4 | 5 | c_corpus::c_corpus() { 6 | m_num_docs = 0; 7 | m_size_vocab = 0; 8 | m_num_total_words = 0; 9 | } 10 | 11 | c_corpus::~c_corpus() { 12 | for (int i = 0; i < m_num_docs; i ++) { 13 | c_document * doc = m_docs[i]; 14 | delete doc; 15 | } 16 | m_docs.clear(); 17 | 18 | m_num_docs = 0; 19 | m_size_vocab = 0; 20 | m_num_total_words = 0; 21 | } 22 | 23 | void c_corpus::read_data(const char * data_filename, int OFFSET) { 24 | 25 | int length = 0, count = 0, word = 0, n = 0, nd = 0, nw = 0; 26 | 27 | FILE * fileptr; 28 | fileptr = fopen(data_filename, "r"); 29 | nd = 0; 30 | nw = 0; 31 | 32 | printf("reading data from %s\n", data_filename); 33 | while ((fscanf(fileptr, "%10d", &length) != EOF)) { 34 | c_document * doc = new c_document(length); 35 | for (n = 0; n < length; n++) { 36 | fscanf(fileptr, "%10d:%10d", &word, &count); 37 | word = word - OFFSET; 38 | doc->m_words[n] = word; 39 | doc->m_counts[n] = count; 40 | doc->m_total += count; 41 | if (word >= nw) 42 | nw = word + 1; 43 | } 44 | m_num_total_words += doc->m_total; 45 | m_docs.push_back(doc); 46 | nd++; 47 | } 48 | fclose(fileptr); 49 | m_num_docs = nd; 50 | m_size_vocab = nw; 51 | printf("number of docs : %d\n", nd); 52 | printf("number of terms : %d\n", nw); 53 | printf("number of total words : %d\n", m_num_total_words); 54 | } 55 | 56 | int c_corpus::max_corpus_length() const { 57 | int max_length = 0; 58 | 59 | for (int d = 0; d < m_num_docs; d++) { 60 | if (m_docs[d]->m_length > max_length) 61 | max_length = m_docs[d]->m_length; 62 | } 63 | return max_length; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /C_code_TCTR/corpus.h: -------------------------------------------------------------------------------- 1 | // class for lda-c format 2 | // 3 | #ifndef CORPUS_H 4 | #define CORPUS_H 5 | 6 | #include 7 | #include 8 | 9 | using namespace std; 10 | 11 | class c_document { 12 | public: 13 | /* for document itself */ 14 | int * m_words; 15 | int * m_counts; 16 | int m_length; 17 | int m_total; 18 | 19 | public: 20 | c_document() { 21 | m_words = NULL; 22 | m_counts = NULL; 23 | m_length = 0; 24 | m_total = 0; 25 | } 26 | 27 | c_document(int len) { 28 | m_length = len; 29 | m_words = new int [len]; 30 | m_counts = new int [len]; 31 | m_total = 0; 32 | } 33 | 34 | ~c_document() { 35 | if (m_words != NULL) { 36 | delete [] m_words; 37 | delete [] m_counts; 38 | m_length = 0; 39 | m_total = 0; 40 | } 41 | } 42 | }; 43 | 44 | class c_corpus { 45 | public: 46 | c_corpus(); 47 | ~c_corpus(); 48 | void read_data(const char * data_filename, int OFFSET=0); 49 | int max_corpus_length() const; 50 | public: 51 | int m_num_docs; 52 | int m_size_vocab; 53 | int m_num_total_words; 54 | vector m_docs; 55 | }; 56 | 57 | #endif // CORPUS_H 58 | -------------------------------------------------------------------------------- /C_code_TCTR/ctr: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anasalzogbi/T-CTR/25a1d68cc99e4f922e9d155ca99ff9c53effcee8/C_code_TCTR/ctr -------------------------------------------------------------------------------- /C_code_TCTR/ctr-condor: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anasalzogbi/T-CTR/25a1d68cc99e4f922e9d155ca99ff9c53effcee8/C_code_TCTR/ctr-condor -------------------------------------------------------------------------------- /C_code_TCTR/ctr.cpp: -------------------------------------------------------------------------------- 1 | #include "ctr.h" 2 | #include "opt.h" 3 | 4 | extern gsl_rng * RANDOM_NUMBER; 5 | int min_iter = 15; 6 | double beta_smooth = 0.01; 7 | 8 | c_ctr::c_ctr() { 9 | m_beta = NULL; 10 | m_theta = NULL; 11 | m_U = NULL; 12 | m_V = NULL; 13 | 14 | m_num_factors = 0; // m_num_topics 15 | m_num_items = 0; // m_num_docs 16 | m_num_users = 0; // num of users 17 | } 18 | 19 | c_ctr::~c_ctr() { 20 | // free memory 21 | if (m_beta != NULL) gsl_matrix_free(m_beta); 22 | if (m_theta != NULL) gsl_matrix_free(m_theta); 23 | if (m_U != NULL) gsl_matrix_free(m_U); 24 | if (m_V != NULL) gsl_matrix_free(m_V); 25 | } 26 | 27 | void c_ctr::read_init_information(const char* theta_init_path, 28 | const char* beta_init_path, 29 | const c_corpus* c, 30 | double alpha_smooth) { 31 | int num_topics = m_num_factors; 32 | m_theta = gsl_matrix_alloc(c->m_num_docs, num_topics); 33 | printf("\nreading theta initialization from %s\n", theta_init_path); 34 | FILE * f = fopen(theta_init_path, "r"); 35 | mtx_fscanf(f, m_theta); 36 | fclose(f); 37 | 38 | //smoothing 39 | gsl_matrix_add_constant(m_theta, alpha_smooth); 40 | 41 | //normalize m_theta, in case it's not 42 | for (size_t j = 0; j < m_theta->size1; j ++) { 43 | gsl_vector_view theta_v = gsl_matrix_row(m_theta, j); 44 | vnormalize(&theta_v.vector); 45 | } 46 | 47 | m_beta = gsl_matrix_alloc(num_topics, c->m_size_vocab); 48 | printf("reading beta initialization from %s\n", beta_init_path); 49 | f = fopen(beta_init_path, "r"); 50 | mtx_fscanf(f, m_beta); 51 | fclose(f); 52 | 53 | // exponentiate if it's not 54 | if (mget(m_beta, 0, 0) < 0) { 55 | mtx_exp(m_beta); 56 | } 57 | else { 58 | gsl_matrix_add_constant(m_beta, beta_smooth); 59 | for (size_t j = 0; j < m_beta->size1; j ++) { 60 | gsl_vector_view beta_v = gsl_matrix_row(m_beta, j); 61 | vnormalize(&beta_v.vector); 62 | } 63 | } 64 | } 65 | 66 | void c_ctr::set_model_parameters(int num_factors, 67 | int num_users, 68 | int num_items) { 69 | m_num_factors = num_factors; 70 | m_num_users = num_users; 71 | m_num_items = num_items; 72 | } 73 | 74 | void c_ctr::init_model(int ctr_run) { 75 | 76 | m_U = gsl_matrix_calloc(m_num_users, m_num_factors); 77 | m_V = gsl_matrix_calloc(m_num_items, m_num_factors); 78 | 79 | if (ctr_run) { 80 | gsl_matrix_memcpy(m_V, m_theta); 81 | } 82 | else { 83 | // this is for convenience, so that updates are similar. 84 | m_theta = gsl_matrix_calloc(m_num_items, m_num_factors); 85 | 86 | for (size_t i = 0; i < m_V->size1; i ++) 87 | for (size_t j = 0; j < m_V->size2; j ++) 88 | mset(m_V, i, j, runiform()); 89 | } 90 | } 91 | 92 | 93 | void c_ctr::stochastic_learn_map_estimate(const c_data* users, const c_data* items, 94 | const c_double_data* users_a, const c_double_data* items_a, 95 | const c_corpus* c, const ctr_hyperparameter* param, 96 | const char* directory) { 97 | // init model parameters 98 | printf("\nrunning stochastic learning ...\n"); 99 | printf("initializing the model ...\n"); 100 | init_model(param->ctr_run); 101 | 102 | // filename 103 | char name[500]; 104 | 105 | // start time 106 | time_t start, current; 107 | time(&start); 108 | int elapsed = 0; 109 | 110 | int iter = 0; 111 | double likelihood = -exp(50), likelihood_old; 112 | double converge = 1.0; 113 | double learning_rate = param->learning_rate; 114 | 115 | /// create the state log file 116 | sprintf(name, "%s/state.log", directory); 117 | FILE* file = fopen(name, "w"); 118 | fprintf(file, "iter time likelihood converge\n"); 119 | 120 | /* alloc auxiliary variables */ 121 | gsl_vector* x = gsl_vector_alloc(m_num_factors); 122 | 123 | gsl_matrix* phi = NULL; 124 | gsl_matrix* word_ss = NULL; 125 | gsl_matrix* log_beta = NULL; 126 | gsl_vector* gamma = NULL; 127 | 128 | if (param->ctr_run && param->theta_opt) { 129 | int max_len = c->max_corpus_length(); 130 | phi = gsl_matrix_calloc(max_len, m_num_factors); 131 | word_ss = gsl_matrix_calloc(m_num_factors, c->m_size_vocab); 132 | log_beta = gsl_matrix_calloc(m_num_factors, c->m_size_vocab); 133 | gsl_matrix_memcpy(log_beta, m_beta); 134 | mtx_log(log_beta); 135 | gamma = gsl_vector_alloc(m_num_factors); 136 | } 137 | 138 | /* tmp variables for indexes */ 139 | int i, j, m, n, l, k, ll, jj; 140 | int* item_ids; 141 | bool positive = true; 142 | 143 | double result, inner; 144 | int active_num_items = 0; 145 | for (j = 0; j < m_num_items; ++j) { 146 | if (items->m_vec_len[j] > 0) 147 | active_num_items++; 148 | } 149 | 150 | int* idx_base = new int[active_num_items]; 151 | l = 0; 152 | for (j = 0; j < m_num_items; ++j) { 153 | if (items->m_vec_len[j] > 0) { 154 | idx_base[l] = j; 155 | ++l; 156 | } 157 | } 158 | int* sel = new int[active_num_items]; 159 | 160 | while (iter < param->max_iter) { 161 | likelihood_old = likelihood; 162 | likelihood = 0.0; 163 | 164 | for (i = 0; i < m_num_users; ++i) { 165 | item_ids = users->m_vec_data[i]; 166 | n = users->m_vec_len[i]; 167 | if (n > 0) { 168 | double lambda_u = param->lambda_u / (2*n); 169 | gsl_vector_view u = gsl_matrix_row(m_U, i); 170 | // this user has rated some articles 171 | // Randomly choose 2*n negative examples 172 | sample_k_from_n(n, active_num_items, sel, idx_base); 173 | qsort(sel, n, sizeof(int), compare); 174 | l = 0; ll = 0; 175 | while (true) { 176 | if (l < n) { 177 | j = item_ids[l]; // positive 178 | } else { 179 | j = -1; 180 | } 181 | 182 | if (ll < n) { 183 | jj = sel[ll]; //negative 184 | while (ll < n-1 && jj == sel[ll+1]) ++ll; // skip same values 185 | } else { 186 | jj = -1; 187 | } 188 | 189 | if (j == -1) { 190 | if (jj == -1) break; 191 | else { 192 | positive = false; // jj is a negative example 193 | ++ll; 194 | } 195 | } else { 196 | if (j < jj) { 197 | positive = true; // j is a positive example 198 | ++l; 199 | } else if (j == jj) { 200 | positive = true; // j is a positive example 201 | ++l; 202 | ++ll; 203 | } else { // j > jj 204 | if (jj == -1) { 205 | positive = true; // j is a positive example 206 | ++l; 207 | } else { 208 | positive = false; 209 | ++ll; // jj is a negative example 210 | } 211 | } 212 | } 213 | gsl_vector_view v; 214 | gsl_vector_view theta_v; 215 | double lambda_v = 0.0; 216 | if (positive) { 217 | // j is a positive example 218 | lambda_v = param->lambda_v / (2 * items->m_vec_len[j]); 219 | v = gsl_matrix_row(m_V, j); 220 | theta_v = gsl_matrix_row(m_theta, j); 221 | // second-order 222 | // u 223 | gsl_vector_scale(&u.vector, 1 - learning_rate); 224 | gsl_blas_ddot(&v.vector, &v.vector, &inner); 225 | gsl_blas_daxpy(learning_rate / (lambda_u + inner), &v.vector, &u.vector); 226 | // v 227 | if (!param->lda_regression) { 228 | gsl_vector_scale(&v.vector, 1 - learning_rate); 229 | gsl_blas_daxpy(learning_rate, &theta_v.vector, &v.vector); 230 | gsl_blas_ddot(&u.vector, &u.vector, &inner); 231 | gsl_blas_ddot(&u.vector, &theta_v.vector, &result); 232 | gsl_blas_daxpy(learning_rate * (1.0 - result) / (lambda_v + inner), &u.vector, &v.vector); 233 | } 234 | 235 | gsl_blas_ddot(&u.vector, &v.vector, &result); 236 | likelihood += -0.5 * (1 - result) * (1 - result); 237 | // gsl_blas_ddot(&u.vector, &v.vector, &result); 238 | // result -= 1.0; 239 | } else { 240 | // jj is a negative example 241 | lambda_v = param->lambda_v / (2 * items->m_vec_len[jj]); 242 | v = gsl_matrix_row(m_V, jj); 243 | theta_v = gsl_matrix_row(m_theta, jj); 244 | // second order 245 | // u 246 | gsl_vector_scale(&u.vector, 1 - learning_rate); 247 | 248 | // v 249 | if (!param->lda_regression) { 250 | gsl_vector_scale(&v.vector, 1 - learning_rate); 251 | gsl_blas_daxpy(learning_rate, &theta_v.vector, &v.vector); 252 | gsl_blas_ddot(&u.vector, &u.vector, &inner); 253 | gsl_blas_ddot(&u.vector, &theta_v.vector, &result); 254 | gsl_blas_daxpy(-learning_rate * result / (lambda_v + inner), &u.vector, &v.vector); 255 | } 256 | 257 | gsl_blas_ddot(&u.vector, &v.vector, &result); 258 | likelihood += -0.5 * result * result; 259 | // gsl_blas_ddot(&u.vector, &v.vector, &result); 260 | } 261 | // update u 262 | // first-order 263 | // gsl_vector_scale(&u.vector, 1 - param->learning_rate * lambda_u); 264 | // gsl_blas_daxpy(-result * param->learning_rate, &v.vector, &u.vector); 265 | // second order 266 | 267 | // update v 268 | // gsl_vector_scale(&v.vector, 1 - param->learning_rate * lambda_v); 269 | // gsl_blas_daxpy(-result * param->learning_rate, &u.vector, &v.vector); 270 | // gsl_blas_daxpy(param->learning_rate * lambda_v, &theta_v.vector, &v.vector); 271 | } 272 | assert(n == l && n == l); 273 | //printf("n=%d, l=%d, ll=%d, j=%d, jj=%d\n", n, l, ll, j, jj); 274 | 275 | // update the likelihood 276 | gsl_blas_ddot(&u.vector, &u.vector, &result); 277 | likelihood += -0.5 * param->lambda_u * result; 278 | } 279 | } 280 | 281 | for (j = 0; j < m_num_items; ++j) { 282 | gsl_vector_view v = gsl_matrix_row(m_V, j); 283 | gsl_vector_view theta_v = gsl_matrix_row(m_theta, j); 284 | gsl_vector_memcpy(x, &v.vector); 285 | gsl_vector_sub(x, &theta_v.vector); 286 | gsl_blas_ddot(x, x, &result); 287 | likelihood += -0.5 * param->lambda_v * result; 288 | } 289 | 290 | // update theta 291 | if (param->ctr_run && param->theta_opt) { 292 | gsl_matrix_set_zero(word_ss); 293 | for (j = 0; j < m_num_items; j ++) { 294 | gsl_vector_view v = gsl_matrix_row(m_V, j); 295 | gsl_vector_view theta_v = gsl_matrix_row(m_theta, j); 296 | m = items->m_vec_len[j]; 297 | if (m>0) { 298 | // m > 0, some users have rated this article 299 | const c_document* doc = c->m_docs[j]; 300 | likelihood += doc_inference(doc, &theta_v.vector, log_beta, phi, gamma, word_ss, true); 301 | optimize_simplex(gamma, &v.vector, param->lambda_v, &theta_v.vector); 302 | } 303 | else { 304 | // m=0, this article has never been rated 305 | const c_document* doc = c->m_docs[j]; 306 | doc_inference(doc, &theta_v.vector, log_beta, phi, gamma, word_ss, false); 307 | vnormalize(gamma); 308 | gsl_vector_memcpy(&theta_v.vector, gamma); 309 | } 310 | } 311 | gsl_matrix_memcpy(m_beta, word_ss); 312 | for (k = 0; k < m_num_factors; k ++) { 313 | gsl_vector_view row = gsl_matrix_row(m_beta, k); 314 | vnormalize(&row.vector); 315 | } 316 | gsl_matrix_memcpy(log_beta, m_beta); 317 | mtx_log(log_beta); 318 | } 319 | 320 | time(¤t); 321 | elapsed = (int)difftime(current, start); 322 | 323 | iter++; 324 | if (iter > 50 && learning_rate > 0.001) learning_rate /= 2.0; 325 | converge = fabs((likelihood-likelihood_old)/likelihood_old); 326 | 327 | fprintf(file, "%04d %06d %10.5f %.10f\n", iter, elapsed, likelihood, converge); 328 | fflush(file); 329 | printf("iter=%04d, time=%06d, likelihood=%.5f, converge=%.10f\n", iter, elapsed, likelihood, converge); 330 | 331 | // save intermediate results 332 | if (iter % param->save_lag == 0) { 333 | 334 | sprintf(name, "%s/%04d-U.dat", directory, iter); 335 | FILE * file_U = fopen(name, "w"); 336 | gsl_matrix_fwrite(file_U, m_U); 337 | fclose(file_U); 338 | 339 | sprintf(name, "%s/%04d-V.dat", directory, iter); 340 | FILE * file_V = fopen(name, "w"); 341 | gsl_matrix_fwrite(file_V, m_V); 342 | fclose(file_V); 343 | 344 | if (param->ctr_run && param->theta_opt) { 345 | sprintf(name, "%s/%04d-theta.dat", directory, iter); 346 | FILE * file_theta = fopen(name, "w"); 347 | gsl_matrix_fwrite(file_theta, m_theta); 348 | fclose(file_theta); 349 | 350 | sprintf(name, "%s/%04d-beta.dat", directory, iter); 351 | FILE * file_beta = fopen(name, "w"); 352 | gsl_matrix_fwrite(file_beta, m_beta); 353 | fclose(file_beta); 354 | } 355 | } 356 | } 357 | 358 | // save final results 359 | sprintf(name, "%s/final-U.dat", directory); 360 | FILE * file_U = fopen(name, "w"); 361 | gsl_matrix_fwrite(file_U, m_U); 362 | fclose(file_U); 363 | 364 | sprintf(name, "%s/final-V.dat", directory); 365 | FILE * file_V = fopen(name, "w"); 366 | gsl_matrix_fwrite(file_V, m_V); 367 | fclose(file_V); 368 | 369 | if (param->ctr_run && param->theta_opt) { 370 | sprintf(name, "%s/final-theta.dat", directory); 371 | FILE * file_theta = fopen(name, "w"); 372 | gsl_matrix_fwrite(file_theta, m_theta); 373 | fclose(file_theta); 374 | 375 | sprintf(name, "%s/final-beta.dat", directory); 376 | FILE * file_beta = fopen(name, "w"); 377 | gsl_matrix_fwrite(file_beta, m_beta); 378 | fclose(file_beta); 379 | } 380 | 381 | // free memory 382 | gsl_vector_free(x); 383 | delete [] idx_base; 384 | delete [] sel; 385 | 386 | if (param->ctr_run && param->theta_opt) { 387 | gsl_matrix_free(phi); 388 | gsl_matrix_free(log_beta); 389 | gsl_matrix_free(word_ss); 390 | gsl_vector_free(gamma); 391 | } 392 | } 393 | 394 | void c_ctr::learn_map_estimate(const c_data* users, const c_data* items, 395 | const c_double_data* users_a, const c_double_data* items_a, 396 | const c_corpus* c, const ctr_hyperparameter* param, 397 | const char* directory) { 398 | // init model parameters 399 | printf("\ninitializing the model ...\n"); 400 | init_model(param->ctr_run); 401 | 402 | // filename 403 | char name[500]; 404 | 405 | // start time 406 | time_t start, current; 407 | time(&start); 408 | int elapsed = 0; 409 | 410 | int iter = 0; 411 | double likelihood = -exp(50), likelihood_old; 412 | double converge = 1.0; 413 | 414 | /// create the state log file 415 | sprintf(name, "%s/state.log", directory); 416 | FILE* file = fopen(name, "w"); 417 | fprintf(file, "iter time likelihood converge\n"); 418 | 419 | 420 | /* alloc auxiliary variables */ 421 | gsl_matrix* XX = gsl_matrix_alloc(m_num_factors, m_num_factors); 422 | gsl_matrix* A = gsl_matrix_alloc(m_num_factors, m_num_factors); 423 | gsl_matrix* B = gsl_matrix_alloc(m_num_factors, m_num_factors); 424 | gsl_vector* x = gsl_vector_alloc(m_num_factors); 425 | 426 | gsl_matrix* phi = NULL; 427 | gsl_matrix* word_ss = NULL; 428 | gsl_matrix* log_beta = NULL; 429 | gsl_vector* gamma = NULL; 430 | 431 | if (param->ctr_run && param->theta_opt) { 432 | int max_len = c->max_corpus_length(); 433 | phi = gsl_matrix_calloc(max_len, m_num_factors); 434 | word_ss = gsl_matrix_calloc(m_num_factors, c->m_size_vocab); 435 | log_beta = gsl_matrix_calloc(m_num_factors, c->m_size_vocab); 436 | gsl_matrix_memcpy(log_beta, m_beta); 437 | mtx_log(log_beta); 438 | gamma = gsl_vector_alloc(m_num_factors); 439 | } 440 | 441 | /* tmp variables for indexes */ 442 | int i, j, m, n, l, k; 443 | int* item_ids; 444 | int* user_ids; 445 | double* item_confs; 446 | double* user_confs; 447 | 448 | double result; 449 | 450 | /// confidence parameters 451 | double a; 452 | 453 | while ((iter < param->max_iter and converge > 1e-4 ) or iter < min_iter) { 454 | 455 | likelihood_old = likelihood; 456 | likelihood = 0.0; 457 | 458 | // update U 459 | gsl_matrix_set_zero(XX); 460 | for (j = 0; j < m_num_items; j ++) { 461 | m = items->m_vec_len[j]; 462 | if (m>0) { 463 | gsl_vector_const_view v = gsl_matrix_const_row(m_V, j); 464 | gsl_blas_dger(1.0, &v.vector, &v.vector, XX); 465 | } 466 | } 467 | gsl_matrix_scale(XX, param->b); 468 | // this is only for U 469 | gsl_matrix_add_diagonal(XX, param->lambda_u); 470 | 471 | for (i = 0; i < m_num_users; i ++) { 472 | item_ids = users->m_vec_data[i]; 473 | 474 | // Get the list of confidence values for this user, one value for each rated item 475 | user_confs = users_a->m_vec_data[i]; 476 | 477 | n = users->m_vec_len[i]; 478 | if (n > 0) { 479 | // this user has rated some articles 480 | gsl_matrix_memcpy(A, XX); 481 | gsl_vector_set_zero(x); 482 | for (l=0; l < n; l ++) { 483 | j = item_ids[l]; 484 | a = user_confs[l]; 485 | gsl_vector_const_view v = gsl_matrix_const_row(m_V, j); 486 | gsl_blas_dger(a - param->b, &v.vector, &v.vector, A); 487 | gsl_blas_daxpy(a, &v.vector, x); 488 | } 489 | 490 | gsl_vector_view u = gsl_matrix_row(m_U, i); 491 | matrix_vector_solve(A, x, &(u.vector)); 492 | 493 | // update the likelihood 494 | gsl_blas_ddot(&u.vector, &u.vector, &result); 495 | likelihood += -0.5 * param->lambda_u * result; 496 | } 497 | } 498 | 499 | if (param->lda_regression) break; // one iteration is enough for lda-regression 500 | 501 | // update V 502 | if (param->ctr_run && param->theta_opt) gsl_matrix_set_zero(word_ss); 503 | 504 | gsl_matrix_set_zero(XX); 505 | for (i = 0; i < m_num_users; i ++) { 506 | n = users->m_vec_len[i]; 507 | if (n>0) { 508 | gsl_vector_const_view u = gsl_matrix_const_row(m_U, i); 509 | gsl_blas_dger(1.0, &u.vector, &u.vector, XX); 510 | } 511 | } 512 | gsl_matrix_scale(XX, param->b); 513 | 514 | for (j = 0; j < m_num_items; j ++) { 515 | gsl_vector_view v = gsl_matrix_row(m_V, j); 516 | gsl_vector_view theta_v = gsl_matrix_row(m_theta, j); 517 | 518 | user_ids = items->m_vec_data[j]; 519 | // Get the list of confidence values for this item, one value for each rating 520 | item_confs = items_a->m_vec_data[j]; 521 | 522 | m = items->m_vec_len[j]; 523 | if (m>0) { 524 | // m > 0, some users have rated this article 525 | gsl_matrix_memcpy(A, XX); 526 | gsl_vector_set_zero(x); 527 | for (l = 0; l < m; l ++) { 528 | i = user_ids[l]; 529 | a = item_confs[l]; 530 | gsl_vector_const_view u = gsl_matrix_const_row(m_U, i); 531 | gsl_blas_dger(a - param->b, &u.vector, &u.vector, A); 532 | gsl_blas_daxpy(a, &u.vector, x); 533 | } 534 | 535 | // adding the topic vector 536 | // even when ctr_run=0, m_theta=0 537 | gsl_blas_daxpy(param->lambda_v, &theta_v.vector, x); 538 | 539 | gsl_matrix_memcpy(B, A); // save for computing likelihood 540 | 541 | // here different from U update 542 | gsl_matrix_add_diagonal(A, param->lambda_v); 543 | matrix_vector_solve(A, x, &v.vector); 544 | 545 | // update the likelihood for the relevant part 546 | // If a is the same for all ratings: 547 | // likelihood += -0.5 * m * param->a; 548 | for (l = 0; l < m; l ++) { 549 | i = user_ids[l]; 550 | a = item_confs[l]; 551 | gsl_vector_const_view u = gsl_matrix_const_row(m_U, i); 552 | gsl_blas_ddot(&u.vector, &v.vector, &result); 553 | likelihood += -0.5 * a + a * result; 554 | } 555 | likelihood += -0.5 * mahalanobis_prod(B, &v.vector, &v.vector); 556 | // likelihood part of theta, even when theta=0, which is a 557 | // special case 558 | gsl_vector_memcpy(x, &v.vector); 559 | gsl_vector_sub(x, &theta_v.vector); 560 | gsl_blas_ddot(x, x, &result); 561 | likelihood += -0.5 * param->lambda_v * result; 562 | 563 | if (param->ctr_run && param->theta_opt) { 564 | const c_document* doc = c->m_docs[j]; 565 | likelihood += doc_inference(doc, &theta_v.vector, log_beta, phi, gamma, word_ss, true); 566 | optimize_simplex(gamma, &v.vector, param->lambda_v, &theta_v.vector); 567 | } 568 | } 569 | else { 570 | // m=0, this article has never been rated 571 | if (param->ctr_run && param->theta_opt) { 572 | const c_document* doc = c->m_docs[j]; 573 | doc_inference(doc, &theta_v.vector, log_beta, phi, gamma, word_ss, false); 574 | vnormalize(gamma); 575 | gsl_vector_memcpy(&theta_v.vector, gamma); 576 | } 577 | } 578 | } 579 | 580 | // update beta if needed 581 | if (param->ctr_run && param->theta_opt) { 582 | gsl_matrix_memcpy(m_beta, word_ss); 583 | for (k = 0; k < m_num_factors; k ++) { 584 | gsl_vector_view row = gsl_matrix_row(m_beta, k); 585 | vnormalize(&row.vector); 586 | } 587 | gsl_matrix_memcpy(log_beta, m_beta); 588 | mtx_log(log_beta); 589 | } 590 | 591 | time(¤t); 592 | elapsed = (int)difftime(current, start); 593 | 594 | iter++; 595 | converge = fabs((likelihood-likelihood_old)/likelihood_old); 596 | 597 | if (likelihood < likelihood_old) printf("likelihood is decreasing!\n"); 598 | 599 | fprintf(file, "%04d %06d %10.5f %.10f\n", iter, elapsed, likelihood, converge); 600 | fflush(file); 601 | printf("iter=%04d, time=%06d, likelihood=%.5f, converge=%.10f\n", iter, elapsed, likelihood, converge); 602 | 603 | // save intermediate results 604 | if (iter % param->save_lag == 0) { 605 | 606 | sprintf(name, "%s/%04d-U.dat", directory, iter); 607 | FILE * file_U = fopen(name, "w"); 608 | mtx_fprintf(file_U, m_U); 609 | fclose(file_U); 610 | 611 | sprintf(name, "%s/%04d-V.dat", directory, iter); 612 | FILE * file_V = fopen(name, "w"); 613 | mtx_fprintf(file_V, m_V); 614 | fclose(file_V); 615 | 616 | if (param->ctr_run) { 617 | sprintf(name, "%s/%04d-theta.dat", directory, iter); 618 | FILE * file_theta = fopen(name, "w"); 619 | mtx_fprintf(file_theta, m_theta); 620 | fclose(file_theta); 621 | 622 | sprintf(name, "%s/%04d-beta.dat", directory, iter); 623 | FILE * file_beta = fopen(name, "w"); 624 | mtx_fprintf(file_beta, m_beta); 625 | fclose(file_beta); 626 | } 627 | } 628 | } 629 | 630 | // save final results 631 | sprintf(name, "%s/final-U.dat", directory); 632 | FILE * file_U = fopen(name, "w"); 633 | mtx_fprintf(file_U, m_U); 634 | fclose(file_U); 635 | 636 | sprintf(name, "%s/final-V.dat", directory); 637 | FILE * file_V = fopen(name, "w"); 638 | mtx_fprintf(file_V, m_V); 639 | fclose(file_V); 640 | 641 | if (param->ctr_run) { 642 | sprintf(name, "%s/final-theta.dat", directory); 643 | FILE * file_theta = fopen(name, "w"); 644 | mtx_fprintf(file_theta, m_theta); 645 | fclose(file_theta); 646 | 647 | sprintf(name, "%s/final-beta.dat", directory); 648 | FILE * file_beta = fopen(name, "w"); 649 | mtx_fprintf(file_beta, m_beta); 650 | fclose(file_beta); 651 | } 652 | 653 | // free memory 654 | gsl_matrix_free(XX); 655 | gsl_matrix_free(A); 656 | gsl_matrix_free(B); 657 | gsl_vector_free(x); 658 | 659 | if (param->ctr_run && param->theta_opt) { 660 | gsl_matrix_free(phi); 661 | gsl_matrix_free(log_beta); 662 | gsl_matrix_free(word_ss); 663 | gsl_vector_free(gamma); 664 | } 665 | } 666 | 667 | double c_ctr::doc_inference(const c_document* doc, const gsl_vector* theta_v, 668 | const gsl_matrix* log_beta, gsl_matrix* phi, 669 | gsl_vector* gamma, gsl_matrix* word_ss, 670 | bool update_word_ss) { 671 | 672 | double pseudo_count = 1.0; 673 | double likelihood = 0; 674 | gsl_vector* log_theta_v = gsl_vector_alloc(theta_v->size); 675 | gsl_vector_memcpy(log_theta_v, theta_v); 676 | vct_log(log_theta_v); 677 | 678 | int n, k, w; 679 | double x; 680 | for (n = 0; n < doc->m_length; n ++) { 681 | w = doc->m_words[n]; 682 | for (k = 0; k < m_num_factors; k ++) 683 | mset(phi, n, k, vget(theta_v, k) * mget(m_beta, k, w)); 684 | 685 | gsl_vector_view row = gsl_matrix_row(phi, n); 686 | vnormalize(&row.vector); 687 | 688 | for (k = 0; k < m_num_factors; k ++) { 689 | x = mget(phi, n, k); 690 | if (x > 0) 691 | likelihood += x*(vget(log_theta_v, k) + mget(log_beta, k, w) - log(x)); 692 | } 693 | } 694 | 695 | if (pseudo_count > 0) { 696 | likelihood += pseudo_count * vsum(log_theta_v); 697 | } 698 | 699 | gsl_vector_set_all(gamma, pseudo_count); // smoothing with small pseudo counts 700 | for (n = 0; n < doc->m_length; n ++) { 701 | for (k = 0; k < m_num_factors; k ++) { 702 | x = doc->m_counts[n] * mget(phi, n, k); 703 | vinc(gamma, k, x); 704 | if (update_word_ss) minc(word_ss, k, doc->m_words[n], x); 705 | } 706 | } 707 | 708 | gsl_vector_free(log_theta_v); 709 | return likelihood; 710 | } 711 | -------------------------------------------------------------------------------- /C_code_TCTR/ctr.h: -------------------------------------------------------------------------------- 1 | // class for ctr 2 | // 3 | #ifndef CTR_H 4 | #define CTR_H 5 | 6 | #include "utils.h" 7 | #include "corpus.h" 8 | #include "data.h" 9 | 10 | struct ctr_hyperparameter { 11 | double a; 12 | double b; 13 | double lambda_u; 14 | double lambda_v; 15 | double learning_rate; 16 | double alpha_smooth; 17 | int random_seed; 18 | int max_iter; 19 | int save_lag; 20 | int theta_opt; 21 | int ctr_run; 22 | int lda_regression; 23 | 24 | void set(double aa, double bb, 25 | double lu, double lv, 26 | double lr, double as, 27 | int rs, int mi, int sl, 28 | int to, int cr, int lda_r) { 29 | a = aa; b = bb; 30 | lambda_u = lu; lambda_v = lv; 31 | learning_rate = lr; 32 | alpha_smooth = as; 33 | random_seed = rs; max_iter = mi; 34 | save_lag = sl; theta_opt = to; 35 | ctr_run = cr; lda_regression = lda_r; 36 | } 37 | 38 | void save(char* filename) { 39 | FILE * file = fopen(filename, "w"); 40 | fprintf(file, "a = %.4f\n", a); 41 | fprintf(file, "b = %.4f\n", b); 42 | fprintf(file, "lambda_u = %.4f\n", lambda_u); 43 | fprintf(file, "lambda_v = %.4f\n", lambda_v); 44 | fprintf(file, "learning_rate = %.6f\n", learning_rate); 45 | fprintf(file, "alpha_smooth = %.6f\n", alpha_smooth); 46 | fprintf(file, "random seed = %d\n", (int)random_seed); 47 | fprintf(file, "max iter = %d\n", max_iter); 48 | fprintf(file, "save lag = %d\n", save_lag); 49 | fprintf(file, "theta opt = %d\n", theta_opt); 50 | fprintf(file, "ctr run = %d\n", ctr_run); 51 | fprintf(file, "lda_regression = %d\n", lda_regression); 52 | fclose(file); 53 | } 54 | }; 55 | 56 | class c_ctr { 57 | public: 58 | c_ctr(); 59 | ~c_ctr(); 60 | void read_init_information(const char* theta_init_path, 61 | const char* beta_init_path, 62 | const c_corpus* c, double alpha_smooth); 63 | 64 | void set_model_parameters(int num_factors, 65 | int num_users, 66 | int num_items); 67 | 68 | void learn_map_estimate(const c_data* users, const c_data* items, 69 | const c_double_data* users_a, const c_double_data* items_a, 70 | const c_corpus* c, const ctr_hyperparameter* param, 71 | const char* directory); 72 | 73 | void stochastic_learn_map_estimate(const c_data* users, const c_data* items, 74 | const c_double_data* users_a, const c_double_data* items_a, 75 | const c_corpus* c, const ctr_hyperparameter* param, 76 | const char* directory); 77 | 78 | void init_model(int ctr_run); 79 | 80 | double doc_inference(const c_document* doc, const gsl_vector* theta_v, 81 | const gsl_matrix* log_beta, gsl_matrix* phi, 82 | gsl_vector* gamma, gsl_matrix* word_ss, 83 | bool update_word_ss); 84 | public: 85 | gsl_matrix* m_beta; 86 | gsl_matrix* m_theta; 87 | 88 | gsl_matrix* m_U; 89 | gsl_matrix* m_V; 90 | 91 | int m_num_factors; // m_num_topics 92 | int m_num_items; // m_num_docs 93 | int m_num_users; // num of users 94 | }; 95 | 96 | #endif // CTR_H 97 | -------------------------------------------------------------------------------- /C_code_TCTR/data.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include "data.h" 4 | 5 | c_double_data::c_double_data() { 6 | } 7 | 8 | c_double_data::~c_double_data() { 9 | for (size_t i = 0; i < m_vec_data.size(); i ++) { 10 | double* confs = m_vec_data[i]; 11 | if (confs != NULL) delete [] confs; 12 | } 13 | m_vec_data.clear(); 14 | m_vec_len.clear(); 15 | } 16 | 17 | void c_double_data::read_data(const char * data_filename, int OFFSET) { 18 | 19 | int length = 0, n = 0, total = 0; 20 | double conf; 21 | 22 | FILE * fileptr; 23 | fileptr = fopen(data_filename, "r"); 24 | 25 | while ((fscanf(fileptr, "%10d", &length) != EOF)) { 26 | double * confs = NULL; 27 | if (length > 0) { 28 | confs = new double[length]; 29 | for (n = 0; n < length; n++) { 30 | fscanf(fileptr, "%lf", &conf); 31 | confs[n] = conf; 32 | } 33 | } 34 | m_vec_data.push_back(confs); 35 | m_vec_len.push_back(length); 36 | total += length; 37 | } 38 | fclose(fileptr); 39 | printf("read %d vectors with %d entries ...\n", (int)m_vec_len.size(), total); 40 | } 41 | 42 | c_data::c_data() { 43 | } 44 | 45 | c_data::~c_data() { 46 | for (size_t i = 0; i < m_vec_data.size(); i ++) { 47 | int* ids = m_vec_data[i]; 48 | if (ids != NULL) delete [] ids; 49 | } 50 | m_vec_data.clear(); 51 | m_vec_len.clear(); 52 | } 53 | 54 | void c_data::read_data(const char * data_filename, int OFFSET) { 55 | 56 | int length = 0, n = 0, id = 0, total = 0; 57 | 58 | FILE * fileptr; 59 | fileptr = fopen(data_filename, "r"); 60 | 61 | while ((fscanf(fileptr, "%10d", &length) != EOF)) { 62 | int * ids = NULL; 63 | if (length > 0) { 64 | ids = new int[length]; 65 | for (n = 0; n < length; n++) { 66 | fscanf(fileptr, "%10d", &id); 67 | ids[n] = id - OFFSET; 68 | } 69 | } 70 | m_vec_data.push_back(ids); 71 | m_vec_len.push_back(length); 72 | total += length; 73 | } 74 | fclose(fileptr); 75 | printf("read %d vectors with %d entries ...\n", (int)m_vec_len.size(), total); 76 | } 77 | 78 | 79 | -------------------------------------------------------------------------------- /C_code_TCTR/data.h: -------------------------------------------------------------------------------- 1 | // class for reading the sparse matrix data 2 | // for both user confidence matrix and item confidence matrix 3 | // user matrix: 4 | // number_of_items confidence_item1 confidence_item2 ... 5 | // item matrix: 6 | // number_of_users confidence_user1 confidence_user2 ... 7 | 8 | #ifndef DATA_H 9 | #define DATA_H 10 | 11 | #include 12 | 13 | using namespace std; 14 | 15 | class c_double_data { 16 | public: 17 | c_double_data(); 18 | ~c_double_data(); 19 | void read_data(const char * data_filename, int OFFSET=0); 20 | public: 21 | vector m_vec_data; 22 | vector m_vec_len; 23 | }; 24 | 25 | class c_data { 26 | public: 27 | c_data(); 28 | ~c_data(); 29 | void read_data(const char * data_filename, int OFFSET=0); 30 | public: 31 | vector m_vec_data; 32 | vector m_vec_len; 33 | }; 34 | 35 | #endif // DATA_H 36 | -------------------------------------------------------------------------------- /C_code_TCTR/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include "ctr.h" 5 | 6 | gsl_rng * RANDOM_NUMBER = NULL; 7 | 8 | void print_usage_and_exit() { 9 | // print usage information 10 | printf("*********************************collaborative topic models for recommendations************************\n"); 11 | printf("Authors: Chong Wang, chongw@cs.princeton.edu, Computer Science Department, Princeton University.\n"); 12 | printf("usage:\n"); 13 | printf(" ctr [options]\n"); 14 | printf(" --help: print help information\n"); 15 | 16 | printf("\n"); 17 | printf(" --directory: save directory, required\n"); 18 | 19 | printf("\n"); 20 | printf(" --user: user file, required\n"); 21 | printf(" --user_a: user confidence file, required\n"); 22 | printf(" --item: item file, required\n"); 23 | printf(" --item_a: item confidence file, required\n"); 24 | printf(" --a: positive item weight, default 1\n"); 25 | printf(" --b: negative item weight, default 0.01 (b < a)\n"); 26 | printf(" --lambda_u: user vector regularizer, default 0.01\n"); 27 | printf(" --lambda_v: item vector regularizer, default 100\n"); 28 | printf(" --learning_rate: stochastic version for large datasets, default -1. Stochastic learning will be called when > 0.\n"); 29 | printf(" --alpha_smooth: alpha smooth, default [0.0]\n"); 30 | printf("\n"); 31 | 32 | printf(" --random_seed: the random seed, default from the current time\n"); 33 | printf(" --save_lag: the saving lag, default 20 (-1 means no savings for intermediate results)\n"); 34 | printf(" --max_iter: the max number of iterations, default 200\n"); 35 | printf("\n"); 36 | 37 | printf(" --num_factors: the number of factors, default 200\n"); 38 | printf(" --mult: mult file, in lda-c format, optional, if not provided, it's the matrix factorization\n"); 39 | printf(" --theta_init: topic proportions file from lda, optional (required if mult file is provided)\n"); 40 | printf(" --beta_init: topic distributions file from lda, optional (required if mult file is provided)\n"); 41 | printf(" --theta_opt: optimize theta or not, optional, default not\n"); 42 | printf(" --lda_regression: run lda regression, default not\n"); 43 | 44 | printf("*******************************************************************************************************\n"); 45 | 46 | exit(0); 47 | } 48 | 49 | int main(int argc, char* argv[]) { 50 | if (argc < 2) print_usage_and_exit(); 51 | 52 | char filename[500]; 53 | int theta_opt = 0; 54 | int lda_regression = 0; 55 | 56 | const char* const short_options = "hd:x:c:i:f:a:b:u:v:r:s:m:k:t:e:y:z:w:"; 57 | const struct option long_options[] = { 58 | {"help", no_argument, NULL, 'h'}, 59 | {"directory", required_argument, NULL, 'd'}, 60 | {"user", required_argument, NULL, 'x'}, 61 | {"user_a", required_argument, NULL, 'c'}, 62 | {"item", required_argument, NULL, 'i'}, 63 | {"item_a", required_argument, NULL, 'f'}, 64 | {"a", required_argument, NULL, 'a'}, 65 | {"b", required_argument, NULL, 'b'}, 66 | {"lambda_u", required_argument, NULL, 'u'}, 67 | {"lambda_v", required_argument, NULL, 'v'}, 68 | {"random_seed", required_argument, NULL, 'r'}, 69 | {"save_lag", required_argument, NULL, 's'}, 70 | {"max_iter", required_argument, NULL, 'm'}, 71 | {"num_factors", required_argument, NULL, 'k'}, 72 | {"mult", required_argument, NULL, 't'}, 73 | {"theta_init", required_argument, NULL, 'e'}, 74 | {"beta_init", required_argument, NULL, 'y'}, 75 | {"learning_rate", required_argument, NULL, 'z'}, 76 | {"alpha_smooth", required_argument, NULL, 'w'}, 77 | {"theta_opt", no_argument, &theta_opt, 1}, 78 | {"lda_regression",no_argument, &lda_regression, 1}, 79 | {NULL, 0, NULL, 0}}; 80 | 81 | char* directory = NULL; 82 | 83 | char* user_path = NULL; 84 | char* item_path = NULL; 85 | char* user_a_path = NULL; 86 | char* item_a_path = NULL; 87 | double a = 1.0; 88 | double b = 0.01; 89 | double lambda_u = 0.01; 90 | double lambda_v = 100; 91 | double learning_rate = -1; 92 | double alpha_smooth = 0.0; 93 | 94 | time_t t; time(&t); 95 | long random_seed = (long) t; 96 | int save_lag = 20; 97 | int max_iter = 200; 98 | 99 | int num_factors = 200; 100 | char* mult_path = NULL; 101 | char* theta_init_path = NULL; 102 | char* beta_init_path = NULL; 103 | 104 | int cc = 0; 105 | while(true) { 106 | cc = getopt_long(argc, argv, short_options, long_options, NULL); 107 | switch(cc) { 108 | case 'h': 109 | print_usage_and_exit(); 110 | break; 111 | case 'd': 112 | directory = optarg; 113 | break; 114 | case 'x': 115 | user_path = optarg; 116 | break; 117 | case 'c': 118 | user_a_path = optarg; 119 | break; 120 | case 'i': 121 | item_path = optarg; 122 | break; 123 | case 'f': 124 | item_a_path = optarg; 125 | break; 126 | case 'a': 127 | a = atof(optarg); 128 | break; 129 | case 'b': 130 | b = atof(optarg); 131 | break; 132 | case 'u': 133 | lambda_u = atof(optarg); 134 | break; 135 | case 'v': 136 | lambda_v = atof(optarg); 137 | break; 138 | case 'z': 139 | learning_rate = atof(optarg); 140 | break; 141 | case 'w': 142 | alpha_smooth = atof(optarg); 143 | break; 144 | case 'r': 145 | random_seed = atoi(optarg); 146 | break; 147 | case 's': 148 | save_lag = atoi(optarg); 149 | break; 150 | case 'm': 151 | max_iter = atoi(optarg); 152 | break; 153 | case 'k': 154 | num_factors = atoi(optarg); 155 | break; 156 | case 't': 157 | mult_path = optarg; 158 | break; 159 | case 'e': 160 | theta_init_path = optarg; 161 | break; 162 | case 'y': 163 | beta_init_path = optarg; 164 | break; 165 | case -1: 166 | break; 167 | case '?': 168 | print_usage_and_exit(); 169 | break; 170 | default: 171 | break; 172 | } 173 | if (cc == -1) 174 | break; 175 | } 176 | 177 | /// print information 178 | printf("\n************************************************************************************************\n"); 179 | 180 | if (!dir_exists(directory)) make_directory(directory); 181 | printf("result directory: %s\n", directory); 182 | 183 | if (!file_exists(user_path)) { 184 | printf("user file %s doesn't exist! quit ...\n", user_path); 185 | exit(-1); 186 | } 187 | printf("user file: %s\n", user_path); 188 | if (!file_exists(user_a_path)) { 189 | printf("user confidence file %s doesn't exist! quit ...\n", user_a_path); 190 | exit(-1); 191 | } 192 | printf("user confidence file: %s\n", user_a_path); 193 | 194 | if (!file_exists(item_path)) { 195 | printf("item file %s doesn't exist! quit ...\n", item_path); 196 | exit(-1); 197 | } 198 | printf("item file: %s\n", item_path); 199 | 200 | if (!file_exists(item_a_path)) { 201 | printf("item confidence file %s doesn't exist! quit ...\n", item_a_path); 202 | exit(-1); 203 | } 204 | printf("item confidence file: %s\n", item_a_path); 205 | 206 | printf("a: %.4f\n", a); 207 | printf("b: %.4f\n", b); 208 | printf("lambda_u: %.4f\n", lambda_u); 209 | printf("lambda_v: %.4f\n", lambda_v); 210 | printf("learning_rate: %.5f\n", learning_rate); 211 | printf("alpha_smooth: %.5f\n", alpha_smooth); 212 | printf("random seed: %d\n", (int)random_seed); 213 | printf("save lag: %d\n", save_lag); 214 | printf("max iter: %d\n", max_iter); 215 | printf("number of factors: %d\n", num_factors); 216 | 217 | if (mult_path != NULL) { 218 | if (!file_exists(item_path)) { 219 | printf("mult file %s doesn't exist! quit ...\n", mult_path); 220 | exit(-1); 221 | } 222 | printf("mult file: %s\n", mult_path); 223 | 224 | if (theta_init_path == NULL) { 225 | printf("topic proportions file must be provided ...\n"); 226 | exit(-1); 227 | } 228 | if (!file_exists(theta_init_path)) { 229 | printf("topic proportions file %s doesn't exist! quit ...\n", theta_init_path); 230 | exit(-1); 231 | } 232 | printf("topic proportions file: %s\n", theta_init_path); 233 | 234 | if (beta_init_path == NULL) { 235 | printf("topic distributions file must be provided ...\n"); 236 | exit(-1); 237 | } 238 | if (!file_exists(beta_init_path)) { 239 | printf("topic distributions file %s doesn't exist! quit ...\n", beta_init_path); 240 | exit(-1); 241 | } 242 | printf("topic distributions file: %s\n", beta_init_path); 243 | if (theta_opt) printf("theta optimization: True\n"); 244 | else printf("theta optimization: false\n"); 245 | } 246 | else if (theta_opt) { 247 | printf("theta optimization: false"); 248 | printf("(theta_opt has no effect, back to default value: false)\n"); 249 | theta_opt = 0; 250 | } 251 | 252 | printf("\n"); 253 | 254 | /// save the settings 255 | int ctr_run = 1; 256 | if (mult_path == NULL) ctr_run = 0; 257 | ctr_hyperparameter ctr_param; 258 | ctr_param.set(a, b, lambda_u, lambda_v, learning_rate, alpha_smooth, 259 | random_seed, max_iter, save_lag, theta_opt, ctr_run, lda_regression); 260 | sprintf(filename, "%s/settings.txt", directory); 261 | ctr_param.save(filename); 262 | 263 | /// init random numbe generator 264 | RANDOM_NUMBER = new_random_number_generator(random_seed); 265 | 266 | // read users 267 | printf("reading user matrix from %s ...\n", user_path); 268 | c_data* users = new c_data(); 269 | users->read_data(user_path); 270 | int num_users = (int)users->m_vec_data.size(); 271 | 272 | // read users confidence 273 | printf("reading user confidence matrix from %s ...\n", user_a_path); 274 | c_double_data* users_a = new c_double_data(); 275 | users_a->read_data(user_a_path); 276 | 277 | // read items 278 | printf("reading item matrix from %s ...\n", item_path); 279 | c_data* items = new c_data(); 280 | items->read_data(item_path); 281 | int num_items = (int)items->m_vec_data.size(); 282 | 283 | // read items confidence 284 | printf("reading item confidence matrix from %s ...\n", item_a_path); 285 | c_double_data* items_a = new c_double_data(); 286 | items_a->read_data(item_a_path); 287 | 288 | // create model instance 289 | c_ctr* ctr = new c_ctr(); 290 | ctr->set_model_parameters(num_factors, num_users, num_items); 291 | 292 | c_corpus* c = NULL; 293 | if (mult_path != NULL) { 294 | // read word data 295 | c = new c_corpus(); 296 | c->read_data(mult_path); 297 | ctr->read_init_information(theta_init_path, beta_init_path, c, alpha_smooth); 298 | } 299 | 300 | if (learning_rate <= 0) { 301 | ctr->learn_map_estimate(users, items, users_a, items_a, c, &ctr_param, directory); 302 | } else { 303 | ctr->stochastic_learn_map_estimate(users, items, users_a, items_a, c, &ctr_param, directory); 304 | } 305 | 306 | free_random_number_generator(RANDOM_NUMBER); 307 | if (c != NULL) delete c; 308 | 309 | delete ctr; 310 | delete users; 311 | delete items; 312 | delete users_a; 313 | delete items_a; 314 | return 0; 315 | } 316 | -------------------------------------------------------------------------------- /C_code_TCTR/opt.cpp: -------------------------------------------------------------------------------- 1 | #include "opt.h" 2 | #include "utils.h" 3 | #include 4 | 5 | // projection gradient algorithm 6 | void optimize_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, gsl_vector* opt_x) { 7 | size_t size = opt_x->size; 8 | gsl_vector* g = gsl_vector_alloc(size); 9 | gsl_vector* x_bar = gsl_vector_alloc(size); 10 | gsl_vector* opt_x_old = gsl_vector_alloc(size); 11 | gsl_vector_memcpy(opt_x_old, opt_x); // save the old value 12 | double f_old = f_simplex(gamma, v, lambda, opt_x); 13 | //printf("f_old: %0.10f -> ", f_old); 14 | 15 | df_simplex(gamma, v, lambda, opt_x, g); 16 | double ab_sum = gsl_blas_dasum(g); 17 | if (ab_sum > 1.0) gsl_vector_scale(g, 1.0/ab_sum); // rescale the gradient 18 | 19 | gsl_blas_daxpy(-1, g, opt_x); 20 | simplex_projection(opt_x, x_bar); 21 | gsl_vector_sub(x_bar, opt_x_old); 22 | double r = 0; 23 | gsl_blas_ddot(g, x_bar, &r); 24 | r *= 0.5; 25 | 26 | double beta = 0.5; 27 | double f_new; 28 | double t = beta; 29 | int iter = 0; 30 | while(++iter < 100) { 31 | gsl_vector_memcpy(opt_x, opt_x_old); 32 | gsl_blas_daxpy(t, x_bar, opt_x); 33 | 34 | f_new = f_simplex(gamma, v, lambda, opt_x); 35 | if (f_new > f_old + r * t) t = t * beta; 36 | else break; 37 | } 38 | //printf("f_new %0.10f\n", f_new); 39 | 40 | if (!is_feasible(opt_x)) printf("sth is wrong, not feasible. you've got to check it ...\n"); 41 | 42 | gsl_vector_free(g); 43 | gsl_vector_free(opt_x_old); 44 | gsl_vector_free(x_bar); 45 | } 46 | 47 | double f_simplex(const gsl_vector* gamma, const gsl_vector* v, 48 | double lambda, const gsl_vector* opt_x) { 49 | double f = 0.0, val; 50 | 51 | gsl_vector* y = gsl_vector_alloc(opt_x->size); 52 | gsl_vector_memcpy(y, opt_x); 53 | vct_log(y); 54 | 55 | gsl_blas_ddot(y, gamma, &f); 56 | 57 | gsl_vector_memcpy(y, v); 58 | gsl_vector_sub(y, opt_x); 59 | gsl_blas_ddot(y, y, &val); 60 | f -= 0.5 * lambda * val; 61 | gsl_vector_free(y); 62 | 63 | return -f; 64 | } 65 | 66 | void df_simplex(const gsl_vector* gamma, const gsl_vector* v, 67 | double lambda, const gsl_vector* opt_x, 68 | gsl_vector* g) { 69 | gsl_vector_memcpy(g, opt_x); 70 | gsl_vector_sub(g, v); 71 | gsl_vector_scale(g, -lambda); 72 | 73 | gsl_vector* y = gsl_vector_alloc(opt_x->size); 74 | gsl_vector_memcpy(y, gamma); 75 | gsl_vector_div(y, opt_x); 76 | gsl_vector_add(g, y); 77 | gsl_vector_scale(g, -1.0); 78 | gsl_vector_free(y); 79 | } 80 | 81 | bool is_feasible(const gsl_vector* x) { 82 | double val; 83 | double sum = 0; 84 | for (size_t i = 0; i < x->size-1; i ++) { 85 | val = vget(x, i); 86 | if (val < 0 || val >1) return false; 87 | sum += val; 88 | if (sum > 1) return false; 89 | } 90 | return true; 91 | } 92 | 93 | // project x on to simplex (using // http://www.cs.berkeley.edu/~jduchi/projects/DuchiShSiCh08.pdf) 94 | void simplex_projection(const gsl_vector* x, gsl_vector* x_proj, double z) { 95 | gsl_vector_memcpy(x_proj, x); 96 | gsl_sort_vector(x_proj); 97 | double cumsum = -z, u; 98 | int j = 0; 99 | int i; // this has to be int, not size_t 100 | for (i = (int)x->size-1; i >= 0; i --) { 101 | u = vget(x_proj, i); 102 | cumsum += u; 103 | if (u > cumsum/(j+1)) j++; 104 | else break; 105 | } 106 | double theta = cumsum/j; 107 | for (i = 0; i < (int)x->size; i ++) { 108 | u = vget(x, i)-theta; 109 | if (u <= 0) u = 0.0; 110 | vset(x_proj, i, u); 111 | } 112 | vnormalize(x_proj); // fix the normaliztion issue due to numerical errors 113 | } 114 | -------------------------------------------------------------------------------- /C_code_TCTR/opt.h: -------------------------------------------------------------------------------- 1 | #ifndef OPT_H 2 | #define OPT_H 3 | #include 4 | 5 | void optimize_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, gsl_vector* opt_x); 6 | double f_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, const gsl_vector* opt_x); 7 | void df_simplex(const gsl_vector* gamma, const gsl_vector* v, double lambda, const gsl_vector* opt_x, gsl_vector* g); 8 | bool is_feasible(const gsl_vector* x); 9 | void simplex_projection(const gsl_vector* x, gsl_vector* x_proj, double z=1.0); 10 | 11 | #endif // OPT_H 12 | 13 | -------------------------------------------------------------------------------- /C_code_TCTR/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | extern gsl_rng * RANDOM_NUMBER; 4 | 5 | /* 6 | * compare two ints 7 | * */ 8 | 9 | int compare (const void * a, const void * b) { 10 | return ( *(int*)a - *(int*)b ); 11 | } 12 | 13 | /* 14 | * given log(a) and log(b), return log(a+b) 15 | * 16 | */ 17 | 18 | double log_sum(double log_a, double log_b) { 19 | double v; 20 | 21 | if (log_a == -1) return(log_b); 22 | 23 | if (log_a < log_b) { 24 | v = log_b+log(1 + exp(log_a-log_b)); 25 | } 26 | else { 27 | v = log_a+log(1 + exp(log_b-log_a)); 28 | } 29 | return(v); 30 | } 31 | 32 | /* 33 | void vinc(gsl_vector* v, int i, double x) 34 | { 35 | vset(v, i, vget(v, i) + x); 36 | } 37 | */ 38 | 39 | void minc(gsl_matrix* m, int i, int j, double x) { 40 | mset(m, i, j, mget(m, i, j) + x); 41 | } 42 | 43 | /* 44 | * compute the row sums of a matrix 45 | * 46 | */ 47 | 48 | void row_sum(const gsl_matrix* m, gsl_vector* val) { 49 | size_t i, j; 50 | gsl_vector_set_zero(val); 51 | 52 | for (i = 0; i < m->size1; i++) 53 | for (j = 0; j < m->size2; j++) 54 | vinc(val, i, mget(m, i, j)); 55 | } 56 | 57 | /* 58 | * compute the column sums of a matrix 59 | * 60 | */ 61 | 62 | void col_sum(const gsl_matrix* m, gsl_vector* val) { 63 | size_t i, j; 64 | gsl_vector_set_zero(val); 65 | 66 | for (i = 0; i < m->size1; i++) 67 | for (j = 0; j < m->size2; j++) 68 | vinc(val, j, mget(m, i, j)); 69 | } 70 | 71 | 72 | /* 73 | * print a vector to standard out 74 | * 75 | */ 76 | 77 | void vct_fprintf(FILE * file, const gsl_vector * v) { 78 | size_t i; 79 | for (i = 0; i < v->size; i++) 80 | fprintf(file, "%10.15e ", vget(v, i)); 81 | fprintf(file, "\n"); 82 | } 83 | 84 | 85 | /* 86 | * print a matrix to standard out 87 | * 88 | */ 89 | 90 | void mtx_fprintf(FILE * file, const gsl_matrix * m) { 91 | size_t i, j; 92 | for (i = 0; i < m->size1; i++) { 93 | for (j = 0; j < m->size2; j++) 94 | fprintf(file, "%10.15e ", mget(m, i, j)); 95 | fprintf(file, "\n"); 96 | } 97 | } 98 | 99 | void mtx_fscanf(FILE* file, gsl_matrix* m) { 100 | size_t i, j; 101 | double x; 102 | for (i = 0; i < m->size1; i++) { 103 | for (j = 0; j < m->size2; j++) { 104 | fscanf(file, "%lf", &x); 105 | mset(m, i, j, x); 106 | } 107 | } 108 | } 109 | 110 | /* 111 | * matrix vector solve using blas 112 | * 113 | */ 114 | 115 | void matrix_vector_solve(const gsl_matrix* m, const gsl_vector* b, gsl_vector* v) { 116 | gsl_matrix *lu; 117 | gsl_permutation* p; 118 | int signum; 119 | 120 | p = gsl_permutation_alloc(m->size1); 121 | lu = gsl_matrix_alloc(m->size1, m->size2); 122 | 123 | gsl_matrix_memcpy(lu, m); 124 | gsl_linalg_LU_decomp(lu, p, &signum); 125 | gsl_linalg_LU_solve(lu, p, b, v); 126 | 127 | gsl_matrix_free(lu); 128 | gsl_permutation_free(p); 129 | } 130 | 131 | /* 132 | * matrix inversion using blas 133 | * 134 | */ 135 | 136 | void matrix_inverse(const gsl_matrix* m, gsl_matrix* inverse) { 137 | gsl_matrix *lu; 138 | gsl_permutation* p; 139 | int signum; 140 | 141 | p = gsl_permutation_alloc(m->size1); 142 | lu = gsl_matrix_alloc(m->size1, m->size2); 143 | 144 | gsl_matrix_memcpy(lu, m); 145 | gsl_linalg_LU_decomp(lu, p, &signum); 146 | gsl_linalg_LU_invert(lu, p, inverse); 147 | 148 | gsl_matrix_free(lu); 149 | gsl_permutation_free(p); 150 | } 151 | 152 | /* 153 | * log determinant using blas 154 | * 155 | */ 156 | 157 | double log_det(const gsl_matrix* m) { 158 | gsl_matrix* lu; 159 | gsl_permutation* p; 160 | double result; 161 | int signum; 162 | 163 | p = gsl_permutation_alloc(m->size1); 164 | lu = gsl_matrix_alloc(m->size1, m->size2); 165 | 166 | gsl_matrix_memcpy(lu, m); 167 | gsl_linalg_LU_decomp(lu, p, &signum); 168 | result = gsl_linalg_LU_lndet(lu); 169 | 170 | gsl_matrix_free(lu); 171 | gsl_permutation_free(p); 172 | 173 | return(result); 174 | } 175 | 176 | 177 | /* 178 | * eigenvalues of a symmetric matrix using blas 179 | * 180 | */ 181 | 182 | void sym_eigen(gsl_matrix* m, gsl_vector* vals, gsl_matrix* vects) { 183 | gsl_eigen_symmv_workspace* wk; 184 | gsl_matrix* mcpy; 185 | int r; 186 | 187 | mcpy = gsl_matrix_alloc(m->size1, m->size2); 188 | wk = gsl_eigen_symmv_alloc(m->size1); 189 | gsl_matrix_memcpy(mcpy, m); 190 | r = gsl_eigen_symmv(mcpy, vals, vects, wk); 191 | gsl_eigen_symmv_free(wk); 192 | gsl_matrix_free(mcpy); 193 | } 194 | 195 | 196 | /* 197 | * sum of a vector 198 | * 199 | */ 200 | /* 201 | double sum(const gsl_vector* v) { 202 | double val = 0; 203 | int i, size = v->size; 204 | for (i = 0; i < size; i++) 205 | val += vget(v, i); 206 | return(val); 207 | } 208 | */ 209 | 210 | /* 211 | * apply a function to each element of a gsl vector. 212 | * 213 | */ 214 | void gsl_vector_apply(gsl_vector* x, double(*fun)(double)) { 215 | size_t i; 216 | for(i = 0; i < x->size; i ++) 217 | vset(x, i, fun(vget(x, i))); 218 | } 219 | 220 | 221 | /* 222 | * take log of each element for a vector 223 | * 224 | */ 225 | void vct_log(gsl_vector* v) { 226 | int i, size = v->size; 227 | for (i = 0; i < size; i++) 228 | vset(v, i, safe_log(vget(v, i))); 229 | } 230 | 231 | 232 | /* 233 | * take log of each element for a matrix 234 | * 235 | */ 236 | void mtx_log(gsl_matrix* x) { 237 | size_t i, j; 238 | for (i = 0; i < x->size1; i++) 239 | for (j = 0; j < x->size2; j++) 240 | mset(x, i, j, safe_log(mget(x, i, j))); 241 | } 242 | 243 | 244 | 245 | /* 246 | * l2 norm of a vector 247 | * 248 | */ 249 | 250 | double vnorm(const gsl_vector *v) { 251 | return gsl_blas_dnrm2(v); 252 | } 253 | 254 | 255 | /* 256 | * normalize a vector in log space 257 | * 258 | * x_i = log(a_i) 259 | * v = log(a_1 + ... + a_k) 260 | * x_i = x_i - v 261 | * 262 | */ 263 | 264 | double log_normalize(gsl_vector* x) { 265 | double v = vget(x, 0); 266 | size_t i; 267 | 268 | for (i = 1; i < x->size; i++) 269 | v = log_sum(v, vget(x, i)); 270 | 271 | for (i = 0; i < x->size; i++) 272 | vset(x, i, vget(x,i)-v); 273 | 274 | return v; 275 | } 276 | 277 | 278 | /* 279 | * normalize a positive vector 280 | * 281 | */ 282 | 283 | double vnormalize(gsl_vector* x) { 284 | double v = vsum(x); 285 | if (v > 0 || v < 0) 286 | gsl_vector_scale(x, 1/v); 287 | return v; 288 | } 289 | 290 | 291 | /* 292 | * exponentiate a vector 293 | * 294 | */ 295 | 296 | void vct_exp(gsl_vector* x) { 297 | for (size_t i = 0; i < x->size; i++) 298 | vset(x, i, exp(vget(x, i))); 299 | } 300 | 301 | /* 302 | * exponentiate a matrix 303 | * 304 | */ 305 | void mtx_exp(gsl_matrix* x) { 306 | size_t i, j; 307 | for (i = 0; i < x->size1; i++) 308 | for (j = 0; j < x->size2; j++) 309 | mset(x, i, j, exp(mget(x, i, j))); 310 | } 311 | 312 | double mahalanobis_distance(const gsl_matrix* m, 313 | const gsl_vector* u, 314 | const gsl_vector* v) { 315 | double val = 0; 316 | gsl_vector* x = gsl_vector_alloc(u->size); 317 | gsl_vector_memcpy(x, u); 318 | gsl_vector_sub(x, v); 319 | val = mahalanobis_prod(m, x, x); 320 | gsl_vector_free(x); 321 | return val; 322 | } 323 | 324 | // blasified 325 | double mahalanobis_prod(const gsl_matrix* m, 326 | const gsl_vector* u, 327 | const gsl_vector* v) { 328 | gsl_vector* x = gsl_vector_alloc(u->size); 329 | gsl_blas_dgemv(CblasNoTrans, 1.0, m, v, 0.0, x); 330 | double val = 0; 331 | gsl_blas_ddot(u, x, &val); 332 | gsl_vector_free(x); 333 | return val; 334 | } 335 | 336 | double matrix_dot_prod(const gsl_matrix* m1, const gsl_matrix* m2) { 337 | double val = 0, result; 338 | for (size_t i = 0; i < m1->size1; i ++) { 339 | gsl_vector_const_view v1 = gsl_matrix_const_row(m1, i); 340 | gsl_vector_const_view v2 = gsl_matrix_const_row(m2, i); 341 | gsl_blas_ddot(&v1.vector, &v2.vector, &result); 342 | val += result; 343 | } 344 | return val; 345 | } 346 | 347 | 348 | /** 349 | * 350 | * check if file exisits 351 | */ 352 | bool file_exists(const char * filename) { 353 | if ( 0 == access(filename, R_OK)) 354 | return true; 355 | return false; 356 | } 357 | 358 | 359 | 360 | /* 361 | * check if a directory exists 362 | * 363 | * !!! shouldn't be here 364 | */ 365 | 366 | int dir_exists(const char *dname) { 367 | struct stat st; 368 | int ret; 369 | 370 | if (stat(dname,&st) != 0) { 371 | return 0; 372 | } 373 | 374 | ret = S_ISDIR(st.st_mode); 375 | 376 | if(!ret) { 377 | errno = ENOTDIR; 378 | } 379 | 380 | return ret; 381 | } 382 | 383 | void make_directory(const char* name) { 384 | mkdir(name, S_IRUSR|S_IWUSR|S_IXUSR); 385 | } 386 | 387 | 388 | /* 389 | * new random number generator 390 | * 391 | */ 392 | gsl_rng * new_random_number_generator(long seed) { 393 | gsl_rng * random_number_generator = gsl_rng_alloc(gsl_rng_taus); 394 | gsl_rng_set(random_number_generator, (long) seed); // init the seed 395 | 396 | return random_number_generator; 397 | } 398 | 399 | /* 400 | * free random number generator 401 | * */ 402 | 403 | void free_random_number_generator(gsl_rng * random_number_generator) { 404 | gsl_rng_free(random_number_generator); 405 | } 406 | 407 | void choose_k_from_n(int k, int n, int* result, int* src) { 408 | gsl_ran_choose (RANDOM_NUMBER, (void *) result, k, (void *) src, n, sizeof(int)); 409 | } 410 | 411 | void sample_k_from_n(int k, int n, int* result, int* src) { 412 | gsl_ran_sample (RANDOM_NUMBER, (void *) result, k, (void *) src, n, sizeof(int)); 413 | } 414 | 415 | double digamma(double x) { 416 | return gsl_sf_psi(x); 417 | } 418 | 419 | unsigned int rmultinomial(const gsl_vector* v) { 420 | size_t i; 421 | 422 | double sum = vsum(v); 423 | 424 | double u = runiform() * sum; 425 | double cum_sum = 0.0; 426 | for (i = 0; i < v->size; i ++) { 427 | cum_sum += vget(v, i); 428 | if (u < cum_sum) break; 429 | } 430 | return i; 431 | } 432 | 433 | double rgamma(double a, double b) { 434 | return gsl_ran_gamma_mt(RANDOM_NUMBER, a, b); 435 | } 436 | 437 | double rbeta(double a, double b) { 438 | return gsl_ran_beta(RANDOM_NUMBER, a, b); 439 | } 440 | 441 | unsigned int rbernoulli(double p) { 442 | return gsl_ran_bernoulli(RANDOM_NUMBER, p); 443 | } 444 | 445 | double runiform() { 446 | return gsl_rng_uniform_pos(RANDOM_NUMBER); 447 | } 448 | 449 | void rshuffle(void* base, size_t n, size_t size) { 450 | gsl_ran_shuffle(RANDOM_NUMBER, base, n, size); 451 | } 452 | 453 | unsigned long int runiform_int(unsigned long int n) { 454 | return gsl_rng_uniform_int(RANDOM_NUMBER, n); 455 | } 456 | 457 | -------------------------------------------------------------------------------- /C_code_TCTR/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef UTILS_H 2 | #define UTILS_H 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | 25 | #define outlog(format, args...) \ 26 | fprintf(stderr, format, args); \ 27 | fprintf(stderr, "\n"); 28 | 29 | int compare (const void * a, const void * b); 30 | 31 | inline double safe_log(double x) { 32 | if (x <= 0) 33 | return(-10000); 34 | else 35 | return(log(x)); 36 | } 37 | double log_sum(double, double); 38 | 39 | inline double vget(const gsl_vector* v, int i) { return(gsl_vector_get(v, i)); } 40 | 41 | inline void vset(gsl_vector* v, int i, double x) { gsl_vector_set(v, i, x); } 42 | 43 | // Increment a vector element by a double. 44 | inline void vinc(gsl_vector* v, int i, double x) { 45 | vset(v, i, vget(v, i) + x); 46 | } 47 | 48 | inline double mget(const gsl_matrix* m, int i, int j) 49 | { return(gsl_matrix_get(m, i, j)); } 50 | 51 | inline void mset(gsl_matrix* m, int i, int j, double x) 52 | { gsl_matrix_set(m, i, j, x); } 53 | 54 | // Increment a matrix element by a double. 55 | void minc(gsl_matrix*, int, int, double); 56 | 57 | void col_sum(const gsl_matrix*, gsl_vector*); 58 | void row_sum(const gsl_matrix*, gsl_vector*); 59 | 60 | void vct_fprintf(FILE* file, const gsl_vector* v); 61 | void mtx_fprintf(FILE* file, const gsl_matrix* m); 62 | void mtx_fscanf(FILE* file, gsl_matrix* m); 63 | 64 | inline bool check_sym(const gsl_matrix *m) { 65 | for (size_t i = 0; i < m->size1-1; i ++) 66 | for (size_t j=i; j < m->size2; j ++) 67 | if (mget(m, i, j) != mget(m, j, i)) { 68 | printf("not sym\n"); 69 | return false; 70 | } 71 | return true; 72 | } 73 | 74 | double log_det(const gsl_matrix*); 75 | 76 | void matrix_inverse(const gsl_matrix*, gsl_matrix*); 77 | void matrix_vector_solve(const gsl_matrix* m, const gsl_vector* b, gsl_vector* v); 78 | 79 | void sym_eigen(gsl_matrix*, gsl_vector*, gsl_matrix*); 80 | 81 | inline double vsum(const gsl_vector* v) { 82 | double val = 0; 83 | int i, size = v->size; 84 | for (i = 0; i < size; i++) 85 | val += vget(v, i); 86 | return(val); 87 | } 88 | 89 | double vnorm(const gsl_vector * v); 90 | 91 | void gsl_vector_apply(gsl_vector* x, double(*fun)(double)); 92 | void vct_log(gsl_vector* v); 93 | void mtx_log(gsl_matrix* x); 94 | void vct_exp(gsl_vector* x); 95 | void mtx_exp(gsl_matrix* x); 96 | 97 | double mahalanobis_distance(const gsl_matrix * m, const gsl_vector* u, const gsl_vector* v); 98 | double mahalanobis_prod(const gsl_matrix * m, const gsl_vector* u, const gsl_vector* v); 99 | double matrix_dot_prod(const gsl_matrix * m1, const gsl_matrix* m2); 100 | 101 | void choose_k_from_n(int k, int n, int* result, int* src); 102 | void sample_k_from_n(int k, int n, int* result, int* src); 103 | 104 | double log_normalize(gsl_vector* x); 105 | double vnormalize(gsl_vector* x); 106 | 107 | int dir_exists(const char *dname); 108 | bool file_exists(const char * filename); 109 | void make_directory(const char* name); 110 | 111 | double digamma(double x); 112 | unsigned int rmultinomial(const gsl_vector* v); 113 | double rgamma(double a, double b); 114 | double rbeta(double a, double b); 115 | unsigned int rbernoulli(double p); 116 | double runiform(); 117 | void rshuffle (void* base, size_t n, size_t size); 118 | unsigned long int runiform_int(unsigned long int n); 119 | 120 | // new and free random number generator 121 | gsl_rng* new_random_number_generator(long seed); 122 | void free_random_number_generator(gsl_rng * random_number_generator); 123 | 124 | #endif 125 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Temporal Collaborative Topic Regression (T-CTR) 2 | Implementation for the paper [Time-aware Collaborative Topic Regression: Towards Higher Relevance in Textual Item Recommendation](http://ceur-ws.org/Vol-2132/paper2.pdf). 3 | Extends Collaborative Topic Modelling [CTR Recommender System](https://github.com/blei-lab/ctr) 4 | used in the work of [Wang and Blei](http://www.cs.princeton.edu/~chongw/papers/WangBlei2011.pdf) 5 | to consider the temporal aspect in recommendation. 6 | This project generates a recommender system model. To evaluate the generated model, 7 | use the [Recommender Evaluator System](https://github.com/anasalzogbi/Recommender_Evaluator), which is responsible for splitting the labeled data 8 | and computing the evaluation metrics. 9 | 10 | ### Rquirements: 11 | - python 3.5 12 | - numpy 13 | ### Dataset: 14 | This work uses dataset collected from citeulike, you can downlowd it from [here](http://dbis.informatik.uni-freiburg.de/forschung/projekte/SciPRec/) 15 | ### Please cite using the following BibTex entry: 16 | ``` 17 | @inproceedings{DBLP:conf/sigir/Alzogbi18, 18 | author = {Anas Alzogbi}, 19 | title = {Time-aware Collaborative Topic Regression: Towards Higher Relevance 20 | in Textual Item Recommendation}, 21 | booktitle = {Proceedings of the 3rd Joint Workshop on Bibliometric-enhanced Information 22 | Retrieval and Natural Language Processing for Digital Libraries {(BIRNDL} 23 | 2018) co-located with the 41st International {ACM} {SIGIR} Conference 24 | on Research and Development in Information Retrieval {(SIGIR} 2018), 25 | Ann Arbor, USA, July 12, 2018.}, 26 | pages = {10--23}, 27 | year = {2018}, 28 | crossref = {DBLP:conf/sigir/2018birndl}, 29 | url = {http://ceur-ws.org/Vol-2132/paper2.pdf}, 30 | timestamp = {Mon, 09 Jul 2018 18:23:12 +0200}, 31 | biburl = {https://dblp.org/rec/bib/conf/sigir/Alzogbi18}, 32 | bibsource = {dblp computer science bibliography, https://dblp.org} 33 | } 34 | ``` 35 | ### Directory structure: 36 | The following directory tree illustrates how the structure of data directory will be: 37 | |__ `[USER_RATINGS_FILE.dat]` 38 | |__ `[SPLIT_DIRECTORY]` 39 | ......|__ fold`[1-5]` 40 | ......|......|_ train-fold_`[1-5]`-items.dat 41 | ......|......|_ test-fold_`[1-5]`-items.dat 42 | ......|......|_ train-fold_`[1-5]`-users.dat 43 | ......|......|_ test-fold_`[1-5]`-users.dat 44 | ......|__ `[EXPERIMENT_DIRECTORY]` 45 | .............|_ `[EXPERIMENT_NAME]`\_eval_results.txt 46 | .............|_ results-matrix.npy 47 | .............|_ fold`[1-5]` 48 | .............|......|_ final-U.dat 49 | .............|......|_ final-V.dat 50 | .............|......|_ score.npy 51 | .............|......|_ results-users.dat 52 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anasalzogbi/T-CTR/25a1d68cc99e4f922e9d155ca99ff9c53effcee8/__init__.py -------------------------------------------------------------------------------- /lib/Probabilistic_Matrix_Factorization.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | class PMF(object): 4 | def __init__(self, num_user, num_item, num_feat=150, epsilon=1, reg_param=0.1, momentum=0.8, maxepoch=20, num_batches=2, batch_size=100): 5 | self.num_user = num_user 6 | self.num_item = num_item 7 | self.num_feat = num_feat # Number of latent features, 8 | self.epsilon = epsilon # learning rate, 9 | self.reg_param = reg_param # L2 regularization, 10 | self.momentum = momentum # momentum of the gradient, 11 | self.maxepoch = maxepoch # Number of epoch before stop, 12 | self.num_batches = num_batches # Number of batches in each epoch (for SGD optimization), 13 | self.batch_size = batch_size # Number of training samples used in each batches (for SGD optimization) 14 | 15 | self.w_item = None # Item feature vectors 16 | self.w_user = None # User feature vectors 17 | 18 | self.rmse_train = [] 19 | self.rmse_test = [] 20 | 21 | # ***Fit the model with train_tuple and evaluate RMSE on both train and test data. ***********# 22 | # ***************** train_vec=TrainData, test_vec=TestData*************# 23 | # train_vec: list of training data arrays for timestamps 24 | def fit(self, train_vec_time_series, T0): 25 | 26 | 27 | # initialize 28 | self.epoch = 0 29 | # The items' latent factors are shared among all time-slots 30 | self.w_item = 0.1 * np.random.randn(self.num_item, self.num_feat) 31 | 32 | # Initialize the usres' latent factors for each time slot. 33 | #self.w_user = [0.1 * np.random.randn(self.num_user, self.num_feat) for _ in range(T0)] 34 | self.w_user = 0.1 * np.random.randn(self.num_user, T0, self.num_feat) 35 | 36 | 37 | self.w_Item_inc = np.zeros((self.num_item, self.num_feat)) 38 | self.w_User_inc = np.zeros((self.num_user, T0, self.num_feat)) 39 | 40 | while self.epoch < self.maxepoch: 41 | self.epoch += 1 42 | # Iterate over all time slots 43 | for time_slot in range(T0): 44 | 45 | # Get the ratings of time (time_slot) 46 | train_vec = train_vec_time_series[train_vec_time_series.idx==time_slot][['user','paper']].values 47 | 48 | if len(train_vec) > 0: 49 | # Count the number of ratings 50 | pairs_train = train_vec.shape[0] 51 | 52 | # Shuffle training truples 53 | shuffled_order = np.arange(train_vec.shape[0]) 54 | np.random.shuffle(shuffled_order) 55 | if pairs_train < self.batch_size: 56 | batch_s = pairs_train 57 | else: 58 | batch_s = self.batch_size 59 | if pairs_train//batch_s < self.num_batches: 60 | batch_num = pairs_train//batch_s 61 | else: 62 | batch_num = self.num_batches 63 | print("time slot: {:d}, #ratings: {}, batch_size: {}, batch_num: {}".format(time_slot, train_vec.shape[0], batch_s, batch_num)) 64 | # Batch update 65 | for batch in range(batch_num): 66 | print("epoch: {:d}, batch: {:d} ".format(self.epoch, batch+1)) 67 | 68 | test = np.arange(batch_s * batch, batch_s * (batch + 1)) 69 | batch_idx = np.mod(test, shuffled_order.shape[0]) 70 | 71 | batch_UserID = np.array(train_vec[shuffled_order[batch_idx], 0], dtype='int32') 72 | batch_ItemID = np.array(train_vec[shuffled_order[batch_idx], 1], dtype='int32') 73 | 74 | # Compute Objective Function 75 | try: 76 | pred_out = np.sum(np.multiply(self.w_user[batch_UserID,time_slot, :], self.w_item[batch_ItemID, :]), axis=1) 77 | except Warning: 78 | print('RuntimeWarning was rased in multiply, batch is skipped') 79 | continue 80 | #rawErr = pred_out - train_vec[shuffled_order[batch_idx], 2] 81 | rawErr = pred_out - len(pred_out)*[1] 82 | 83 | # Compute gradients 84 | Ix_User = 2 * np.multiply(rawErr[:, np.newaxis], self.w_item[batch_ItemID, :]) + self.reg_param * self.w_user[batch_UserID, time_slot, :] 85 | Ix_Item = 2 * np.multiply(rawErr[:, np.newaxis], self.w_user[batch_UserID,time_slot, :]) + self.reg_param * (self.w_item[batch_ItemID, :]) 86 | 87 | dw_Item = np.zeros((self.num_item, self.num_feat)) 88 | dw_User = np.zeros((self.num_user, self.num_feat)) 89 | 90 | # loop to aggreate the gradients of the same element 91 | for i in range(batch_s): 92 | dw_Item[batch_ItemID[i], :] += Ix_Item[i, :] 93 | dw_User[batch_UserID[i], :] += Ix_User[i, :] 94 | 95 | # Update with momentum 96 | self.w_Item_inc = self.momentum * self.w_Item_inc + self.epsilon * dw_Item / batch_s 97 | self.w_User_inc[:,time_slot,:] = self.momentum * self.w_User_inc[:,time_slot,:] + self.epsilon * dw_User / batch_s 98 | 99 | self.w_item = self.w_item - self.w_Item_inc 100 | self.w_user[:,time_slot, :] = self.w_user[:,time_slot, :] - self.w_User_inc[:,time_slot,:] 101 | 102 | # Compute Objective Function after 103 | if batch == batch_num - 1: 104 | pred_out = np.sum(np.multiply(self.w_user[train_vec[:, 0],time_slot, :], self.w_item[train_vec[:, 1], :]), axis=1) 105 | #rawErr = pred_out - train_vec[:, 2] 106 | rawErr = pred_out - len(pred_out) * [1] 107 | 108 | obj = np.linalg.norm(rawErr) ** 2 + 0.5 * self.reg_param * (np.linalg.norm(self.w_user[:, time_slot]) ** 2 + np.linalg.norm(self.w_item) ** 2) 109 | 110 | self.rmse_train.append(np.sqrt(obj / pairs_train)) 111 | print('Training RMSE: {:4.3f}'.format(self.rmse_train[-1])) 112 | """ 113 | # Compute validation error 114 | if batch == batch_num - 1: 115 | pred_out = np.sum(np.multiply(self.w_user[np.array(train_vec[:, 0], dtype='int32'),time_slot, :], 116 | self.w_item[np.array(test_vec[:, 1], dtype='int32'), :]), 117 | axis=1) 118 | #rawErr = pred_out - test_vec[:, 2] 119 | rawErr = pred_out - len(pred_out) * [1] 120 | 121 | self.rmse_test.append(np.linalg.norm(rawErr) / np.sqrt(pairs_test)) 122 | 123 | # Print info 124 | if batch == batch_num- 1: 125 | print('Training RMSE: {:4.3f}, Test RMSE {:4.3f}'.format(self.rmse_train[-1], self.rmse_test[-1])) 126 | """ 127 | return self.w_user,self.w_item -------------------------------------------------------------------------------- /lib/Rocchio_CTR_JS_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_data/terms_keywords_based 3 | #for folder in 2k_10_P3_reduced 2k_10_P5_reduced 2k_10_P10_reduced 2k_20_P3_reduced 2k_20_P5_reduced 2k_20_P10_reduced 2k_30_P3_reduced 2k_30_P5_reduced 2k_30_P10_reduced 4 | #for folder in 2k_40_P3_reduced 2k_40_P5_reduced 2k_50_P3_reduced 2k_50_P5_reduced 2k_100_P3_reduced 2k_100_P5_reduced 5 | for folder in 2k_30_P3_reduced 6 | do 7 | line=$(head -n 1 ${rootpath}/${folder}/stats.txt) 8 | IFS='(' read -a v <<< "${line}" 9 | v=${v[1]//)/} 10 | v=${v// /} 11 | IFS=',' read -a v <<< "${v}" 12 | users=${v[0]} 13 | items=${v[1]} 14 | for k in 200 15 | do 16 | screen -S Rocchio_CTR_papers_users_Normalized_JS_${folder}_k_${k} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 17 | python3 /home/alzoghba/IFUP2018/SciPRec_CTR/lib/rocchio_based_recommender.py \ 18 | -u ${rootpath}/${folder}/in-matrix-item_folds \ 19 | -ps ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-1/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-2/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-3/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-4/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-5/final-V.dat \ 20 | -s jenson_shannon \ 21 | -e CTR_Rocchio_papers_users_normalized_JS_k_${k} \ 22 | -splt ${rootpath}/${folder}/in-matrix-item_folds \ 23 | -n ${users} -m ${items} -l 500 ; exec sh" 24 | done 25 | done 26 | -------------------------------------------------------------------------------- /lib/Rocchio_CTR_LDA-profiles_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_data/terms_keywords_based 3 | #for folder in 2k_10_P3_reduced 2k_10_P5_reduced 2k_10_P10_reduced 2k_20_P3_reduced 2k_20_P5_reduced 2k_20_P10_reduced 2k_30_P3_reduced 2k_30_P5_reduced 2k_30_P10_reduced 2k_40_P3_reduced 2k_40_P5_reduced 4 | #for folder in 2k_40_P5_reduced 2k_40_P10_reduced 2k_50_P3_reduced 2k_50_P5_reduced 2k_100_P3_reduced 2k_100_P5_reduced 5 | for folder in 2k_30_P3_reduced 6 | do 7 | line=$(head -n 1 ${rootpath}/${folder}/stats.txt) 8 | IFS='(' read -a v <<< "${line}" 9 | v=${v[1]//)/} 10 | v=${v// /} 11 | IFS=',' read -a v <<< "${v}" 12 | users=${v[0]} 13 | items=${v[1]} 14 | echo $users 15 | echo $items 16 | for k in 200 17 | do 18 | screen -S Rocchio_LDAPROFILE_Cosine_${folder}_k_${k} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 19 | python3 /home/alzoghba/IFUP2018/SciPRec_CTR/lib/rocchio_based_recommender.py \ 20 | -u ${rootpath}/${folder}/in-matrix-item_folds \ 21 | -p ${rootpath}/${folder}/lda_topics/theta_${k}.dat \ 22 | -ps ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-1/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-2/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-3/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-4/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-5/final-V.dat \ 23 | -s cosine \ 24 | -e CTR_Rocchio_LDAPROFILE_Cosine_k_${k} \ 25 | -splt ${rootpath}/${folder}/in-matrix-item_folds \ 26 | -n ${users} -m ${items} -ldau -l 500 ;" 27 | done 28 | done -------------------------------------------------------------------------------- /lib/Rocchio_CTR_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_data/terms_keywords_based 3 | #for folder in 2k_10_P3_reduced 2k_10_P5_reduced 2k_10_P10_reduced 2k_20_P3_reduced 2k_20_P5_reduced 2k_20_P10_reduced 2k_30_P3_reduced 2k_30_P5_reduced 2k_30_P10_reduced 4 | #for folder in 2k_40_P3_reduced 2k_40_P5_reduced 2k_50_P3_reduced 2k_50_P5_reduced 2k_100_P3_reduced 2k_100_P5_reduced 5 | for folder in 2k_30_P3_reduced 6 | do 7 | line=$(head -n 1 ${rootpath}/${folder}/stats.txt) 8 | IFS='(' read -a v <<< "${line}" 9 | v=${v[1]//)/} 10 | v=${v// /} 11 | IFS=',' read -a v <<< "${v}" 12 | users=${v[0]} 13 | items=${v[1]} 14 | for k in 200 15 | do 16 | screen -S Rocchio_CTR_notpapers_notusers_Normalized_cosine_${folder}_k_${k} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 17 | python3 /home/alzoghba/IFUP2018/SciPRec_CTR/lib/rocchio_based_recommender.py \ 18 | -u ${rootpath}/${folder}/in-matrix-item_folds \ 19 | -ps ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-1/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-2/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-3/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-4/final-V.dat ${rootpath}/${folder}/in-matrix-item_folds/CTR_K_${k}/fold-5/final-V.dat \ 20 | -s cosine \ 21 | -e CTR_Rocchio_notpapers_notusers_normalized_cosine_k_${k} \ 22 | -n ${users} -m ${items} -l 500 ; exec sh" 23 | done 24 | done 25 | -------------------------------------------------------------------------------- /lib/Rocchio_LDA_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_data/terms_keywords_based 3 | for folder in 2k_10_P3_reduced 2k_10_P5_reduced 2k_10_P10_reduced 2k_20_P3_reduced 2k_20_P5_reduced 2k_20_P10_reduced 2k_30_P3_reduced 2k_30_P5_reduced 2k_30_P10_reduced 2k_40_P3_reduced 2k_40_P5_reduced 4 | #for folder in 2k_40_P5_reduced 2k_40_P10_reduced 2k_50_P3_reduced 2k_50_P5_reduced 2k_100_P3_reduced 2k_100_P5_reduced 5 | do 6 | line=$(head -n 1 ${rootpath}/${folder}/stats.txt) 7 | IFS='(' read -a v <<< "${line}" 8 | v=${v[1]//)/} 9 | v=${v// /} 10 | IFS=',' read -a v <<< "${v}" 11 | users=${v[0]} 12 | items=${v[1]} 13 | echo $users 14 | echo $items 15 | for k in 200 16 | do 17 | screen -S Rocchio_LDA_Normalized_Cosine${folder}_k_${k} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 18 | python3 /home/alzoghba/IFUP2018/SciPRec_CTR/lib/rocchio_based_recommender.py \ 19 | -u ${rootpath}/${folder}/in-matrix-item_folds \ 20 | -p ${rootpath}/${folder}/lda_topics/theta_${k}.dat \ 21 | -s jenson_shannon \ 22 | -e LDA_Rocchio_normalized_JS_k_${k} \ 23 | -splt ${rootpath}/${folder}/in-matrix-item_folds \ 24 | -n ${users} -m ${items} -ptdst -no -l 500 ;" 25 | done 26 | done -------------------------------------------------------------------------------- /lib/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anasalzogbi/T-CTR/25a1d68cc99e4f922e9d155ca99ff9c53effcee8/lib/__init__.py -------------------------------------------------------------------------------- /lib/ce_temporal.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import argparse 4 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 5 | import numpy as np 6 | import pandas as pd 7 | from util.files_utils import read_mappings 8 | from util.files_utils import read_ratings_as_list 9 | from lib.Probabilistic_Matrix_Factorization import PMF 10 | from util.utils import kron_A_N, calculate_metrics_user 11 | import time 12 | class CE(): 13 | def __init__(self, num_users, num_items, intervals_count, num_factors=50, epochs=30, phi=10, reg_param=0.5, tolerance = 1e-5, momentum = 0.5): 14 | self.factors = num_factors 15 | self.num_users = num_users 16 | self.num_items = num_items 17 | self.num_factors = num_factors 18 | self.max_epochs = epochs 19 | self.reg_param = reg_param 20 | self.phi = phi 21 | self.intervals_count = intervals_count 22 | self.tol = tolerance 23 | self.momentum = momentum 24 | 25 | def bootstrap(self, ratings_df, T0): 26 | # Decide 27 | pmf = PMF(self.num_users, self.num_items, num_feat=self.factors, epsilon=0.1, reg_param=self.reg_param, momentum=0.8, maxepoch=self.max_epochs, num_batches=5, batch_size=1000) 28 | return pmf.fit(ratings_df, T0=T0) 29 | 30 | 31 | def calculate_a_user(self, U, t, verbos = False): 32 | # U: K X |T| 33 | U = U[:, 0:t] 34 | if verbos: 35 | print("U:") 36 | print("-----------") 37 | print(U) 38 | Z = np.zeros((U.shape[1] - self.phi, self.phi * self.num_factors)) 39 | for j in range(self.phi - 1, U.shape[1] - 1): 40 | end = j - self.phi if j >= self.phi else -U.shape[1] - 1 41 | a = U[:, j:end:-1].T.reshape((U.shape[0] * (end - j))) 42 | Z[j - self.phi + 1, :] = a 43 | if verbos: 44 | print("Z:") 45 | print("-----------") 46 | print(Z) 47 | print("Y: ") 48 | print("-----------") 49 | print(U.flatten('F')[self.phi * self.num_factors:, np.newaxis]) 50 | eye = 0.01 *np.eye(Z.shape[1]) 51 | # zzt=Z.dot(Z.T) 52 | zzt = Z.T.dot(Z)+eye 53 | if verbos: 54 | print("zzt:") 55 | print("-----------") 56 | print(zzt.shape) 57 | eye = np.eye(zzt.shape[0]) 58 | # zztinv = np.linalg.inv(zzt) 59 | zztinv = np.linalg.solve(zzt, eye) 60 | if verbos: 61 | if np.allclose(zzt.dot(zztinv), eye, rtol=1e-02, atol=1e-02): 62 | print("inverted correctly") 63 | else: 64 | print("was not inverted correctly") 65 | print(zzt.dot(zztinv)) 66 | zztz = zztinv.dot(Z.T) 67 | 68 | if verbos: 69 | print(zztz.shape) 70 | # print(U.flatten('F')[self.phi*k:, np.newaxis].shape) 71 | cron = kron_A_N(zztz, self.num_factors) 72 | if verbos: 73 | print('cron shape', cron.shape) 74 | B = cron.dot(U.flatten('F')[self.phi * self.num_factors:, np.newaxis]) 75 | if verbos: 76 | print("B:") 77 | print("-----------") 78 | print(B.shape) 79 | A = [] 80 | for i in B.reshape(self.phi, self.num_factors * self.num_factors): 81 | A.append(i.reshape((self.num_factors, self.num_factors), order='F')) 82 | return A 83 | 84 | def calculate_a(self, UT, t): 85 | #UT: self.num_users, self.intervals_count, self.num_factors 86 | A = [] 87 | times = [] 88 | for u in range(self.num_users): 89 | U = UT[u] 90 | # U dimensions: intervals_count X num_factors 91 | if u % 50 ==0: 92 | print('Calculating A for user {}/ {}'.format(u,self.num_users)) 93 | t0 = time.time() 94 | A.append(self.calculate_a_user(U.T, t)) 95 | times.append(time.time() - t0) 96 | print("Calculating A for {} users in {:5.4f} seconds in average".format(self.num_users, sum(times)/len(times))) 97 | return A 98 | 99 | def calculate_W(self, A, UT,t): 100 | W = np.zeros(self.num_factors) 101 | for i in range(self.phi): 102 | W += A[i].dot(UT[t - i-1]) 103 | return W 104 | 105 | 106 | 107 | def fit(self, ratings_df): 108 | # Define T0: 109 | T0 = self.num_factors * self.phi+self.phi 110 | 111 | # Bootstrap 112 | UT0, V0 = self.bootstrap(ratings_df, T0) 113 | 114 | # initialize A's for all users: 115 | A = self.calculate_a(UT0, T0) 116 | UT = 0.1 * np.random.randn(self.num_users, self.intervals_count, self.num_factors) 117 | VT = 0.1 * np.random.randn(self.num_items, self.intervals_count, self.num_factors) 118 | UT[:,0:T0,:] = UT0 119 | converge_num = 0 120 | for t in range(T0, self.intervals_count): 121 | print("Time point: {}".format(t)) 122 | # Get the ratings of time (time_slot) 123 | train_vec = ratings_df[ratings_df.idx == t][['user', 'paper']].values 124 | if len(train_vec) > 0: 125 | W = [] 126 | for u in range(self.num_users): 127 | W.append(self.calculate_W(A[u], UT[u], t)) 128 | W = np.array(W) 129 | converged = False 130 | epoch = 1 131 | last_rmse = None 132 | while not converged and epoch <= self.max_epochs: 133 | #print("Epoch: {}".format(epoch)) 134 | user_IDs = np.array(train_vec[:,0], dtype='int32') 135 | item_IDs = np.array(train_vec[:,1], dtype='int32') 136 | 137 | # Compute Objective Function 138 | pred_out = np.sum(np.multiply(UT[user_IDs, t, :], VT[item_IDs,t, :]), axis=1) 139 | 140 | rawErr = pred_out - len(pred_out) * [1] 141 | 142 | # Compute gradients 143 | #print("Updating U, V") 144 | U_W = UT[user_IDs, t, :] - W[user_IDs] 145 | Ix_User = 2 * np.multiply(rawErr[:, np.newaxis], VT[item_IDs, t, :]) + 2 * self.reg_param * U_W 146 | V_V0 = VT[item_IDs, t, :] - V0[item_IDs] 147 | Ix_Item = 2 * np.multiply(rawErr[:, np.newaxis], UT[user_IDs, t, :]) + 2 * self.reg_param * V_V0 148 | 149 | dw_Item = np.zeros((self.num_items, self.num_factors)) 150 | dw_User = np.zeros((self.num_users, self.num_factors)) 151 | 152 | # loop to aggreate the gradients of the same element 153 | for i in range(len(train_vec)): 154 | dw_Item[item_IDs[i], :] += Ix_Item[i, :] 155 | dw_User[user_IDs[i], :] += Ix_User[i, :] 156 | 157 | # Update: 158 | VT[:, t, :] = VT[:, t, :] - (self.momentum * dw_Item / len(train_vec)) 159 | UT[:, t, :] = UT[:, t, :] - (self.momentum * dw_User / len(train_vec)) 160 | 161 | # stop when converge 162 | pred_out = np.sum(np.multiply(UT[user_IDs, t, :], VT[item_IDs, t, :]), axis=1) 163 | rawErr = pred_out - len(pred_out) * [1] 164 | obj = np.linalg.norm(rawErr) ** 2 +self.reg_param * (np.linalg.norm(U_W) ** 2 + np.linalg.norm(V_V0) ** 2) 165 | 166 | train_rmse = np.sqrt(obj / len(train_vec)) 167 | #print("RMSE: {:5.3f}".format(train_rmse)) 168 | #if last_rmse: 169 | # print("rmse diff: {:5.3f}".format(train_rmse - last_rmse)) 170 | if last_rmse and abs(train_rmse - last_rmse) <= self.tol: 171 | print('converges at iteration {:d}, RMSE: {:5.4f}/{:5.4f} #ratings: {:d}'.format(epoch,train_rmse,last_rmse, len(train_vec))) 172 | converged = True 173 | converge_num +=1 174 | else: 175 | last_rmse = train_rmse 176 | epoch += 1 177 | #if not converged: 178 | # print("Epochs count: {}, not converged".format(epoch-1)) 179 | #print("Updating A...") 180 | A = self.calculate_a(UT, t) 181 | print("Number of convergence: {}".format(converge_num)) 182 | self.A = A 183 | self.UT = UT 184 | self.V0 = V0 185 | self.VT = VT 186 | 187 | def evaluate(self, test_ratings_df, candidate_papers, recall_breaks=[5, 10] + list(range(20, 201, 20)), mrr_breaks=[10], ndcg_breaks=[5, 10], folds_num=5, top=200): 188 | print("Evaluating...") 189 | metrics_count = len(recall_breaks) + len(mrr_breaks) + len(ndcg_breaks) 190 | max_t = test_ratings_df.idx.max() 191 | predictions = np.zeros((self.num_users, self.num_items)) 192 | U = 0.1 * np.random.randn(self.num_users, max_t, self.num_factors) 193 | U[:, 0:self.intervals_count, :] = self.UT 194 | test_intervals= test_ratings_df.idx.drop_duplicates() 195 | users_with_test = set() 196 | results = np.zeros(shape=(len(test_intervals),num_users, metrics_count)) 197 | t_idx = 0 198 | results.fill(-1) 199 | for t in range(self.intervals_count, test_ratings_df.idx.max()): 200 | print("Interval: {}".format(t)) 201 | users_with_zero_test = 0 202 | # Calculate W: 203 | W = [] 204 | for u in range(self.num_users): 205 | W.append(self.calculate_W(self.A[u], U[u], t)) 206 | test_vec = test_ratings_df[test_ratings_df.idx == t][['user', 'paper']].values 207 | 208 | # If the interval t has tes ratings 209 | if len(test_vec) >0: 210 | print("Evaluating interval: {}".format(t)) 211 | # There are some test ratins at this time interval, run evaluation: 212 | W = np.array(W) 213 | R = W.dot(self.V0.T) 214 | for user in range(num_users): 215 | # Get the test positive items for the user 216 | user_test_positive = list(set(test_vec[test_vec[:,0]==user][:,1])) 217 | if len(user_test_positive) == 0: 218 | # This user has no test positives, add Not available as result values 219 | users_with_zero_test += 1 220 | # Write results to the file 221 | l = map(str, ['{:7d}'.format(user), '{:7d}'.format(fold + 1)] + ["{:>7}".format('NA')] * metrics_count) 222 | continue 223 | users_with_test.add(user) 224 | # Get the prediction scores for the candidate items 225 | scores_u = R[user, candidate_papers[user]] 226 | 227 | # Identify the top recommendations 228 | recommended_items_idx = np.argsort(scores_u)[::-1][0:top] 229 | recommended_items_ids = np.array(candidate_papers[user])[recommended_items_idx] 230 | 231 | # Identify the hits: 232 | hits = [1 if i in user_test_positive else 0 for i in recommended_items_ids] 233 | 234 | # Calculate the metrics: 235 | metrics_values = calculate_metrics_user(hits, len(user_test_positive), recall_breaks, mrr_breaks, ndcg_breaks) 236 | try: 237 | results[t_idx,user,:] = metrics_values 238 | except: 239 | print(t_idx,user, results.shape) 240 | # Increment for the intervals only if t has ratings 241 | t_idx +=1 242 | # Keep the maximum metric value across all test intervals: 243 | res = np.max(results, axis=(0)) 244 | 245 | # The evaluation result, average over users with test: 246 | res = np.average(res[list(users_with_test)], axis=0) 247 | print( ["{:7.3f}".format(i) for i in res]) 248 | return res 249 | def check_ex(x, ratings): 250 | if ratings[x.user, x.paper] == 1: 251 | return True 252 | return False 253 | 254 | def load_data(timestamped_ratings_file, training_ratings_file, test_ratings_file, users_mapping_file, items_mapping_file, interval): 255 | 256 | # 1- Load training ratings into a dataframe and add timestamps to them: (u_id, p_id, timestamp) 257 | training_list = read_ratings_as_list(training_ratings_file) 258 | test_list = read_ratings_as_list(test_ratings_file) 259 | 260 | # Read userid- citeulikeid mapping 261 | users_dict = read_mappings(users_mapping_file) 262 | 263 | # Read citeulike_paperid mapping 264 | items_dict = read_mappings(items_mapping_file) 265 | 266 | num_items = len(items_dict) 267 | num_users = len(users_dict) 268 | 269 | training_ratings_mat = np.zeros((len(training_list), num_items)) 270 | for u_id, u_list in enumerate(training_list): 271 | for i in u_list: 272 | training_ratings_mat[u_id, i] = 1 273 | 274 | test_ratings_mat = np.zeros((len(training_list), num_items)) 275 | for u_id, u_list in enumerate(test_list): 276 | for i in u_list: 277 | test_ratings_mat[u_id, i] = 1 278 | 279 | print("#Users: {}, #Items: {}, #Ratings: {}".format(len(training_list), num_items, int(training_ratings_mat.sum()))) 280 | 281 | # Load timestamped ratings: 282 | ratings_df = pd.read_csv(timestamped_ratings_file, sep=',', header=0, names=['user', 'paper', 'date', 'tag'], parse_dates=['date'])[ 283 | ['user', 'paper', 'date']].drop_duplicates() 284 | 285 | ratings_df_f5 = ratings_df[(ratings_df.user.isin(users_dict.keys()) & (ratings_df.paper.isin(items_dict.keys())))].drop_duplicates() 286 | ratings_df_f5['user'] = ratings_df_f5.user.apply(lambda x: users_dict[x]) 287 | ratings_df_f5['paper'] = ratings_df_f5.paper.apply(lambda x: items_dict[str(x)]) 288 | 289 | ratings_df_f5.sort_values(by=['date'], inplace=True) 290 | per = ratings_df_f5.date.dt.to_period(interval) 291 | g = ratings_df_f5.groupby(per) 292 | ratings_df_f5['idx'] = g.grouper.group_info[0] 293 | 294 | ratings_train_df = ratings_df_f5[ratings_df_f5.apply(check_ex, axis=1, args=(training_ratings_mat,))] 295 | ratings_test_df = ratings_df_f5[ratings_df_f5.apply(check_ex, axis=1, args=(test_ratings_mat,))] 296 | 297 | return ratings_train_df, ratings_test_df, num_users, num_items 298 | 299 | local = False 300 | if local: 301 | # Local configs: 302 | fold = 1 303 | num_factors, phi, epochs = (5, 20, 30) 304 | # Load data: 305 | base_dir = '../../../datasets/citeulike/citeulike_2004_2007' 306 | exp_dir = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/CE/fold-'+str(fold) 307 | interval = 'W' 308 | 309 | 310 | else: 311 | # Server configs: 312 | fold = 5 313 | num_factors, epochs, phi = (5, 10, 4) 314 | base_dir = "/vol1/data_anas/citeulike_2004_2007" 315 | exp_dir = "/vol1/data_anas/citeulike_2004_2007/time-based_split_out-of-matrix/CE/fold-"+str(fold) 316 | interval = 'M' 317 | 318 | parser = argparse.ArgumentParser() 319 | parser.add_argument("--fold", "-f", type=int, help="The fold number.") 320 | parser.add_argument("--phi", "-phi", type=int) 321 | parser.add_argument("--num_factors", "-k", type=int, help="The number of latent factors.") 322 | parser.add_argument("--epochs", "-e", type=int, help="The number of epochs.") 323 | parser.add_argument("--interval", "-i", choices=['D', 'W', 'M'], help="The interval. Day (D), Week (W) or Month (M).") 324 | 325 | args = parser.parse_args() 326 | 327 | # Checking and setting the arguments: 328 | if args.fold: 329 | fold = args.fold 330 | if args.phi: 331 | phi = args.phi 332 | if args.num_factors: 333 | num_factors = args.num_factors 334 | if args.epochs: 335 | epochs = args.epochs 336 | if args.interval: 337 | interval = args.interval 338 | 339 | 340 | timestamp_ratings_file = os.path.join(base_dir, "ratings.csv") 341 | training_ratings_file = os.path.join(base_dir,'time-based_split_out-of-matrix', 'fold-'+str(fold), 'train-users.dat') 342 | test_ratings_file = os.path.join(base_dir,'time-based_split_out-of-matrix', 'fold-'+str(fold), 'test-users.dat') 343 | users_mapping_file = os.path.join(base_dir,'time-based_split_out-of-matrix', 'fold-'+str(fold), 'userhash_user_id_map.csv') 344 | items_mapping_file = os.path.join(base_dir,'time-based_split_out-of-matrix', 'fold-'+str(fold), 'citeulike_id_doc_id_map.csv') 345 | 346 | if not os.path.exists(exp_dir): 347 | os.makedirs(exp_dir) 348 | print("Resulting Matrices will be stored in: [{}]".format(exp_dir)) 349 | 350 | training_ratings_df, test_ratings_df, num_users, num_items = load_data(timestamp_ratings_file, training_ratings_file, test_ratings_file, users_mapping_file, items_mapping_file, interval) 351 | 352 | intervals_training = training_ratings_df.idx.max() 353 | 354 | 355 | if intervals_training < phi * num_factors +phi: 356 | print("phi {} * k {} + phi {} cann't be larger than #intervals in training {}. Stop!".format(phi, num_factors, phi, intervals_training)) 357 | sys.exit() 358 | 359 | # Load Candidate papers: 360 | candidates_file = os.path.join(base_dir,'time-based_split_out-of-matrix', 'fold-'+str(fold), 'candidate-items.dat') 361 | if os.path.exists(candidates_file): 362 | print("Loading candidates from [{}]".format(candidates_file)) 363 | candidate_papers = read_ratings_as_list(candidates_file) 364 | 365 | # ce = CE(num_users, num_items,intervals_count=training_ratings_df.idx.max()+1, num_factors=5, epochs=3, phi = 3, reg_param=0.5, tolerance = 1e-5, momentum = 0.5) 366 | ce = CE(num_users, num_items, intervals_count=training_ratings_df.idx.max() + 1, phi = phi, num_factors = num_factors, epochs=epochs) 367 | t0 = time.time() 368 | print("Start...") 369 | ce.fit(training_ratings_df) 370 | ce.evaluate(test_ratings_df, candidate_papers) 371 | 372 | np.save(os.path.join(exp_dir, "A"), ce.A) 373 | np.save(os.path.join(exp_dir, "UT"), ce.UT) 374 | np.save(os.path.join(exp_dir, "V0"), ce.V0) 375 | np.save(os.path.join(exp_dir, "VT"), ce.VT) 376 | print("factors: {}, phi: {}, epochs: {}, Interval: {}".format(num_factors, phi, epochs, interval)) 377 | print("Finished in {:6.4f} hours ".format((time.time() - t0) / 3600)) 378 | 379 | else: 380 | print("Candidate file not found: [{}]".format(candidates_file)) 381 | -------------------------------------------------------------------------------- /lib/lda_topics_gensim.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Anas Alzogbi 3 | Description: 4 | This module provides the functionality of: 5 | - Generating LDA topics for a set of documents using gensim library 6 | - Saving the documents-topic matrix (theta) and the topics-vocab matrix (beta) to files. 7 | - Exploring the generated topics 8 | Date: November 06th, 2017 9 | alzoghba@informatik.uni-freiburg.de 10 | """ 11 | import sys 12 | import os 13 | import argparse 14 | import time 15 | import multiprocessing 16 | import numpy as np 17 | from gensim.models.ldamodel import LdaModel 18 | from gensim.models.ldamulticore import LdaMulticore 19 | 20 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 21 | from util.files_utils import read_docs_vocabs_file, write_distribution 22 | 23 | 24 | 25 | def readVocabs(vocab_file): 26 | """ 27 | # Reads the vocabulary file into dictionary 28 | :param vocab_file: file path 29 | :return: dictionary(vocab_id, vocabulary) 30 | """ 31 | vocabs = {} 32 | idx = 0 33 | with open(vocab_file, 'r') as f: 34 | for line in f: 35 | vocabs[idx] = line.strip() 36 | idx += 1 37 | return vocabs 38 | 39 | 40 | # print_lda_topics(lda.components_, vocab_dict) 41 | def print_lda_topics(topics, vocabs_dict, n_top_words=10): 42 | 43 | """ 44 | This method prints the top n words of each document for a list of latent topics. 45 | # source: https://stackoverflow.com/questions/44208501/getting-topic-word-distribution-from-lda-in-scikit-learn 46 | :param topics: 2d array: topics_count x vocabs_count 47 | :param vocabs_dict: vocabulary dictionary( vocab_id, vocabulary) 48 | :param n_top_words: The desired number of the topic' most important word. 49 | """ 50 | topic_words = {} 51 | for topic, comp in enumerate(topics): 52 | # for the n-dimensional array "arr": 53 | # argsort() returns a ranked n-dimensional array of arr, call it "ranked_array" 54 | # which contains the indices that would sort arr in a descending fashion 55 | # for the ith element in ranked_array, ranked_array[i] represents the index of the 56 | # element in arr that should be at the ith index in ranked_array 57 | # ex. arr = [3,7,1,0,3,6] 58 | # np.argsort(arr) -> [3, 2, 0, 4, 5, 1] 59 | # word_idx contains the indices in "topic" of the top num_top_words most relevant 60 | # to a given topic ... it is sorted ascending to begin with and then reversed (desc. now) 61 | word_idx = np.argsort(comp)[::-1][:n_top_words] 62 | 63 | # store the words most relevant to the topic 64 | topic_words[topic] = [vocabs_dict[i] for i in word_idx] 65 | for topic, words in topic_words.items(): 66 | print('Topic: %d' % topic) 67 | print(' %s' % ', '.join(words)) 68 | 69 | 70 | # main code; 71 | if __name__ == '__main__': 72 | docs_file = '../../citeulike-crawled/converted_data/2k_1_P3/terms_keywords_based/2k_100_P3_reduced/mult.dat' 73 | output_directory = '../../citeulike-crawled/converted_data/2k_1_P3/terms_keywords_based/2k_100_P3_reduced/lda_topics' 74 | vocab_file = '../../citeulike-crawled/converted_data/2k_1_P3/terms_keywords_based/2k_100_P3_reduced/terms.dat' 75 | k_list = [50, 100, 150, 200, 250] 76 | cores = 1 77 | parser = argparse.ArgumentParser() 78 | parser.add_argument("--output_dir", "-o", help="The output directory") 79 | parser.add_argument("--docs_file", "-f", help="The documents bag of words file (mult.dat)") 80 | parser.add_argument("--vocabs_file", "-v", help="The vocabulary file") 81 | parser.add_argument("--k_list", "-k", help="The list of number of topics desired.", type=int, nargs='+') 82 | parser.add_argument("--cores", "-c", type=int, help="The number of cores to be used, default: single core") 83 | 84 | args = parser.parse_args() 85 | multicore = False 86 | 87 | # Checking and setting the arguments: 88 | if args.output_dir: 89 | output_directory = args.output_dir 90 | if args.docs_file: 91 | docs_file = args.docs_file 92 | 93 | if not os.path.exists(docs_file): 94 | print("Error, document file not exists: {}".format(docs_file)) 95 | 96 | if args.vocabs_file: 97 | vocab_file = args.vocabs_file 98 | 99 | if not os.path.exists(vocab_file): 100 | print("Error, vocabulary file not exists: {}".format(vocab_file)) 101 | 102 | if args.k_list: 103 | k_list = args.k_list 104 | if args.cores: 105 | cores = args.cores 106 | 107 | if not os.path.exists(output_directory): 108 | os.makedirs(output_directory) 109 | # Reading the documents bag of words file: 110 | documents = read_docs_vocabs_file(docs_file) 111 | 112 | print("Reading vocabularies...") 113 | vocabs_dict = readVocabs(vocab_file) 114 | 115 | # Computing LDA 116 | for k in k_list: 117 | t1 = time.time() 118 | if cores > 1: 119 | print("Building Lda model k = {}, multicores...".format(k)) 120 | lda = LdaMulticore(corpus=documents, num_topics=k, id2word=vocabs_dict, workers=min(cores,multiprocessing.cpu_count()), alpha=1e-5, eta=5e-1, minimum_probability=0.0) 121 | else: 122 | print("Building Lda model k = {} ...".format(k)) 123 | lda = LdaModel(corpus=documents, num_topics=k, minimum_probability=0.0) 124 | 125 | # theta: 126 | print("Extracting theta...") 127 | document_distribution = [] 128 | for doc in documents: 129 | document_distribution.append(lda[doc]) 130 | #l = sorted(lda[doc], key=lambda x: x[0]) 131 | #document_distribution.append([i for _, i in l]) 132 | 133 | print("Extracting beta...") 134 | # Beta: # topics x # terms np array 135 | beta = lda.get_topics() 136 | 137 | t2 = time.time() 138 | print("Done k = {} in {} mins, saving theta and beta to files ...".format(k, (t2 - t1) / 60)) 139 | 140 | # Writing distributions to the file 141 | write_distribution(document_distribution, os.path.join(output_directory, "theta_{}.dat".format(k))) 142 | write_distribution(beta, os.path.join(output_directory, "beta_{}.dat".format(k))) -------------------------------------------------------------------------------- /lib/lda_topics_sklearn.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Anas Alzogbi 3 | Description: 4 | This module provides the functionality of: 5 | - Generating LDA topics for a set of documents using sklearn library 6 | - Saving the documents-topic matrix (theta) and the topics-vocab matrix (beta) to files. 7 | - Exploring the generated topics 8 | Date: October 27th, 2017 9 | alzoghba@informatik.uni-freiburg.de 10 | """ 11 | import sys 12 | import os 13 | import argparse 14 | import time 15 | import numpy as np 16 | import multiprocessing 17 | from sklearn.decomposition import LatentDirichletAllocation 18 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 19 | from util.files_utils import read_docs_vocabs_file_as_array, write_distribution 20 | 21 | 22 | 23 | def readVocabs(vocab_file): 24 | """ 25 | # Reads the vocabulary file into dictionary 26 | :param vocab_file: file path 27 | :return: dictionary(vocab_id, vocabulary) 28 | """ 29 | vocabs = {} 30 | idx = 0 31 | with open(vocab_file, 'r') as f: 32 | for line in f: 33 | vocabs[idx] = line.strip() 34 | idx += 1 35 | return vocabs 36 | 37 | 38 | # print_lda_topics(lda.components_, vocab_dict) 39 | def print_lda_topics(topics, vocabs_dict, n_top_words=10): 40 | 41 | """ 42 | This method prints the top n words of each document for a list of latent topics. 43 | # source: https://stackoverflow.com/questions/44208501/getting-topic-word-distribution-from-lda-in-scikit-learn 44 | :param topics: 2d array: topics_count x vocabs_count 45 | :param vocabs_dict: vocabulary dictionary( vocab_id, vocabulary) 46 | :param n_top_words: The desired number of the topic' most important word. 47 | """ 48 | topic_words = {} 49 | for topic, comp in enumerate(topics): 50 | # for the n-dimensional array "arr": 51 | # argsort() returns a ranked n-dimensional array of arr, call it "ranked_array" 52 | # which contains the indices that would sort arr in a descending fashion 53 | # for the ith element in ranked_array, ranked_array[i] represents the index of the 54 | # element in arr that should be at the ith index in ranked_array 55 | # ex. arr = [3,7,1,0,3,6] 56 | # np.argsort(arr) -> [3, 2, 0, 4, 5, 1] 57 | # word_idx contains the indices in "topic" of the top num_top_words most relevant 58 | # to a given topic ... it is sorted ascending to begin with and then reversed (desc. now) 59 | word_idx = np.argsort(comp)[::-1][:n_top_words] 60 | 61 | # store the words most relevant to the topic 62 | topic_words[topic] = [vocabs_dict[i] for i in word_idx] 63 | for topic, words in topic_words.items(): 64 | print('Topic: %d' % topic) 65 | print(' %s' % ', '.join(words)) 66 | 67 | 68 | # main code; 69 | if __name__ == '__main__': 70 | docs_file = '../../citeulike-crawled/converted_data/2k_1_P3/terms_keywords_based/2k_100_P3_reduced/mult.dat' 71 | output_directory = '../../citeulike-crawled/converted_data/2k_1_P3/terms_keywords_based/2k_100_P3_reduced/lda_topics' 72 | vocab_file = '../../citeulike-crawled/converted_data/2k_1_P3/terms_keywords_based/2k_100_P3_reduced/terms.dat' 73 | k_list = [50, 100, 150, 200, 250] 74 | normalize_beta = False 75 | cores = 1 76 | parser = argparse.ArgumentParser() 77 | parser.add_argument("--output_dir", "-o", 78 | help="The output directory") 79 | parser.add_argument("--docs_file", "-f", help="The documents bag of words file (mult.dat)") 80 | parser.add_argument("--vocabs_file", "-v", help="The vocabulary file") 81 | parser.add_argument("--k_list", "-k", help="The list of number of topics desired.", type=int, nargs='+') 82 | parser.add_argument("--normalize", "-n", action="store_true", default=False, 83 | help="A flag controls if the beta vector should be normalized or not, default: not normalized.") 84 | parser.add_argument("--cores", "-c", type=int, help="The number of cores to be used, default: single core") 85 | 86 | args = parser.parse_args() 87 | 88 | # Checking and setting the arguments: 89 | if args.output_dir: 90 | output_directory = args.output_dir 91 | if not os.path.exists(output_directory): 92 | os.makedirs(output_directory) 93 | if args.docs_file: 94 | docs_file = args.docs_file 95 | 96 | if not os.path.exists(docs_file): 97 | print("Error, document file not exists: {}".format(docs_file)) 98 | 99 | if args.vocabs_file: 100 | vocab_file = args.vocabs_file 101 | 102 | if not os.path.exists(vocab_file): 103 | print("Error, vocabulary file not exists: {}".format(vocab_file)) 104 | 105 | if args.k_list: 106 | k_list = args.k_list 107 | if args.normalize: 108 | normalize_beta = True 109 | if args.cores: 110 | cores = args.cores 111 | # Reading the documents bag of words file: 112 | documents = read_docs_vocabs_file_as_array(docs_file) 113 | 114 | # Reading the vocabularies 115 | vocabs_dict = readVocabs(vocab_file) 116 | 117 | # Computing LDA 118 | for k in k_list: 119 | lda = LatentDirichletAllocation(n_components=k, max_iter=5, learning_method='online', learning_offset=50., 120 | random_state=0, n_jobs=min(cores,multiprocessing.cpu_count())) 121 | t1 = time.time() 122 | print("Building Lda model...") 123 | document_distribution = lda.fit_transform(documents) 124 | 125 | if normalize_beta: 126 | # Normalize the topics-vocab matrix (beta), it is not normalized 127 | #np.testing.assert_almost_equal(lda.components_.sum(axis=1), np.ones(lda.components_.shape[0])) 128 | beta = lda.components_ / lda.components_.sum(axis=1)[:, np.newaxis] 129 | else: 130 | beta = lda.components_ 131 | 132 | t2 = time.time() 133 | print("Done k = {} in {} mins".format(k, (t2 - t1) / 60)) 134 | 135 | # Writing distributions to the file 136 | write_distribution(document_distribution, os.path.join(output_directory, "theta_{}.dat".format(k))) 137 | write_distribution(beta, os.path.join(output_directory, "beta_{}.dat".format(k))) -------------------------------------------------------------------------------- /lib/pub_rec.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Anas Alzogbi 3 | Description: 4 | This module provides the functionality of: 5 | - Generate papers recommendations following the PubRec method, the approach is explained in the paper: 6 | PubRec: Recommending Publications Based On Publicly Available Meta-Data 7 | Date: November 15th, 2017 8 | alzoghba@informatik.uni-freiburg.de 9 | """ 10 | 11 | import argparse 12 | import os 13 | import numpy as np 14 | from util.files_utils import read_docs_topics_file, read_ratings_as_list 15 | from util.utils import convert_to_probability_dist 16 | import scipy 17 | 18 | def interest_extent(ratings_age_array, forgetting_factor): 19 | """ 20 | computes interest extent of a paper for a user based on the age of the rating 21 | ratings_age_array - a list of ages of the ratings in years or months 22 | returns 1d array of float representing the interest of the user to the papers 23 | """ 24 | return np.exp(-np.power(ratings_age_array, 2) / forgetting_factor) 25 | 26 | 27 | def cost_function( x): 28 | """ 29 | function to be minimized by L-BFGS algorithm 30 | x - matrix of shape 1*k, where k is the # of features 31 | returns a float, representing deviation the interest extent model 32 | """ 33 | return 1 / (2 * m) * (np.power(np.dot(x, self.V) - self.IE, 2).sum()) 34 | 35 | 36 | def calculatePubRecPredictions(ratings_list, papers_topics, ratings_timestamps, forgetting_factor): 37 | for u_ratings in ratings_list: 38 | u_papers = papers_topics[u_ratings] 39 | y = interest_extent(ratings_timestamps[u_ratings], forgetting_factor) 40 | x = np.array(RandomVector(len(self.docTermDict[library[0][0]]))) 41 | res = scipy.optimize.fmin_l_bfgs_b(cost_function, x, approx_grad=1) 42 | return (res[0], res[1]) 43 | 44 | if __name__ == '__main__': 45 | parser = argparse.ArgumentParser() 46 | parser.add_argument("--base_dir", "-u", 47 | help="The base directory that contains the folds, expecting to have sub folders: fold-[1..5], " 48 | "each folder has the training users ratings file") 49 | parser.add_argument("--papers_file", "-p", help="The papers-topics file") 50 | parser.add_argument("--experiment", "-e", help="The experiment name, used to name the output folder, where the " 51 | "resulting prediction files (score.npy) will be saved, the output directory " 52 | "will appear under the base directory") 53 | parser.add_argument("--users_num", "-n", type=int, help="The number of users in the dataset") 54 | parser.add_argument("--items_num", "-m", type=int, help="The number of items in the dataset") 55 | parser.add_argument("--step_lag", "-l", type=int, help="The step lag for reporting progress") 56 | #parser.add_argument("--is_prob_dist", "-d", action="store_true", default=False, help="A flag idicates if the provided papers vectors form probability distribution or not, default: False") 57 | args = parser.parse_args() 58 | 59 | # Checking and setting the arguments: 60 | if args.base_dir: 61 | base_dir = args.base_dir 62 | if not os.path.exists(base_dir): 63 | print("Input directory isnot found: {}".format(base_dir)) 64 | raise NameError("Input directory is not found") 65 | 66 | if args.papers_file: 67 | papers_file = args.papers_file 68 | if not os.path.exists(papers_file): 69 | print("papers file not found: {}".format(papers_file)) 70 | raise NameError("Papers file not found") 71 | # Reading papers file 72 | print("Reading papers-topics file: {}".format(papers_file)) 73 | papers_topics = read_docs_topics_file(papers_file) 74 | print("papers matrix dimensions: {}".format(papers_topics.shape)) 75 | 76 | if args.experiment: 77 | experiment_name = args.experiment 78 | 79 | if args.users_num: 80 | users_num = args.users_num 81 | 82 | if args.items_num: 83 | items_num = args.items_num 84 | 85 | if args.step_lag: 86 | lag = args.step_lag 87 | 88 | for fold in range(1, 6): 89 | users_rtings_file = os.path.join(base_dir, "fold-" + str(fold), "train-fold_" + str(fold) + "-users.dat") 90 | print("Reading users ratings file: {}".format(users_rtings_file)) 91 | output_dir = os.path.join(base_dir, experiment_name, "fold-" + str(fold)) 92 | if not os.path.exists(output_dir): 93 | os.makedirs(output_dir) 94 | # Read users ratings 95 | ratings_list = read_ratings_as_list(users_rtings_file) 96 | print("Rating matrix dimensions: {}".format(ratings_list.shape)) 97 | 98 | # Calculate predictions for all users: 99 | predictions = calculatePubRecPredictions(ratings_list, papers_topics, ratings_timestamps) 100 | 101 | # Saving the predictions: 102 | print("Storing predictions to: [{}]".format(os.path.join(output_dir, "score"))) 103 | np.save(os.path.join(output_dir, "score"), predictions) 104 | -------------------------------------------------------------------------------- /lib/rocchio_based_recommender.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | import argparse 4 | import time 5 | import numpy as np 6 | from gensim.matutils import kullback_leibler, jaccard, hellinger 7 | from sklearn.metrics.pairwise import cosine_similarity 8 | 9 | sys.path.append(os.path.join(os.path.dirname(__file__), "..")) 10 | from util.files_utils import read_ratings, read_docs_topics_file 11 | from util.similarity_metrics import jensen_shannon_div 12 | from util.utils import convert_to_probability_dist 13 | 14 | 15 | def calculate_hellinger_predictions(users_profiles, papers_topics, fold, splits, lag=500): 16 | print("Calculating predictions based on hellinger distance...") 17 | s_time = time.time() 18 | predictions = np.zeros((users_profiles.shape[0], papers_topics.shape[0])) 19 | step = 0 20 | if not (splits is None): 21 | print("Calculating for test items only...") 22 | for (i, u) in enumerate(users_profiles): 23 | # Get the test items, calculate the predictions for the test items only 24 | test_items = np.array(splits[i, fold]) 25 | for j in test_items: 26 | predictions[i,j] = 1 - hellinger(u, papers_topics[j]) 27 | step += 1 28 | if step % lag == 0: 29 | print("{} users done, time since prediction calculation: {:5.2f} minutes".format(step, ( 30 | time.time() - s_time) / 60)) 31 | else: 32 | print("Calculating for all items ...") 33 | for (i, u) in enumerate(users_profiles): 34 | for (j, p) in enumerate(papers_topics): 35 | predictions[i, j] = 1 - hellinger(u, p) 36 | step += 1 37 | if step % lag == 0: 38 | print("{} users done, time since prediction calculation: {:5.2f} minutes".format(step, ( 39 | time.time() - s_time) / 60)) 40 | 41 | return predictions 42 | 43 | 44 | def calculate_jensen_shannon_predictions(users_profiles, papers_topics, fold, splits, lag=100): 45 | print("Calculating predictions based on jensen shannon divergence...") 46 | s_time = time.time() 47 | predictions = np.zeros((users_profiles.shape[0], papers_topics.shape[0])) 48 | step = 0 49 | if not (splits is None): 50 | print("Calculating for test items only...") 51 | for (i, u) in enumerate(users_profiles): 52 | # Get the test items 53 | test_items = np.array(splits[i, fold]) 54 | for j in test_items: 55 | predictions[i, j] = 1 - jensen_shannon_div(u, papers_topics[j]) 56 | step += 1 57 | if step % lag == 0: 58 | print("{} users done, time since prediction calculation: {:5.2f} minutes".format(step, ( 59 | time.time() - s_time) / 60)) 60 | else: 61 | print("Calculating for all items...") 62 | for (i, u) in enumerate(users_profiles): 63 | for (j, p) in enumerate(papers_topics): 64 | predictions[i, j] = 1 - jensen_shannon_div(u, p) 65 | step += 1 66 | if step % lag == 0: 67 | print("{} users done, time since prediction calculation: {:5.2f} minutes".format(step, ( 68 | time.time() - s_time) / 60)) 69 | 70 | return predictions 71 | 72 | 73 | def calculate_cosine_sim_predictions(users_profiles, papers_topics): 74 | print("Calculating predictions based on cosine similarity...") 75 | s_time = time.time() 76 | predictions = cosine_similarity(users_profiles, papers_topics) 77 | print("Elapsed time since prediction calculation: {:5.2f} minutes".format((time.time() - s_time) / 60)) 78 | return predictions 79 | 80 | 81 | if __name__ == '__main__': 82 | base_dir = "../../data" 83 | papers_file = '../data/lda_topics/theta_200.dat' 84 | output_directory = '../../data/rocchio_based' 85 | users_num = 5551 86 | papers_num = 16980 87 | lag = 1000 88 | papers_file_list = [] 89 | papers_to_prob_dist = False 90 | normalize_user_profile = False 91 | lda_user_profile = False 92 | similarity_measure = "hellinger" 93 | 94 | parser = argparse.ArgumentParser() 95 | parser.add_argument("--base_dir", "-u", 96 | help="The base directory that contains the folds, expecting to have sub folders: fold-[1..5], " 97 | "each folder has the training users ratings file") 98 | parser.add_argument("--papers_file", "-p", 99 | help="The papers-topics file, specify this if you have a single paper file for all folds, otherwise use --papers_file_list to give a list of papers files, one for each fold") 100 | parser.add_argument("--papers_file_list", "-ps", 101 | help="The list of papers-topics files, make sure the list is orderd (fold1, fold2,...)", 102 | nargs='+') 103 | parser.add_argument("--similarity_measure", "-s", choices=['jenson_shannon', 'hellinger', 'cosine'], 104 | help="The similarity measure used to compare users profiles with papers' vectors.") 105 | parser.add_argument("--experiment", "-e", help="The experiment name, used to name the output folder, where the " 106 | "resulting prediction files (score.npy) will be saved, the output directory " 107 | "will appear under the base directory") 108 | parser.add_argument("--split_directory", "-splt", 109 | help="The directory that contains the folds. The folds folders are named as 'fold[1-5]', each one should contain the test files, the test files are needed here, so that we predict only for the tests") 110 | parser.add_argument("--users_num", "-n", type=int, help="The number of users in the dataset") 111 | parser.add_argument("--items_num", "-m", type=int, help="The number of items in the dataset") 112 | parser.add_argument("--step_lag", "-l", type=int, help="The step lag for reporting progress") 113 | parser.add_argument("--papers_to_prob_dist", "-ptdst", action="store_true", default=False, 114 | help="A flag whither to convert papers vectors to a probability distribution or not, Not needed for cosine similarity. Needed for probability distribution similarity metrics (jenson shannon, and hellinger). default: False") 115 | parser.add_argument("--normalize_user_profile", "-no", action="store_true", default=False, 116 | help="A flag idicates whither to normalize the user profile or not") 117 | parser.add_argument("--lda_user_profile", "-ldau", action="store_true", default=False, 118 | help="A flag idicates whether to use LDA topics for building user profile") 119 | args = parser.parse_args() 120 | 121 | # Checking and setting the arguments: 122 | if args.base_dir: 123 | base_dir = args.base_dir 124 | if not os.path.exists(base_dir): 125 | print("Input directory isnot found: {}".format(base_dir)) 126 | raise NameError("Input directory is not found") 127 | 128 | if args.papers_file: 129 | papers_file = args.papers_file 130 | if not os.path.exists(papers_file): 131 | print("papers file not found: {}".format(papers_file)) 132 | raise NameError("Papers file not found") 133 | 134 | if args.papers_file_list: 135 | papers_file_list = args.papers_file_list 136 | 137 | split_directory = None 138 | if args.split_directory: 139 | split_directory = args.split_directory 140 | if not os.path.exists(split_directory): 141 | print("Split directory not found: {}".format(split_directory)) 142 | raise NameError("Split directory not found") 143 | 144 | if args.experiment: 145 | experiment_name = args.experiment 146 | 147 | if args.users_num: 148 | users_num = args.users_num 149 | 150 | if args.items_num: 151 | items_num = args.items_num 152 | 153 | if args.step_lag: 154 | lag = args.step_lag 155 | 156 | if args.similarity_measure: 157 | similarity_measure = args.similarity_measure 158 | if args.papers_to_prob_dist: 159 | papers_to_prob_dist = True 160 | 161 | if args.normalize_user_profile: 162 | normalize_user_profile = True 163 | 164 | if args.lda_user_profile: 165 | lda_user_profile = True 166 | 167 | splits = None 168 | if not (split_directory is None): 169 | # reading the splits file 170 | splits_file = os.path.join(split_directory, "splits.npy") 171 | 172 | if not os.path.exists(splits_file): 173 | print("Splits file not found: {} ".format(splits_file)) 174 | raise NameError("Splits file not found") 175 | print("loading {} ...\n".format(splits_file)) 176 | splits = np.load(splits_file) 177 | 178 | 179 | if lda_user_profile: 180 | # Reading papers file 181 | print("Reading papers LDA topics file: {}".format(papers_file)) 182 | papers_lda_topics = read_docs_topics_file(papers_file) 183 | print("papers LDA matrix dimensions: {}".format(papers_lda_topics.shape)) 184 | 185 | for fold in range(1, 6): 186 | users_ratings_file = os.path.join(base_dir, "fold-" + str(fold), "train-fold_" + str(fold) + "-users.dat") 187 | print("Reading users ratings file: {}".format(users_ratings_file)) 188 | output_dir = os.path.join(base_dir, experiment_name, "fold-" + str(fold)) 189 | if not os.path.exists(output_dir): 190 | os.makedirs(output_dir) 191 | # Read users ratings 192 | ratings_mat = read_ratings(users_ratings_file, users_num, items_num) 193 | print("Rating matrix dimensions: {}".format(ratings_mat.shape)) 194 | 195 | # Load the papers CTR topics: 196 | if len(papers_file_list) != 0: 197 | print("Reading papers CTR topics file: {}".format(os.path.join(base_dir, papers_file_list[fold - 1]))) 198 | papers_ctr_topics = read_docs_topics_file(os.path.join(base_dir, papers_file_list[fold - 1])) 199 | print("papers CTR matrix dimensions: {}".format(papers_ctr_topics.shape)) 200 | # Convert CTR papers_topics to probability distribution 201 | print("Converting papers vectors into probability distributions...") 202 | papers_ctr_topics = convert_to_probability_dist(papers_ctr_topics) 203 | 204 | # Build user profiles: Each user profile is the summation of the relevant papers' LDA topics. 205 | print("Building users profiles...") 206 | M = ratings_mat.dot(papers_lda_topics) 207 | # Normalize user profiles: 208 | print("Normalizing users profiles...") 209 | ratings_count = np.sum(ratings_mat, axis=1) 210 | users_profiles = M / ratings_count[:, None] 211 | """ 212 | # Check if the normalization works, users vectors should sum up to 1 213 | np.sum(M, axis=1)[1:5] 214 | sum(np.sum(users_profiles, axis=1)) 215 | # M[0,1:10], normalized_M[0,1:10] 216 | """ 217 | 218 | if similarity_measure == "hellinger": 219 | predictions = calculate_hellinger_predictions(users_profiles, papers_ctr_topics, fold - 1, splits, lag) 220 | elif similarity_measure == "jenson_shannon": 221 | predictions = calculate_jensen_shannon_predictions(users_profiles, papers_ctr_topics, fold - 1, splits, lag) 222 | elif similarity_measure == "cosine": 223 | predictions = calculate_cosine_sim_predictions(users_profiles, papers_ctr_topics) 224 | 225 | # Saving the predictions: 226 | print("Storing predictions to: [{}]".format(os.path.join(output_dir, "score"))) 227 | np.save(os.path.join(output_dir, "score"), predictions) 228 | 229 | else: 230 | # Reading papers file 231 | papers_topics = None 232 | if len(papers_file_list) == 0: 233 | print("Reading papers-topics file: {}".format(papers_file)) 234 | papers_topics = read_docs_topics_file(papers_file) 235 | print("papers matrix dimensions: {}".format(papers_topics.shape)) 236 | # Convert papers_topics to probability distribution if needed 237 | if papers_to_prob_dist: 238 | print("Converting papers vectors into probability distributions...") 239 | papers_topics = convert_to_probability_dist(papers_topics) 240 | 241 | splits = None 242 | if not (split_directory is None): 243 | # reading the splits file 244 | splits_file = os.path.join(split_directory, "splits.npy") 245 | 246 | if not os.path.exists(splits_file): 247 | print("Splits file not found: {} ".format(splits_file)) 248 | raise NameError("Splits file not found") 249 | print("loading {} ...\n".format(splits_file)) 250 | splits = np.load(splits_file) 251 | 252 | for fold in range(1, 6): 253 | users_rtings_file = os.path.join(base_dir, "fold-" + str(fold), "train-fold_" + str(fold) + "-users.dat") 254 | print("Reading users ratings file: {}".format(users_rtings_file)) 255 | output_dir = os.path.join(base_dir, experiment_name, "fold-" + str(fold)) 256 | if not os.path.exists(output_dir): 257 | os.makedirs(output_dir) 258 | # Read users ratings 259 | ratings_mat = read_ratings(users_rtings_file, users_num, items_num) 260 | print("Rating matrix dimensions: {}".format(ratings_mat.shape)) 261 | 262 | # if the there is a different file for each fold, the files will be in papers_file_list, load the corresponding one now: 263 | if len(papers_file_list) != 0: 264 | print("Reading papers-topics file: {}".format(os.path.join(base_dir, papers_file_list[fold - 1]))) 265 | papers_topics = read_docs_topics_file(os.path.join(base_dir, papers_file_list[fold - 1])) 266 | print("papers matrix dimensions: {}".format(papers_topics.shape)) 267 | # Convert papers_topics to probability distribution if needed 268 | if papers_to_prob_dist: 269 | print("Converting papers vectors into probability distributions...") 270 | papers_topics = convert_to_probability_dist(papers_topics) 271 | 272 | # Build user profiles: Each user profile is the summation of the relevant papers' LDA topics. 273 | print("Building users profiles...") 274 | M = ratings_mat.dot(papers_topics) 275 | 276 | if normalize_user_profile: 277 | # Normalize user profiles: 278 | print("Normalizing users profiles...") 279 | ratings_count = np.sum(ratings_mat, axis=1) 280 | users_profiles = M / ratings_count[:, None] 281 | """ 282 | # Check if the normalization works, users vectors should sum up to 1 283 | np.sum(M, axis=1)[1:5] 284 | sum(np.sum(users_profiles, axis=1)) 285 | # M[0,1:10], normalized_M[0,1:10] 286 | """ 287 | else: 288 | users_profiles = M 289 | 290 | if similarity_measure == "hellinger": 291 | predictions = calculate_hellinger_predictions(users_profiles, papers_topics, fold-1, splits, lag) 292 | elif similarity_measure == "jenson_shannon": 293 | predictions = calculate_jensen_shannon_predictions(users_profiles, papers_topics, fold - 1, splits, lag) 294 | elif similarity_measure == "cosine": 295 | predictions = calculate_cosine_sim_predictions(users_profiles, papers_topics) 296 | 297 | # Saving the predictions: 298 | print("Storing predictions to: [{}]".format(os.path.join(output_dir, "score"))) 299 | np.save(os.path.join(output_dir, "score"), predictions) 300 | -------------------------------------------------------------------------------- /lib/time-aware_rec.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Anas Alzogbi 3 | Description: 4 | This module provides the functionality of: 5 | - Computing ratings weights based on the ratings age 6 | Date: December 12th, 2017 7 | alzoghba@informatik.uni-freiburg.de 8 | """ 9 | 10 | import argparse 11 | import os 12 | import numpy as np 13 | from util.files_utils import read_ratings_as_list, write_ratings 14 | 15 | import pandas as pd 16 | 17 | class Range(object): 18 | def __init__(self, start, end): 19 | self.start = start 20 | self.end = end 21 | 22 | def __eq__(self, other): 23 | return self.start <= other <= self.end 24 | 25 | 26 | def interest_extent(ratings_age_array, forgetting_factor): 27 | """ 28 | computes interest extent of a paper for a user based on the age of the rating 29 | ratings_age_array - a list of ages of the ratings in years or months 30 | returns 1d array of float representing the interest of the user to the papers 31 | """ 32 | if forgetting_factor == 0: 33 | forgetting_factor = 0.1 34 | return [i if i > 0.01 else 0.01 for i in np.exp(-np.power(ratings_age_array, 2) / forgetting_factor)] 35 | 36 | # Retuns values between 0 and 100, proportional to the similarity. This is to be used to generate factors for interst_extent function 37 | def calculate_users_lambda(ratings_list, papers_topics): 38 | us_sims = [] 39 | i = 0 40 | for u in ratings_list: 41 | sims = [] 42 | for i, _ in enumerate(u): 43 | if i < len(u) - 1: 44 | sims.append(jackard_sim(papers_topics[u[i]], papers_topics[u[i + 1]])) 45 | if len(sims) == 0: 46 | i += 1 47 | us_sims.append(1) 48 | else: 49 | us_sims.append(np.mean(sims)*100) 50 | return us_sims 51 | 52 | def interest_extent_2(ages_list, factor): 53 | return (2/(1+ np.exp(np.array(ages_list) * factor))).tolist() 54 | 55 | 56 | def jackard_sim(l1, l2): 57 | if len(l1) == 0 or len(l2) == 0: 58 | return 0 59 | s1 = set(l1) 60 | s2 = set(l2) 61 | c = len(s1.intersection(s2)) 62 | return float(c) / (len(s1) + len(s2) - c) 63 | 64 | 65 | def calculate_users_lambda2(ratings_list, papers_topics): 66 | us_sims = [] 67 | i = 0 68 | for u in ratings_list: 69 | sims = [] 70 | for i, _ in enumerate(u): 71 | if i < len(u) - 1: 72 | sims.append(1 - jackard_sim(papers_topics[u[i]], papers_topics[u[i + 1]])) 73 | if len(sims) == 0: 74 | i += 1 75 | us_sims.append(1) 76 | else: 77 | us_sims.append(np.mean(sims)) 78 | return us_sims 79 | 80 | if __name__ == '__main__': 81 | adaptive = False 82 | """ 83 | ratings_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_in-matrix/' + fold + '/train-items.dat' 84 | ratings_ages_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_in-matrix/' + fold + '/train-items-ages.dat' 85 | theta_file = "../../../datasets/citeulike/citeulike_2004_2007/time-based_split_in-matrix/" + fold + "/lda_sklearn/theta_150.dat" 86 | # fold = 'fold-6' 87 | 88 | 89 | parser = argparse.ArgumentParser() 90 | parser.add_argument("--ratings_ages_file", "-r", help="The ratings ages file (-ages.dat)") 91 | parser.add_argument("--factor", "-f", type=float, choices=[Range(0.1, 1)], help="The anti-aging factor") 92 | parser.add_argument("--adaptive", "-a", action="store_true", default=False, 93 | help="Set factor to be fit for adaptively, the factor value if given will be discarded.") 94 | args = parser.parse_args() 95 | factor = 1 96 | # Checking and setting the arguments: 97 | if args.ratings_ages_file: 98 | ratings_file = args.ratings_ages_file 99 | if args.factor: 100 | factor = args.factor 101 | """ 102 | 103 | 104 | for bla in ['items', 'users']: 105 | for fold in [0, 1, 2, 3, 5]: 106 | ratings_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/fold-' + str(fold + 1) + '/train-' + bla + '.dat' 107 | ratings_ages_file = '../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/fold-' + str(fold + 1) + '/train-' + bla + '-ages.dat' 108 | theta_file = "../../../datasets/citeulike/citeulike_2004_2007/time-based_split_out-of-matrix/fold-" + str(fold + 1) + "/lda_sklearn/theta_150.dat" 109 | ratings_file_name = os.path.splitext(os.path.basename(ratings_file))[0] 110 | if '-ages' in ratings_file_name: 111 | output_file = os.path.join(os.path.dirname(ratings_file), ratings_file_name.replace('-ages', '-weights')) 112 | else: 113 | output_file = os.path.join(os.path.dirname(ratings_file), ratings_file_name + "-weights") 114 | 115 | if not os.path.exists(ratings_file): 116 | print("Input file is not found: {}".format(ratings_file)) 117 | raise NameError("Input file is not found") 118 | # Read ratings 119 | print("Reading ratings file: {}".format(ratings_file)) 120 | ratings_list = read_ratings_as_list(ratings_file) 121 | ratings_ages_list = read_ratings_as_list(ratings_ages_file, type_=float) 122 | 123 | if adaptive: 124 | print("Factor: {}, Fold: {}, bla: {}".format('Adaptive', fold + 1, bla)) 125 | output_file += '_Adaptive' 126 | 127 | # Load papers topics 128 | l = [] 129 | with open(theta_file, 'r') as f: 130 | for line in f: 131 | l.append([float(i) for i in line.split(" ")]) 132 | papers_topics = [] 133 | for i in l: 134 | papers_topics.append([k for k, j in enumerate(i) if j > 0.01]) 135 | 136 | # Sort ratings per ages: 137 | sorted_ratings_list = [] 138 | for i in range(len(ratings_list)): 139 | r = ratings_list[i] 140 | ages = ratings_ages_list[i] 141 | r_ages = list(zip(r, ages)) 142 | sorted_ratings_list.append([i for i, _ in sorted(r_ages, key=lambda x: x[1], reverse=True)]) 143 | lambdas = calculate_users_lambda2(sorted_ratings_list, papers_topics) 144 | # lambdas = calculate_users_lambda(sorted_ratings_list, papers_topics) 145 | 146 | # the weights: 147 | weights = [] 148 | for u, user_ratings in enumerate(ratings_ages_list): 149 | # Convert to years: 150 | l = [i / 12 for i in user_ratings] 151 | weights.append(["{:5.3f}".format(i) for i in interest_extent_2(l, lambdas[u])]) 152 | # weights.append(["{:5.3f}".format(i) for i in interest_extent(l, lambdas[u])]) 153 | 154 | output_file += '_IE2.dat' 155 | # Saving the predictions: 156 | write_ratings(weights, output_file) 157 | 158 | else: 159 | for factor in [0.1, 0.5, 1]: 160 | output_f = output_file + '_Factor_{}'.format(factor) 161 | print("Factor: {}, Fold: {}, bla: {}".format(factor, fold+1, bla)) 162 | # the weights: 163 | weights = [] 164 | for u,user_ratings in enumerate(ratings_ages_list): 165 | # Convert to years: 166 | l = [i/12 for i in user_ratings] 167 | weights.append(["{:5.3f}".format(i) for i in interest_extent_2(l, factor)]) 168 | 169 | output_f += '_IE2.dat' 170 | # Saving the predictions: 171 | print("Saving to file: [{}]".format(output_f)) 172 | write_ratings(weights, output_f) -------------------------------------------------------------------------------- /running/MF_time-aware_experiment.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | mkdir ${rootpath}/time-based_split_out-of-matrix/logs 4 | for k in 150 5 | do 6 | for v in 0.1 1 10 7 | do 8 | mkdir ${rootpath}/time-based_split_out-of-matrix/MF_sklearn_K_${k}_V_${v}/ 9 | for fold in 1 2 3 4 6 10 | do 11 | mkdir ${rootpath}/time-based_split_out-of-matrix/MF_sklearn_K_${k}_V_${v}/fold-${fold} 12 | screen -S MF_K_${k}_V_${v}_sklearn_fold_${fold} -dm bash -c "echo I_started; cd /home/alzoghba/ctr-blei; LD_LIBRARY_PATH=/home/alzoghba/gsl/lib; export LD_LIBRARY_PATH; \ 13 | ./ctr-condor --save_lag 40 \ 14 | --user ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-users.dat \ 15 | --item ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-items.dat \ 16 | --directory ${rootpath}/time-based_split_out-of-matrix/MF_sklearn_K_${k}_V_${v}/fold-${fold} \ 17 | --lambda_v ${v} \ 18 | --random_seed 43 --num_factors ${k} > ${rootpath}/time-based_split_out-of-matrix/logs/MF_k_${k}_v_${v}_sklearn_fold_${fold}.out; echo I_finished; exec sh;" 19 | done 20 | done 21 | done 22 | 23 | -------------------------------------------------------------------------------- /running/TCTR_experiment.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | mkdir ${rootpath}/time-based_split_out-of-matrix/logs 4 | for k in 150 5 | do 6 | for v in 1 10 7 | do 8 | for factor in adaptive 0.1 0.5 1 9 | do 10 | mkdir ${rootpath}/time-based_split_out-of-matrix/Factor_${factor}_IE2_temporal_CTR_sklearn_K_${k}_V_${v}/ 11 | for fold in 2 12 | do 13 | mkdir ${rootpath}/time-based_split_out-of-matrix/Factor_${factor}_IE2_temporal_CTR_sklearn_K_${k}_V_${v}/fold-${fold} 14 | screen -S Factor_${factor}_IE2_temporal_CTR_K_${k}_V_${v}_sklearn_fold_${fold} -dm bash -c "echo I_started; cd /home/alzoghba/temporal-ctr-blei; LD_LIBRARY_PATH=/home/alzoghba/gsl/lib; export LD_LIBRARY_PATH; \ 15 | ./ctr-condor --save_lag 40 \ 16 | --user ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-users.dat \ 17 | --user_a ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-users-weights_Factor_${factor}_IE2.dat \ 18 | --item ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-items.dat \ 19 | --item_a ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-items-weights_Factor_${factor}_IE2.dat \ 20 | --directory ${rootpath}/time-based_split_out-of-matrix/Factor_${factor}_IE2_temporal_CTR_sklearn_K_${k}_V_${v}/fold-${fold} \ 21 | --mult ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/mult.dat \ 22 | --theta_init ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/lda_sklearn/theta_${k}.dat \ 23 | --beta_init ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/lda_sklearn/beta_${k}.dat \ 24 | --lambda_v ${v} \ 25 | --random_seed 43 --num_factors ${k} > ${rootpath}/time-based_split_out-of-matrix/logs/factor${factor}_IE2_temporal_ctr_k_${k}_v_${v}_sklearn_fold_${fold}.out; echo I_finished; exec sh;" 26 | done 27 | done 28 | done 29 | done 30 | 31 | -------------------------------------------------------------------------------- /running/TMF_experiment.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | mkdir ${rootpath}/time-based_split_out-of-matrix/logs 4 | for k in 150 5 | do 6 | for v in 0.1 1 10 7 | do 8 | for factor in 0 0.1 0.5 1 9 | do 10 | mkdir ${rootpath}/time-based_split_out-of-matrix/Factor_${factor}_IE2_temporal_MF_sklearn_K_${k}_V_${v}/ 11 | for fold in 5 12 | do 13 | mkdir ${rootpath}/time-based_split_out-of-matrix/Factor_${factor}_IE2_temporal_MF_sklearn_K_${k}_V_${v}/fold-${fold} 14 | screen -S Factor_${factor}_IE2_temporal_MF_K_${k}_V_${v}_sklearn_fold_${fold} -dm bash -c "echo I_started; cd /home/alzoghba/temporal-ctr-blei; LD_LIBRARY_PATH=/home/alzoghba/gsl/lib; export LD_LIBRARY_PATH; \ 15 | ./ctr-condor --save_lag 40 \ 16 | --user ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-users.dat \ 17 | --user_a ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-users-weights_Factor_${factor}_IE2.dat \ 18 | --item ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-items.dat \ 19 | --item_a ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-items-weights_Factor_${factor}_IE2.dat \ 20 | --directory ${rootpath}/time-based_split_out-of-matrix/Factor_${factor}_IE2_temporal_MF_sklearn_K_${k}_V_${v}/fold-${fold} \ 21 | --lambda_v ${v} \ 22 | --random_seed 43 --num_factors ${k} > ${rootpath}/time-based_split_out-of-matrix/logs/factor${factor}_IE2_temporal_MF_k_${k}_v_${v}_sklearn_fold_${fold}.out; echo I_finished;" 23 | done 24 | done 25 | done 26 | done 27 | -------------------------------------------------------------------------------- /running/ctr_time-aware_experiment.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | mkdir ${rootpath}/time-based_split_out-of-matrix/logs 4 | for k in 150 5 | do 6 | for v in 0.001 7 | do 8 | mkdir ${rootpath}/time-based_split_out-of-matrix/CTR_sklearn_K_${k}_V_${v}/ 9 | for fold in 6 10 | do 11 | mkdir ${rootpath}/time-based_split_out-of-matrix/CTR_sklearn_K_${k}_V_${v}/fold-${fold} 12 | screen -S CTR_K_${k}_V_${v}_sklearn_fold_${fold} -dm bash -c "echo I_started; cd /home/alzoghba/ctr-blei; LD_LIBRARY_PATH=/home/alzoghba/gsl/lib; export LD_LIBRARY_PATH; \ 13 | ./ctr-condor --save_lag 40 \ 14 | --user ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-users.dat \ 15 | --item ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/train-items.dat \ 16 | --directory ${rootpath}/time-based_split_out-of-matrix/CTR_sklearn_K_${k}_V_${v}/fold-${fold} \ 17 | --mult ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/mult.dat \ 18 | --theta_init ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/lda_sklearn/theta_${k}.dat \ 19 | --beta_init ${rootpath}/time-based_split_out-of-matrix/fold-${fold}/lda_sklearn/beta_${k}.dat \ 20 | --lambda_v ${v} \ 21 | --random_seed 43 --num_factors ${k} > ${rootpath}/time-based_split_out-of-matrix/logs/ctr_k_${k}_v_${v}_sklearn_fold_${fold}.out; echo I_finished; exec sh;" 22 | done 23 | done 24 | done 25 | 26 | -------------------------------------------------------------------------------- /running/ctr_time-ignorant_experiment.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | mkdir ${rootpath}/in-matrix-item_folds/logs 4 | for k in 400 5 | do 6 | for v in 0.1 7 | do 8 | mkdir ${rootpath}/in-matrix-item_folds/CTR_sklearn_K_${k}_V_${v}/ 9 | for fold in 1 2 3 4 5 10 | do 11 | mkdir ${rootpath}/in-matrix-item_folds/CTR_sklearn_K_${k}_V_${v}/fold-${fold} 12 | screen -S CTR_K_${k}_V_${v}_sklearn_fold_${fold} -dm bash -c "echo I_started; cd /home/alzoghba/ctr-blei; LD_LIBRARY_PATH=/home/alzoghba/gsl/lib; export LD_LIBRARY_PATH; \ 13 | ./ctr-condor --save_lag 40 --directory ${rootpath}/in-matrix-item_folds/CTR_sklearn_K_${k}_V_${v}/fold-${fold} \ 14 | --user ${rootpath}/in-matrix-item_folds/fold-${fold}/train-fold_${fold}-users.dat \ 15 | --item ${rootpath}/in-matrix-item_folds/fold-${fold}/train-fold_${fold}-items.dat \ 16 | --mult ${rootpath}/mult.dat \ 17 | --theta_init ${rootpath}/lda_sklearn/theta_${k}.dat \ 18 | --beta_init ${rootpath}/lda_sklearn/beta_${k}.dat \ 19 | --lambda_v ${v} \ 20 | --random_seed 43 --num_factors ${k} > ${rootpath}/in-matrix-item_folds/logs/ctr_k_${k}_v_${v}_sklearn_fold_${fold}.out; echo I_finished;" 21 | done 22 | done 23 | done 24 | 25 | -------------------------------------------------------------------------------- /running/evaluation_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | 4 | folds=( 6 ) 5 | nu=( 2716 ) 6 | 7 | for exp in CTR_sklearn_K_150_V 8 | do 9 | for v in 0.001 10 | do 11 | for ((i=0;i<${#folds[@]};++i)); do 12 | screen -S temporal_eval_${exp}_${v}_fold${folds[i]} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 13 | python3 /home/alzoghba/Recommender_evaluator/lib/evaluator.py -s -nu ${nu[i]} \ 14 | -es ${rootpath}/time-based_split_out-of-matrix/fold-${folds[i]} \ 15 | -x ${rootpath}/time-based_split_out-of-matrix/${exp}_${v}/fold-${folds[i]}; exec sh;" 16 | done 17 | done 18 | done 19 | -------------------------------------------------------------------------------- /running/evaluation_temporal_run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/home/alzoghba/citeulike_2004_2007 3 | 4 | # folds=( 1 2 3 4 6 ) 5 | # nu=( 173 484 978 1518 2716 ) 6 | folds=( 2 ) 7 | nu=( 484 ) 8 | 9 | for exp in Factor_adaptive_IE2_temporal_CTR_sklearn_K_150_V Factor_0.1_IE2_temporal_CTR_sklearn_K_150_V Factor_0.5_IE2_temporal_CTR_sklearn_K_150_V Factor_1_IE2_temporal_CTR_sklearn_K_150_V 10 | do 11 | for v in 1 10 12 | do 13 | for ((i=0;i<${#folds[@]};++i)); do 14 | screen -S temporal_eval_${exp}_${v}_fold${folds[i]} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 15 | python3 /home/alzoghba/Recommender_evaluator/lib/evaluator.py -s -nu ${nu[i]} \ 16 | -es ${rootpath}/time-based_split_out-of-matrix/fold-${folds[i]} \ 17 | -x ${rootpath}/time-based_split_out-of-matrix/${exp}_${v}/fold-${folds[i]}; exec sh;" 18 | done 19 | done 20 | done 21 | -------------------------------------------------------------------------------- /running/generate_lda_topics.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | rootpath=/vol1/data_anas/citeulike_2004_2007/time-based_split_out-of-matrix 3 | for i in $(seq 6) 4 | #for folder in 2k_40_P3_reduced 2k_40_P5_reduced 2k_40_P10_reduced 5 | do 6 | folder=fold-${i} 7 | screen -S lda_topics_extraction_${folder} -dm bash -c " source /home/alzoghba/HyPRec/py3.5_hyprec/bin/activate; \ 8 | python3 /home/alzoghba/SciPRec_CTR/lib/lda_topics_sklearn.py \ 9 | -o ${rootpath}/${folder}/lda_sklearn \ 10 | -f ${rootpath}/${folder}/mult.dat \ 11 | -v ${rootpath}/${folder}/terms.csv \ 12 | -k 150 ; exec sh;" 13 | done 14 | -------------------------------------------------------------------------------- /util/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/anasalzogbi/T-CTR/25a1d68cc99e4f922e9d155ca99ff9c53effcee8/util/__init__.py -------------------------------------------------------------------------------- /util/evaluation_metrics.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | 4 | 5 | def calculate_mrr(ratings_mat, predictions_mat, top_k, mrr_breaks): 6 | u = 0 7 | mrr_list = [] 8 | for predictions in predictions_mat: 9 | positive_idx = set(ratings_mat[u].nonzero()[0]) 10 | rec_idx = np.argsort(predictions)[::-1][0:top_k] 11 | mrrs = [1/(i+1) if j in positive_idx else 0 for (i,j) in enumerate(rec_idx)] 12 | for i in range(1,len(mrrs)): 13 | mrrs[i] = max(mrrs[i], mrrs[i-1]) 14 | mrr_list.append(np.array(mrrs)[mrr_breaks].tolist()) 15 | u +=1 16 | return np.array(mrr_list) 17 | -------------------------------------------------------------------------------- /util/files_utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | Author: Anas Alzogbi 3 | Description: 4 | This module provides the functionality of: 5 | - Reading and writing ratings file 6 | - Reading and writing docs-topics distribution file 7 | - 8 | Date: October 27th, 2017 9 | alzoghba@informatik.uni-freiburg.de 10 | """ 11 | 12 | import csv 13 | import os 14 | import numpy as np 15 | from enum import Enum 16 | 17 | 18 | class FileFormat(Enum): 19 | """ 20 | This Enum encodes the two csv files format. 21 | """ 22 | # No items ids are stored in the file, the ids match line numbers: 23 | line_num_based = 1 24 | 25 | # First value of each line is the item id, ids don't match line numbers: 26 | id_based = 2 27 | 28 | def read_mappings(mappings_file, delimiter = ",", header= True): 29 | """ 30 | Reads mappings between two valus from file that has two columns. 31 | Returns dictionary, the key is the first column, the value is the second column 32 | """ 33 | dic = {} 34 | with open(mappings_file) as f: 35 | if header: 36 | # Skip the first line, the header: 37 | f.readline() 38 | for line in f: 39 | id1, id2 = line.split(delimiter) 40 | dic[id1.strip()] = int(id2) 41 | return dic 42 | 43 | 44 | def read_ratings(ratings_file, users_num, items_num): 45 | """ 46 | Reads the ratings file into a numpy 2d array 47 | :param ratings_file: the path of the ratings file, the file is expected to be formated as following: 48 | The first entry in line i is the ratings count (n) of user (i), the rest n-length space separated list contains the 49 | item ids rated by user i. 50 | :param users_num: number of users 51 | :param items_num: number of items 52 | :return: numpy 2d array, the ith row contains a list of relevant items ids to user i 53 | """ 54 | ratings_mat = np.zeros((users_num, items_num)) 55 | with open(ratings_file) as f: 56 | user_id = 0 57 | for line in f: 58 | ratings = [int(x) for x in line.replace("\n", "").split(" ")[1:] if x != ""] 59 | for r in ratings: 60 | ratings_mat[user_id, r] = 1 61 | user_id += 1 62 | return ratings_mat 63 | 64 | 65 | def convert(value, type_): 66 | """ 67 | Casts a value into type given in a string (type_) 68 | """ 69 | import importlib 70 | try: 71 | # Check if it's a builtin type 72 | module = importlib.import_module('__builtin__') 73 | cls = getattr(module, type_) 74 | except AttributeError: 75 | # if not, separate module and class 76 | module, type_ = type_.rsplit(".", 1) 77 | module = importlib.import_module(module) 78 | cls = getattr(module, type_) 79 | return cls(value) 80 | 81 | def read_ratings_as_list(ratings_file, type_=int): 82 | """ 83 | Reads the ratings file into a list of lists 84 | :param ratings_file: the path of the ratings file, the file is expected to be formated as following: 85 | The first entry in line i is the ratings count (n) of user (i), the rest n-length space separated list contains the 86 | item ids rated by user i. 87 | :param users_num: number of users 88 | :param items_num: number of items 89 | :return: 2d list, the ith row contains a list of relevant items ids to user i 90 | """ 91 | ratings_list = [] 92 | with open(ratings_file) as f: 93 | for line in f: 94 | ratings = [type_(x) for x in line.replace("\n", "").split(" ")[1:] if x != ""] 95 | ratings_list.append(ratings) 96 | return ratings_list 97 | 98 | 99 | def write_ratings(ratings_list, filename, delimiter=" ", print_line_length=True): 100 | """ 101 | writes user matrix to a file, the file will be formated as following: line i has delimiter-separated list of item ids rated by user i 102 | :param ratings_list: users 2d list, row num = num_users 103 | :param filename: the path of the users file 104 | :param delimiter: default: space 105 | :param print_line_length: if True: the first column of each line will record the line's length 106 | """ 107 | if not os.path.exists(os.path.dirname(filename)): 108 | os.makedirs(os.path.dirname(filename)) 109 | 110 | with open(filename, 'w', newline='') as f: 111 | writer = csv.writer(f, delimiter=delimiter) 112 | for ratings in ratings_list: 113 | if print_line_length: 114 | writer.writerow([len(ratings)] + ratings) 115 | else: 116 | writer.writerow(ratings) 117 | 118 | 119 | def read_docs_topics_file(papers_file, delimiter=" "): 120 | """ 121 | Reads documents latent topics from the file 122 | :param papers_file: file contains papers topics 123 | :param delimiter: The separator used in the file 124 | :return: ndarray (2d), one row for each paper, one column for each topic 125 | """ 126 | papers_list = [] 127 | with open(papers_file) as f: 128 | for line in f: 129 | paper_dis = [float(x) for x in line.replace("\n", "").split(delimiter) if x != ""] 130 | papers_list.append(paper_dis) 131 | # Check if all lines have the same length 132 | if len(set([len(x) for x in papers_list])) > 1: 133 | print("Error in papers file, papers have different number of features: {}".format(papers_file)) 134 | raise ValueError("Error in papers file, papers have different number of features.") 135 | return np.array(papers_list) 136 | 137 | 138 | def print_list(lst): 139 | print('[%s]' % ', '.join(map(str, lst))) 140 | 141 | def read_docs_vocabs_file_as_array(doc_vocab_file, with_header=False, lda_c_format=True, delimiter=' '): 142 | start = 0 143 | # lda-c format: first value of each row is the #vocab 144 | if lda_c_format: 145 | start = 1 146 | doc_vocab = [] 147 | vocabs = set() 148 | with open(doc_vocab_file, 'r') as f: 149 | line_num = 0 150 | if with_header: 151 | next(f) 152 | for line in f: 153 | doc_vector = [] 154 | line_split = line.strip().split(delimiter) 155 | for e in line_split[start:]: 156 | vocab, freq = e.split(":") 157 | try: 158 | vocab = int(vocab) 159 | doc_vector.append((vocab, int(freq))) 160 | vocabs.add(vocab) 161 | except ValueError: 162 | print("Error in doc_vocab file {} : line {}, value {} is not int.".format(doc_vocab_file, line_num, 163 | e)) 164 | raise 165 | doc_vocab.append(doc_vector) 166 | line_num += 1 167 | if (len(vocabs) != max(vocabs) + 1): 168 | print("Error in doc_vocab file {}: # Vocabs = {}, max vocab = {}".format(doc_vocab_file, len(vocabs), 169 | max(vocabs))) 170 | raise ValueError 171 | 172 | mat = np.zeros( (len(doc_vocab), len(vocabs)) ) 173 | doc_idx = 0 174 | for d in doc_vocab: 175 | for e in d: 176 | mat[doc_idx, e[0]] = e[1] 177 | if e[1] <= 0: 178 | print(e[1]) 179 | doc_idx += 1 180 | return mat 181 | 182 | def read_docs_vocabs_file(doc_vocab_file, with_header=False, lda_c_format=True, delimiter=' '): 183 | start = 0 184 | # lda-c format: first value of each row is the #vocab 185 | if lda_c_format: 186 | start = 1 187 | doc_vocab = [] 188 | vocabs = set() 189 | with open(doc_vocab_file, 'r') as f: 190 | line_num = 0 191 | if with_header: 192 | next(f) 193 | for line in f: 194 | doc_vector = [] 195 | line_split = line.strip().split(delimiter) 196 | for e in line_split[start:]: 197 | vocab, freq = e.split(":") 198 | try: 199 | vocab = int(vocab) 200 | doc_vector.append((vocab, int(freq))) 201 | vocabs.add(vocab) 202 | except ValueError: 203 | print("Error in doc_vocab file {} : line {}, value {} is not int.".format(doc_vocab_file, line_num,e)) 204 | raise 205 | doc_vocab.append(doc_vector) 206 | line_num += 1 207 | if (len(vocabs) != max(vocabs) + 1): 208 | print("Error in doc_vocab file {}: # Vocabs = {}, max vocab = {}".format(doc_vocab_file, len(vocabs), 209 | max(vocabs))) 210 | raise ValueError 211 | return doc_vocab 212 | 213 | 214 | 215 | # Writing distributions to the file 216 | def write_distribution(distribution, file_out, delimiter=" "): 217 | with open(file_out, 'w') as f: 218 | for row in distribution: 219 | f.write(delimiter.join([str(j) for j in row]) + "\n") 220 | -------------------------------------------------------------------------------- /util/similarity_metrics.py: -------------------------------------------------------------------------------- 1 | from gensim.matutils import kullback_leibler, jaccard, hellinger 2 | import numpy as np 3 | 4 | 5 | def jensen_shannon_div(P, Q): 6 | """ 7 | Compute the Jensen-Shannon divergence between two probability distributions of equal length. 8 | 9 | ----- 10 | :param P: Probability distributions that sum to 1 11 | :param Q: Probability distributions that sum to 1 12 | :return: float 13 | """ 14 | M = 0.5 * (P + Q) 15 | # return 0.5 * (_kldiv(P, M) +_kldiv(Q, M)) 16 | return 0.5 * (kullback_leibler(P, M) + kullback_leibler(Q, M)) 17 | 18 | 19 | def _kldiv(A, B): 20 | return np.sum([v for v in A * np.log2(A / B) if not np.isnan(v)]) 21 | -------------------------------------------------------------------------------- /util/utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | def convert_to_probability_dist(v): 3 | v_min = v.min(axis = 1)[:, None] 4 | v = (v - v_min) / (v.max(axis=1)[:, None] - v_min) 5 | v = v / v.sum(axis=1)[:, None] 6 | return v 7 | 8 | def kron_A_N(A, N): # Simulates np.kron(A, np.eye(N)) 9 | """ 10 | Source: https://stackoverflow.com/questions/44461658/efficient-kronecker-product-with-identity-matrix-and-regular-matrix-numpy-pyt 11 | One approach would be to initialize an output array of 4D and then assign values into it from A. Such an assignment would broadcast values and this is where we would get efficiency in NumPy. 12 | """ 13 | # Get shape of A 14 | m,n = A.shape 15 | 16 | # Initialize output array as 4D 17 | out = np.zeros((m,N,n,N)) 18 | 19 | # Get range array for indexing into the second and fourth axes 20 | r = np.arange(N) 21 | 22 | # Index into the second and fourth axes and selecting all elements along 23 | # the rest to assign values from A. The values are broadcasted. 24 | out[:,r,:,r] = A 25 | 26 | # Finally reshape back to 2D 27 | out.shape = (m*N,n*N) 28 | return out 29 | 30 | 31 | def calculate_metrics_user(hits, num_user_test_positives, recall_breaks, mrr_breaks, ndcg_breaks): 32 | # Adjust the breaks lists to be 0-based: 33 | recall_breaks = [i - 1 for i in recall_breaks] 34 | mrr_breaks = [i - 1 for i in mrr_breaks] 35 | ndcg_breaks = [i - 1 for i in ndcg_breaks] 36 | iDCGs = np.cumsum(np.array([1 / np.log2(i + 2) for i in range(len(hits))])) 37 | 38 | # Calculate recall: 39 | recall = np.cumsum(hits) 40 | recall_at_breaks = (np.array(recall)[recall_breaks] / float(num_user_test_positives)).tolist() 41 | 42 | # Calculate MRR 43 | mrrs = [hits[i] / float(i + 1) for i in range(len(hits))] 44 | for i in range(1, len(mrrs)): 45 | mrrs[i] = max(mrrs[i], mrrs[i - 1]) 46 | mrrs_at_breaks = np.array(mrrs)[mrr_breaks].tolist() 47 | 48 | # Calculate nDCG 49 | dcgs = [hits[i] / np.log2(i + 2) for i in range(len(hits))] 50 | dcgs = np.array(dcgs) 51 | dcgs = np.cumsum(dcgs) / iDCGs 52 | ndcgs_at_breaks = dcgs[ndcg_breaks].tolist() 53 | return recall_at_breaks + mrrs_at_breaks + ndcgs_at_breaks --------------------------------------------------------------------------------