-
Notifications
You must be signed in to change notification settings - Fork 1
/
pmf.c
735 lines (478 loc) · 17.9 KB
/
pmf.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
/* This file is part of SocialFALCON matrix factorization algorithms code contribution
SocialFALCON is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
SocialFALCON is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
See <http://www.gnu.org/licenses/>
Authors: N. Ampazis and T. Emmanouilidis (2018)
Original codebase contribution by George Tsagas
Revision:1
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <stdarg.h>
#include <mysql.h>
#define PREDICTION_MODE 0
#define MIN_EPOCHS 10 // Minimum number of epochs per feature
#define MAX_EPOCHS 10 // Max epochs per feature
#define MIN_IMPROVEMENT 0.00005 // Minimum improvement required to continue current feature
#define INIT_SEED_Mb -0.3 // sqrtf(GLOBAL_AVERAGE/(float)TOTAL_FEATURES) // Initialization value for features
#define INIT_VARIANCE_Mb 0.20 // variance range from the INIT_SEED value
#define INIT_Mb (INIT_SEED_Mb + (2.0*(rand()/(float)(RAND_MAX)) - 1.0)*INIT_VARIANCE_Mb) // INIT + rand[-INIT_VARIANCE, +INIT_VARIANCE]
#define INIT_SEED_Cb 0.0 // sqrtf(GLOBAL_AVERAGE/(float)TOTAL_FEATURES) // Initialization value for features
#define INIT_VARIANCE_Cb 0.010 // variance range from the INIT_SEED value
#define INIT_Cb (INIT_SEED_Cb + (2.0*(rand()/(float)(RAND_MAX)) - 1.0)*INIT_VARIANCE_Cb) // INIT + rand[-INIT_VARIANCE, +INIT_VARIANCE]
#define INIT_SEED_M 0.0 // sqrtf(GLOBAL_AVERAGE/(float)TOTAL_FEATURES) // Initialization value for features
#define INIT_VARIANCE_M 0.001 // variance range from the INIT_SEED value
#define INIT_M (INIT_SEED_M + (2.0*(rand()/(float)(RAND_MAX)) - 1.0)*INIT_VARIANCE_M) // INIT + rand[-INIT_VARIANCE, +INIT_VARIANCE]
#define INIT_SEED_C 0.0 // sqrtf(GLOBAL_AVERAGE/(float)TOTAL_FEATURES) // Initialization value for features
#define INIT_VARIANCE_C 0.001 // variance range from the INIT_SEED value
#define INIT_C (INIT_SEED_C + (2.0*(rand()/(float)(RAND_MAX)) - 1.0)*INIT_VARIANCE_C) // INIT + rand[-INIT_VARIANCE, +INIT_VARIANCE]
double LRATE1u = 0.005; // Learning rate parameter for features
double LAMDA1u = 0.1; // reg for features
double LRATE1m = 0.005; // Learning rate parameter for features
double LAMDA1m = 0.1; // reg for features
double LRATE2ub = 0.005; // Learning rate parameter for biases
double LAMDA2ub = 0.01; // reg for biases
double LRATE2mb = 0.005; // Learning rate parameter for biases
double LAMDA2mb = 0.01; // reg for biases
struct connection_details
{
char *server;
char *user;
char *password;
char *database;
};
MYSQL* mysql_connection_setup(struct connection_details mysql_details)
{
// first of all create a mysql instance and initialize the variables within
MYSQL *connection = mysql_init(NULL);
// connect to the database with the details attached.
if (!mysql_real_connect(connection,mysql_details.server, mysql_details.user, mysql_details.password, mysql_details.database, 0, NULL, 0)) {
printf("Conection error : %s\n", mysql_error(connection));
exit(1);
}
return connection;
}
MYSQL_RES* mysql_perform_query(MYSQL *connection, char *sql_query)
{
// send the query to the database
if (mysql_query(connection, sql_query))
{
printf("MySQL query error : %s\n", mysql_error(connection));
exit(1);
}
return mysql_use_result(connection);
}
float randn(void);
void float_array_fill_zeros (float *my_array, unsigned int size_of_my_array);
double predict_svd_rating (int movieId, int custId, int TOTAL_FEATURES);
int rnd(int max);
void create_txt_file ();
void write_txt_file (unsigned int customer_id, unsigned short movie_id);
void close_txt_file ();
void calc_features(int TOTAL_FEATURES);
double sigmoid (double alpha);
double sign (double x);
FILE *lgfile=NULL;
void lg(char *fmt,...);
void lgopen(int argc, char**argv);
void error(char *fmt,...);
float final_probe_rmse=0.0;
unsigned int final_epochs_for_probe;
//////////////////////////database connection///////////////////////////////////////
char query_string[200];
MYSQL *conn; // the connection
MYSQL_RES *res; // the results
MYSQL_ROW row; // the results row (line by line)
struct connection_details mysqlD;
int TOTAL_MOVIES;
int TOTAL_CUSTOMERS;
int TOTAL_RATES;
int TOTAL_PROBES;
float GLOBAL_AVERAGE;
double GLOBAL_SCALED_AVERAGE;
int min_r,max_r, rating_range;
double avg;
// ****** SVD *********** //
float **movie_features; // Array of features by movie (using floats to save space)
float **cust_features; // Array of features by customer (using floats to save space)
float *m_bias;
float *c_bias;
// ******************** //
int **user_movies;
int *user_movies_size;
int **user_ratings;
// *** PROBE ***//
int *probe_customers;
int *probe_movies;
int *probe_real_scores;
// *** //
char algorithm_name[20];
main (int argc, char**argv) {
lgopen(argc,argv);
float prediction;
unsigned int i,h;
time_t start, stop;
double diff;
int TOTAL_FEATURES = atoi(argv[5]);
/* start timer */
start = time(NULL);
mysqlD.server = argv[1]; // where the mysql database is
mysqlD.user = argv[2]; // the root user of mysql
mysqlD.password = argv[3]; // the password of the root user in mysql
mysqlD.database = argv[4]; // the databse to pick
// connect to the mysql database
conn = mysql_connection_setup(mysqlD);
sprintf(query_string,"SELECT count(DISTINCT item_id) FROM ratings");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
TOTAL_MOVIES=atoi(row[0]);
}
//clean up the database result set
mysql_free_result(res);
sprintf(query_string,"SELECT count(DISTINCT user_id) FROM user_mapping");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
TOTAL_CUSTOMERS=atoi(row[0]);
}
//clean up the database result set
mysql_free_result(res);
sprintf(query_string,"SELECT count(*) FROM train");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
TOTAL_RATES=atoi(row[0]);
}
//clean up the database result set
mysql_free_result(res);
sprintf(query_string,"SELECT count(*) FROM probe");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
TOTAL_PROBES=atoi(row[0]);
}
//clean up the database result set
mysql_free_result(res);
sprintf(query_string,"SELECT avg(rating_value) FROM train");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
GLOBAL_AVERAGE=atof(row[0]);
}
//clean up the database result set
mysql_free_result(res);
// Get maximum and minimum ratings from the ratings table
sprintf(query_string,"SELECT MAX(rating_value) FROM ratings");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
max_r=atoi(row[0]);
}
/* clean up the database result set */
mysql_free_result(res);
sprintf(query_string,"SELECT MIN(rating_value) FROM ratings");
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
min_r=atoi(row[0]);
}
/* clean up the database result set */
mysql_free_result(res);
rating_range=max_r-min_r;
avg = (GLOBAL_AVERAGE - min_r) / rating_range;
GLOBAL_SCALED_AVERAGE = log(avg / (1 - avg));
// ****** SVD *********** //
movie_features = ( float** )malloc(TOTAL_MOVIES * sizeof(float *));
if(movie_features == NULL)
{
fprintf(stderr, "out of memory\n");
exit(-1);
}
for(i = 0; i < TOTAL_MOVIES; i++)
{
movie_features[i] = ( float* )malloc(TOTAL_FEATURES * sizeof(float));
if(movie_features[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(-1);
}
}
cust_features = ( float** )malloc(TOTAL_CUSTOMERS * sizeof(float *));
if(cust_features == NULL)
{
fprintf(stderr, "out of memory\n");
exit(-1);
}
for(i = 0; i < TOTAL_CUSTOMERS; i++)
{
cust_features[i] = ( float* )malloc(TOTAL_FEATURES * sizeof(float));
if(cust_features[i] == NULL)
{
fprintf(stderr, "out of memory\n");
exit(-1);
}
}
m_bias = (float *)malloc(sizeof(float)*TOTAL_MOVIES);
c_bias = (float *)malloc(sizeof(float)*TOTAL_CUSTOMERS);
// ***************** //
user_movies = ( int** )malloc(TOTAL_CUSTOMERS * sizeof(int *));
if(user_movies == NULL)
{
fprintf(stderr, "out of memory for user connections\n");
exit(-1);
}
user_movies_size = (int *)malloc(sizeof(int)*TOTAL_CUSTOMERS);
user_ratings = ( int** )malloc(TOTAL_CUSTOMERS * sizeof(int *));
if(user_ratings == NULL)
{
fprintf(stderr, "out of memory for user connections\n");
exit(-1);
}
/* stop timer and display time */
stop = time(NULL);
diff = difftime(stop, start);
// *** CREATE PROBE *** //
/* start timer */
start = time(NULL);
probe_customers = (int *)malloc(sizeof(int)*TOTAL_PROBES);
probe_movies = (int *)malloc(sizeof(int)*TOTAL_PROBES);
probe_real_scores = (int *)malloc(sizeof(int)*TOTAL_PROBES);
sprintf(query_string,"select user_id,item_id,rating_value FROM probe");
res = mysql_perform_query(conn,query_string);
h=0;////just a counter
while ((row = mysql_fetch_row(res)) !=NULL) {
probe_customers[h]=atoi(row[0]);
probe_movies[h]=atoi(row[1]);
probe_real_scores[h]=atoi(row[2]);
h++;
}
// ******************** //
/* stop timer and display time */
stop = time(NULL);
diff = difftime(stop, start);
// start timer
start = time(NULL);
// RUN SVD
sscanf(argv[0], "./%s", algorithm_name);
lg("%s\t\t",algorithm_name);
calc_features(TOTAL_FEATURES);
/* stop timer and display time */
stop = time(NULL);
diff = difftime(stop, start);
lg("%f sec\n", diff);
exit(-1);
// *** SAVE FEATURES ***
// stop timer and display time
stop = time(NULL);
diff = difftime(stop, start);
exit(0);
}
//****** SVD *********
void calc_features(int TOTAL_FEATURES) {
time_t start, stop, start_e, stop_e;
double avg_diff=0.0;
double diff;
int c, d, h,f, e, i, custId, cnt = 0;
int num_movies;
double err, err2, p, sq, rmse_last, rmse = 2.0, probe_rmse=9998, probe_rmse_last=9999, probe_sq;
int movieId;
double cf, mf, cf_bias, mf_bias;
// INIT all feature values
for (f=0; f<TOTAL_FEATURES; f++) {
for (i=0; i<TOTAL_MOVIES; i++) {
movie_features[i][f] = INIT_M;
}
for (i=0; i<TOTAL_CUSTOMERS; i++) {
cust_features[i][f] = INIT_C;
}
}
// *** INIT biases
for (i=0; i<TOTAL_MOVIES; i++) {
m_bias[i] = INIT_Mb;
}
for (i=0; i<TOTAL_CUSTOMERS; i++) {
c_bias[i] = INIT_Cb;
}
////////////////First we count how many users exist in our dataset and store them
sprintf(query_string,"SELECT COUNT(DISTINCT user_id) FROM user_mapping");
res = mysql_perform_query(conn,query_string);
int num_train_users;
while ((row = mysql_fetch_row(res)) !=NULL) {
num_train_users=atoi(row[0]);
}
/* clean up the database result set */
mysql_free_result(res);
//////////Now we select all train users and store them in an array
int *train_users_id;
train_users_id = (int *)malloc(sizeof(int)*num_train_users);
///The select query
sprintf(query_string,"SELECT DISTINCT(user_id) FROM user_mapping");
res = mysql_perform_query(conn,query_string);
///fetch all selected rows
h=0;////just a counter
while ((row = mysql_fetch_row(res)) !=NULL) {
train_users_id[h]=atoi(row[0]);
h++;
}
//exit(-1);
/* clean up the database result set */
mysql_free_result(res);
////////Now we have the train set users stored
for (c=0; c < num_train_users; c++) {
custId = train_users_id[c];
//////Find out how many movies the user have rated
sprintf(query_string,"select count(item_id) FROM train WHERE user_id=%d",custId);
res = mysql_perform_query(conn,query_string);
while ((row = mysql_fetch_row(res)) !=NULL) {
num_movies=atoi(row[0]);
}
/* clean up the database result set */
mysql_free_result(res);
user_movies_size[c] = num_movies;
if (num_movies!=0) {
user_movies[c] = ( int* )malloc(num_movies * sizeof(int));
if(user_movies[c] == NULL)
{
fprintf(stderr, "out of memory for connections of customer %d\n", custId);
exit(-1);
}
user_ratings[c] = ( int* )malloc(num_movies * sizeof(int));
if(user_ratings[c] == NULL)
{
fprintf(stderr, "out of memory for connections of customer %d\n", custId);
exit(-1);
}
}
/////select and store the movies and ratings the user have rated
sprintf(query_string,"select item_id, rating_value FROM train WHERE user_id=%d",custId);
res = mysql_perform_query(conn,query_string);
h=0;////just a counter
while ((row = mysql_fetch_row(res)) !=NULL) {
user_movies[c][h]=atoi(row[0]);
user_ratings[c][h]=atoi(row[1]);
h++;
}
/* clean up the database result set */
mysql_free_result(res);
}
// Keep looping until you have stopped making significant (probe_rmse) progress
while ((probe_rmse < probe_rmse_last - MIN_IMPROVEMENT)) {
start = time(NULL);
start_e = time(NULL);
cnt++;
sq = 0;
probe_sq = 0;
rmse_last = rmse;
probe_rmse_last = probe_rmse;
/////////////////Here starts primary iteration to users
///////continue with the train iteration
for (c=0; c < num_train_users; c++) {
d=c;
custId = train_users_id[c];
if (user_movies_size[c]!=0) {
for (i=0; i< user_movies_size[c]; i++) {
movieId=user_movies[c][i];
p = predict_svd_rating (movieId, custId, TOTAL_FEATURES);
err = ((float)user_ratings[c][i] - p);
err2 = ((double)user_ratings[c][i] - (rating_range*p + min_r));
sq += err2*err2;
//*** train biases
cf_bias = c_bias[custId - 1];
mf_bias = m_bias[movieId - 1];
c_bias[custId - 1] += (LRATE2ub * (err2 * rating_range * p * (1.0 - p) - LAMDA2ub * cf_bias));
m_bias[movieId - 1] += (LRATE2mb * (err2 * rating_range * p * (1.0 - p) - LAMDA2mb * mf_bias));
for (f=0; f<TOTAL_FEATURES; f++) {
// Cache off old feature values
cf = cust_features[custId - 1][f];
mf = movie_features[movieId - 1][f];
cust_features[custId - 1][f] += (LRATE1u * (err2 * rating_range * p * (1.0 - p) * mf - LAMDA1u * cf));
movie_features[movieId - 1][f] += (LRATE1m * (err2 * rating_range * p * (1.0 - p) * cf - LAMDA1m * mf));
}
}
}
if ((d!=0) && (d%1000000 == 0)){
stop = time(NULL);
diff = difftime(stop,start);
start = time(NULL);
}
}
char probes_file[80];
char str_features[20];
sprintf(str_features,"%d",TOTAL_FEATURES);
strcpy (probes_file, str_features);
strcat (probes_file, "-");
strcat (probes_file, mysqlD.database);
strcat (probes_file, "-");
strcat (probes_file, algorithm_name);
strcat (probes_file, ".txt");
FILE *fp = fopen(probes_file,"w");
for (i=0; i < TOTAL_PROBES; i++) {
movieId = probe_movies[i];
custId = probe_customers[i];
// Predict rating and calc error
p = predict_svd_rating (movieId, custId, TOTAL_FEATURES);
p = (rating_range*p + min_r);
//Write data to file
fprintf(fp,"%d,%d,%d,%f\n",custId,movieId,probe_real_scores[i],p);
err = ((float)probe_real_scores[i] - p);
probe_sq += err*err;
}
//close file
fclose(fp);
// stop timer and display time
stop_e = time(NULL);
diff = difftime(stop_e, start_e);
rmse = sqrt(sq/TOTAL_RATES);
probe_rmse = sqrt(probe_sq/TOTAL_PROBES);
avg_diff+=diff;
}
final_probe_rmse = probe_rmse;
final_epochs_for_probe = cnt;
lg("%f\t\t%d\t\t%f sec\t\t", cnt,probe_rmse,avg_diff/cnt);
/* clean up the database link */
mysql_close(conn);
}
double predict_svd_rating (int movieId, int custId, int TOTAL_FEATURES) {
int f;
float sum = 0.0;
for (f=0; f<TOTAL_FEATURES; f++) {
sum += movie_features[movieId - 1][f] * cust_features[custId - 1][f];
}
sum += c_bias[custId - 1] + m_bias[movieId - 1];
// *** Add residuals
sum += GLOBAL_SCALED_AVERAGE;
return sigmoid(sum);
}
double sigmoid (double alpha) {
return 1.0/(1.0+exp(-alpha));
}
double sign (double x) {
if (x>=0)
return 1;
else
return 0;
}
void lgopen(int argc, char**argv) {
lgfile=fopen("log.txt","a");
if(!lgfile) error("Cant open log file");
time_t curtime=time(NULL);
}
void lg(char *fmt,...) {
char buf[2048];
va_list ap;
va_start(ap, fmt);
vsprintf(buf,fmt,ap);
va_end(ap);
fprintf(stderr,"%s",buf);
if(lgfile) {
fprintf(lgfile,"%s",buf);
fflush(lgfile);
}
}
void error(char *fmt,...) {
char buf[2048];
va_list ap;
va_start(ap, fmt);
vsprintf(buf,fmt,ap);
va_end(ap);
lg("%s",buf);
lg("\n");
exit(1);
}