-
Notifications
You must be signed in to change notification settings - Fork 0
/
algorithm.R
2366 lines (2065 loc) · 86.4 KB
/
algorithm.R
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
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# memory.limit( size = 128000 ) # not needed when working with 'dev_subset', the development data subset
if( !require( caret ) ) { install.packages( "caret" ) } ; library( caret ) # to create folds
if( !require( tidyverse ) ) { install.packages( "tidyverse" ) } ; library( tidyverse )
if( !require( data.table ) ) { install.packages( "data.table" ) } ; library( data.table )
if( !require( scales ) ) { install.packages( "scales" ) } ; library( scales ) # for plot axis formatting (percentages, mostly)
if( !require( lubridate ) ) { install.packages( "lubridate" ) } ; library( lubridate ) # for the 'seconds_to_period' function
if( !require( gridExtra ) ) { install.packages( "gridExtra" ) } ; library( gridExtra ) # to organize plots
if( !require( coop ) ) { install.packages( "coop" ) ; library( coop ) } # for fast pairwise.complete cosine similarity
if( !require( stats ) ) { install.packages( "stats" ) ; library( stats ) } # for primary components decomposition
# Building R for Windows ; @see 'https://cran.r-project.org/bin/windows/Rtools/'
if( !require( devtools ) ) { install.packages( "devtools" ) } ; library( devtools )
if( devtools::find_rtools( debug = TRUE ) ) {
if( !require( Rcpp ) ) { install.packages( "Rcpp" ) } ; library( Rcpp )
Sys.setenv("PKG_CXXFLAGS"="-std=c++11") # C++11 ; @see 'http://gallery.rcpp.org/articles/first-steps-with-C++11/'
}
##################################################
## 'amc_pdf_print' function ##
##################################################
# convenience method to print the pdf report #
# with (optional) input parameters. #
# In addition, allows to access #
# 'global environment' variables from within #
# the 'report printing' session (thus avoiding #
# to train a model each time). #
##################################################
amc_pdf_print <- function(
paramsList = NULL
, SumatraPDF_fullpath =
"C:/PROGRA~1/RStudio/bin/sumatra/SumatraPDF.exe "
, rootFolderPath = getwd()
) {
t1 <- proc.time()
outfile <- file.path( rootFolderPath, "Report.pdf" )
rmarkdown::render(
input = file.path( rootFolderPath, "/Report.Rmd" )
, params = paramsList
, encoding = "UTF-8"
, output_file = outfile )
print( ( proc.time() - t1 )[ "elapsed" ] ) # > 40''
cmd = paste0(
SumatraPDF_fullpath
, "\"", outfile, "\"" )
shell( cmd = cmd, intern = FALSE, wait = FALSE )
}
##################################################
##############################
## SOURCE DATA FORMAT BEGIN ##
##############################
URL <- "http://files.grouplens.org/datasets/movielens/ml-10m.zip"
fil <- basename( URL )
datFil <- paste0( getwd()
, .Platform$file.sep, "orig" )
if( !file.exists( fil ) ) download.file( URL, fil )
if (!dir.exists( datFil ) ) unzip( fil, exdir = datFil )
datFil <- paste0( getwd()
, .Platform$file.sep, "orig"
, .Platform$file.sep, "ml-10M100K" )
ratings <- fread( input = paste0( datFil, .Platform$file.sep, "ratings.dat" )
, sep = ":"
, drop = c( 2, 4, 6 )
, col.names = c( "userId", "movieId"
, "rating", "timestamp" ))
#View( head( ratings ) )
movies <- str_split_fixed(
readLines( paste0( datFil, .Platform$file.sep, "movies.dat" ) )
, "\\::"
, 3 )
colnames( movies ) <- c("movieId", "title", "genres")
movies <- as.data.frame( movies ) %>%
mutate( movieId = as.numeric( levels( movieId ) )[ movieId ]
, title = as.character( title )
, genres = as.character( genres ) )
#str( movies ) ; View( head( movies ) )
movielens <- left_join( ratings, movies, by = "movieId" )
# "Validation" set will be 10% of 'MovieLens (10M)' data
# => 999,999 observations
set.seed( 1 )
test_index <- createDataPartition( y = movielens$rating
, times = 1, p = 0.1, list = FALSE )
edx <- movielens[ -test_index, ]
temp <- movielens[ test_index, ]
# Make sure 'userId' and 'movieId' in "validation" set
# are also in "edx" set :
validation <- temp %>%
semi_join( edx, by = "movieId" ) %>%
semi_join( edx, by = "userId" )
# Add rows removed from "validation" set back into "edx" set
removed <- anti_join( temp, validation, by = c( "movieId", "userId" ) )
edx <- bind_rows( edx, removed ) # rbind( edx, removed )
rm( datFil, fil, URL
, movielens, movies, ratings, removed, temp, test_index )
##############################
## SOURCE DATA FORMAT END ##
##############################
mean( edx$rating ) # 3.512465
############################################
# create indices for our "k" folds #
# (used in our "k-folds cross-validation") #
############################################
t1 <- proc.time()
set.seed( 1806 )
cv_k <- 10
folds <- createFolds( y = edx$rating
, k = cv_k
, list = TRUE
, returnTrain = FALSE )
#?createFolds # segment the data by fold for "k-fold cross validation"
print( ( proc.time() - t1 )[ "elapsed" ] ) # elapsed 575.35
#str( folds ) ; View( head( folds ) ) # str( edx$movieId ) # str( edx$userId )
############################################
###################################################
# for development purpose, declare 'dev_subset' #
# a subset of the source dataset #
# #
# (so as to use that subset while developing and, #
# later run the entire code with the whole thing #
# once ready) #
###################################################
dev_subset <-
edx %>%
filter( userId %in% sample( unique( edx$userId )
, size = 500, replace = FALSE ) )
# random variable ; between 5k and 10k distinct movies
length( unique( dev_subset$movieId ) )
# random variable ; around 60,000 ratings:
nrow( dev_subset )
# random variable ; around {3.50 - 3.60} stars
mean( dev_subset$rating )
# "Validation" set will be 10% of 'MovieLens (10M)' data
# => 999,999 observations
set.seed( 1 )
dev_validation_index <- createDataPartition( y = dev_subset$rating
, times = 1, p = 0.1, list = FALSE )
temp <- dev_subset[ dev_validation_index, ]
dev_subset <- dev_subset[ -dev_validation_index, ]
# Make sure 'userId' and 'movieId' in "validation" set
# are also in "edx" set :
dev_validation <- temp %>%
semi_join( dev_subset, by = "movieId" ) %>%
semi_join( dev_subset, by = "userId" )
# Add rows removed from "validation" set back into "dev_subset" set
removed <- anti_join( temp, dev_validation, by = c( "movieId", "userId" ) )
dev_subset <- bind_rows( dev_subset, removed ) # rbind( dev_subset, removed )
rm( removed, temp, dev_validation_index )
## corresponding 'test' subsubset index:
# dev test sub_subset approx. 10% of 'dev_subset'
dev_folds <- createFolds( y = dev_subset$rating
, k = cv_k
, list = TRUE
, returnTrain = FALSE )
rm( cv_k )
###################################################
## ########################################
## 'RMSE' function ##
###########################################
# a function that computes the "RMSE" #
# for vectors of "ratings" #
# and their corresponding "predictions" : #
# REMINDER: we're optimizing our model #
# against the RMSE metric. #
###########################################
RMSE <- function( true_ratings, predicted_ratings ) {
sqrt( mean( ( true_ratings - predicted_ratings )^2 ) ) }
###########################################
## ##############################################
## 'to_rating' function ##
#################################################
# converts continuous values to 'stars rating' #
# discreet unit movielens ratings ranging #
# from "0.5" to "5" stars (with step: 0.5 stars)#
#################################################
# ?round_any
# Rounding to the nearest 5
# @see 'http://r.789695.n4.nabble.com/Rounding-to-the-nearest-5-td863189.html#message863190'
to_rating <- function( x ) { max( min( ( .5 * round( x / .5 ) ), 5 ), .5 ) }
#to_rating( 4.75 ) ; to_rating( 4.25 ) ; to_rating( 4.3 ) ; to_rating( 4.1 ) ; to_rating( -.88 ) ; to_rating( .88 )
data.frame( raw_prediction = seq( -1, 6, by = .01 ), to_rating = mapply( seq( -1, 6, by = .01 ), FUN = to_rating ) ) %>%
ggplot( aes( x = raw_prediction, y = to_rating ) ) +
geom_hline( yintercept = 0 ) + geom_vline( xintercept = 0 ) +
scale_y_continuous( limits = c( 0, 5.1 ), breaks = seq( 0, 5, by = .5 ), expand=c( 0, 0 ) ) +
scale_x_continuous( limits = c( -1, 6 ), breaks = seq( 0, 6, by = 1 ), expand=c( 0, 0 ) ) +
coord_fixed() + theme_bw() +
theme( panel.grid.minor = element_blank(), panel.border = element_blank()
, axis.line = element_line( colour = "black" ) ) +
xlab( "raw_prediction (continuous variable)" ) + geom_point()
#################################################
## #######################################################
## 'duration_string' function ##
##########################################################
# convenience method to custom-format duration strings #
##########################################################
duration_string <- function(
time_start
, time_end = proc.time()
) {
td <- as.POSIXlt( ( time_end - time_start )[ "elapsed" ]
, origin = lubridate::origin )
round( second( td ) ) -> second( td )
td <- seconds_to_period( td )
return( tolower( td ) )
}
##########################################################
## #######################################################
## 'get_regularization_optimization' function ##
##########################################################
# optimization procedure for the hyperparameter "lambda" #
# (regularization penalty term) #
##########################################################
# inputs : #
# - "train_set" - the source data : #
# user/movie ratings in tidy format #
# with the following column names : #
# o "userId", "movieId", "title", "rating" #
# - "test_set" data points used #
# to generate predictions (to be compared #
# against 'true ratings' #
# - "lambdas" list of different values #
# to be considered for "lambda" #
# (primary components count) #
# - "print_comments" do (or not) show #
# progress info on the console #
##########################################################
# resultset (list of objects) : #
# - "mu_hat", "movie_avgs" and "user_avgs" #
# regularization parameters #
# - "lambda" - the optimum parameter value #
# - "lambda_optimization" #
# the "RMSE" versus "k" dataset #
##########################################################
get_regularization_optimization <- function(
train_set
, test_set = NULL
, lambdas
, print_comments = FALSE
) {
t2 <- proc.time()
optimization_mode <- ( !is.null( test_set ) &
"rating" %in% colnames( test_set ) )
if( !optimization_mode ) lambdas[ 1 ] -> lambdas
# estimated average user/movie rating
mu_hat = mean( train_set$rating )
# movie effect & user effect
# Regularization via optimizing it against the Penalized Least Squares
# Choosing the "penalty" term lambda
if( print_comments ) cat( paste0(
"Regularization - computing \"movie\" & \"user\" effects:\n|"
, paste( rep( "=", length( lambdas ) ), collapse = "" )
, "|\n|" ) )
models_lambdas_rmses <- sapply( lambdas, function( l ){
b_i_hat_l <- train_set %>%
group_by( movieId ) %>%
summarize( b_i_hat =
sum( rating - mu_hat ) /
( n() + l )
, title = title[ 1 ]
)
b_u_hat_l <- train_set %>%
left_join( b_i_hat_l, by = "movieId" ) %>%
group_by( userId ) %>%
summarize( b_u_hat =
sum( rating - b_i_hat - mu_hat ) /
( n() + l ) )
if( !is.null( test_set ) ) {
predicted_ratings <- test_set %>%
left_join( b_i_hat_l, by = "movieId" ) %>%
left_join( b_u_hat_l, by = "userId" ) %>%
mutate( pred = mu_hat + b_i_hat + b_u_hat ) %>%
.$pred
}
if( print_comments ) cat( "-" )
return( list(
b_i_hat_l = b_i_hat_l
, b_u_hat_l = b_u_hat_l
, RMSE_l = switch( optimization_mode + 1
, NULL # returns "NULL" if "!optimization_mode"
, RMSE( test_set$rating, predicted_ratings ) ) ) )
} )
if( print_comments ) cat( "|" )
models_lambdas_rmses <- data.frame( t( models_lambdas_rmses ) )
#View( models_lambdas_rmses )
if( optimization_mode ) {
optimized_index <- which.min( models_lambdas_rmses$RMSE_l )
lambda <- lambdas[ optimized_index ]
movie_avgs <- models_lambdas_rmses$b_i_hat_l[ optimized_index ][[ 1 ]]
user_avgs <- models_lambdas_rmses$b_u_hat_l[ optimized_index ][[ 1 ]]
lambda_optimization <-
cbind( lambda = lambdas
, RMSE = models_lambdas_rmses %>% select( RMSE_l ) %>% unlist )
rm( optimized_index )
} else {
movie_avgs <- models_lambdas_rmses$b_i_hat_l[ 1 ][[ 1 ]]
user_avgs <- models_lambdas_rmses$b_u_hat_l[ 1 ][[ 1 ]]
lambda <- lambdas
lambda_optimization <- NULL
}
setDT( movie_avgs, key = c( "movieId" ) )
setDT( user_avgs, key = c( "userId" ) )
if( print_comments ) cat( paste0(
" done (", duration_string( t2 ), ")\n" ) )
rm( lambdas, models_lambdas_rmses, t2 )
gc( reset = FALSE, full = TRUE, verbose = FALSE )
return( list( mu_hat = mu_hat
, user_avgs = user_avgs
, movie_avgs = movie_avgs
, lambda = lambda
, lambda_optimization = lambda_optimization
) )
}
##########################################################
## #################################################
## 'get_regularization_residuals_matrix' function ##
####################################################
# inputs : #
# - "train_set" - the source data : #
# user/movie ratings in tidy format #
# with the following column names : #
# o "userId", "movieId", "rating" #
# - "mu_hat", "movie_avgs" and "user_avgs" ; #
# the Regularization parameters #
# - "print_comments" do (or not) show progress #
# info on the console #
####################################################
# resultset : a matrix made up of the user/movie #
# rating residuals (e.g. the error/loss from #
# the Regularization) #
####################################################
get_regularization_residuals_matrix <- function(
train_set
, mu_hat
, b_u_hat
, b_i_hat
, print_comments = FALSE
) {
# formating into a matrix of ratings
t2 <- proc.time()
if( print_comments ) cat( paste0(
"Turning tidy dataset into matrix of ratings :\n|"
, paste( rep( "=", 4 ), collapse = "" )
, "|\n|" ) )
ratings_matrix <-
train_set %>%
select( userId, movieId, rating ) %>%
spread( movieId, rating ) %>%
as.matrix()
if( print_comments ) cat( "-" )
rownames( ratings_matrix ) <- ratings_matrix[ , 1 ]
ratings_matrix <- ratings_matrix[ , -1 ]
#View( x = head( ratings_matrix[ , 1:10 ], 20 ), title = "train_set_matrix" )
if( print_comments ) cat( "-" )
# transforming into a matrix of residuals
# remainder from the "Regularization" approximation
# (eg. modeling error/loss)
residuals_matrix <- ratings_matrix
rm( train_set, ratings_matrix )
gc( reset = FALSE, full = TRUE )
residuals_matrix <-
sweep( residuals_matrix - mu_hat
, 2, b_i_hat )
if( print_comments ) cat( "-" )
residuals_matrix <-
sweep( residuals_matrix
, 1, b_u_hat )
rm( mu_hat, b_i_hat, b_u_hat )
gc( reset = FALSE, full = TRUE )
if( print_comments ) cat( paste0(
"-| done (", duration_string( t2 ), ").\n" ) )
#View( head( residuals_matrix[ , 1:10 ], 20 ) )
return( residuals_matrix )
}
####################################################
## ####################################################
## 'get_knn_predictions' function ##
#######################################################
# Rcpp implementation #
# for each "userId"/movieId" pair of the test domain, #
# returns one rating prediction #
# per value of the "ks" vector #
# (Rcpp function called inside #
# the R 'get_knn_optimization' function) #
#######################################################
# inputs : #
# - "ks" list of different values #
# to be considered for "k" (neighbors count) #
# - "test_sim_matrix" similarity matrix #
# for the "test" movies (one per column) #
# - "test_ratings_matrix" rating matrix #
# for the "test" users, all movies included #
# (from which "neighbor" ratings are picked) #
# - "test_domain" list of "userId"/movieId" pairs #
# (for which a prediction is expected) #
# - "print_comments" do (or not) show #
# progress info on the console #
#######################################################
# resultset (tidy format ; 4 columns) : #
# - "userId" #
# - "movieId" #
# - "k" #
# - "prediction" #
#######################################################
{
Rcpp::sourceCpp( code =
'
#include <Rcpp.h>
#include <queue>
#include <string> // std::string, std::stoi
using namespace Rcpp;
using namespace std;
std::string duration_string( const float duration_seconds ) {
int hours, minutes;
minutes = duration_seconds / 60;
hours = minutes / 60;
char hours_numstr[ 3 ];
if( hours > 0 ) sprintf(hours_numstr, "%u", int(hours));
std::string hours_suffixe = "h ";
std::string hours_result = hours > 0 ? hours_numstr + hours_suffixe : "";
char minutes_numstr[ 3 ];
if( minutes > 0 ) sprintf(minutes_numstr, "%u", int(minutes%60));
std::string minutes_suffixe = "m ";
std::string minutes_result =
(hours > 0) | (minutes > 0) ? hours_result + minutes_numstr + minutes_suffixe : hours_result;
char seconds_numstr[ 5 ];
if( (hours > 0) | (minutes > 0) ) {if( duration_seconds > 0 ) sprintf(seconds_numstr, "%u", int(duration_seconds)%60%60);}
else { if( duration_seconds > 0 ) sprintf(seconds_numstr, "%.2f", duration_seconds); }
std::string seconds_suffixe = "s";
std::string seconds_result = (hours > 0) | (minutes > 0) ? minutes_result + seconds_numstr + seconds_suffixe : seconds_numstr + seconds_suffixe;
return seconds_result;
}
typedef pair<double, int> Elt;
class mycomparison {
bool reverse;
public:
mycomparison( const bool& revparam=false ) { reverse=revparam; }
bool operator() (const Elt& lhs, const Elt& rhs) const {
if ( !reverse ) {
if( lhs.first == rhs.first ) {
return ( lhs.second < rhs.second );
} else {
return ( lhs.first > rhs.first );
}
} else {
if( lhs.first == rhs.first ) {
return ( lhs.second > rhs.second );
} else {
return ( lhs.first < rhs.first );
}
}
}
};
/** *********************************
* (ordered) indices *
* of top "n" elements of vector "v" *
* (using the "mycomparison" *
* custom comparator) *
************************************/
std::vector<int> top_n_idx(
NumericVector v
, unsigned int n
) {
// adapted from @see "htpp://gallery.rcpp.org/articles/top-elements-from-vectors-using-priority-queue/"
// also @see "https://en.cppreference.com/w/cpp/container/priority_queue"
// also @see "http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/""
priority_queue< Elt, vector<Elt>, mycomparison > pq;
vector<int> result;
for ( int i = 0; i != v.size() ; ++i ) {
if ( !isnan( v[i] ) ) {
if( pq.size() < n )
pq.push( Elt( v[ i ], i ) );
else {
Elt elt = Elt( v[i], i );
if ( pq.top().first < elt.first ) {
pq.pop(); // removes the top element
pq.push( elt );
}
}
}
}
result.reserve(pq.size());
while ( !pq.empty() ) {
result.insert( result.begin(), pq.top().second + 1 );
pq.pop();
}
/** in case there are not enough "non NA" values => */
for ( int i = 0; ( i != v.size() ) & ( result.size() < n ) ; ++i ) {
if ( isnan( v[i] ) ) {
result.push_back( i + 1 );
}
}
return result ;
}
/** *************************************************
# return in tidy format #
# top-k movies similar to a given "movie_ID" #
*****************************************************
# getMoviesKnns( int k, sim_matrix ) #
# - k - top "k" most similar neighbors #
# - sim_matrix - simmilarity matrix #
# - "m" columns (one per movie) #
# - "n" rows (one per potential #
# neighbor) #
# => (ordered) resultset : #
# - neighbor_ID #
# - similarity [0-1] #
****************************************************/
DataFrame getMovieKnns(
std::string movie_ID
, int k
, NumericMatrix& sim_matrix
) {
const CharacterVector xcols = colnames( sim_matrix );
int colidx = -1;
int i = 0;
for( ; i < xcols.size() ; ++i ) {
if( xcols[ i ] == movie_ID ) colidx = i;
}
if( colidx > -1 ) {
NumericMatrix::Column movie_similarities_vector = sim_matrix( _, colidx );
std::vector<int> rows_idx = top_n_idx( movie_similarities_vector, k );
IntegerVector rows_idx_vec( rows_idx.begin(), rows_idx.end() );
CharacterVector neighborsNamesVec = rownames( sim_matrix );
IntegerVector neighborsNamesIntVec( neighborsNamesVec.size() );
std::transform(
neighborsNamesVec.begin(), neighborsNamesVec.end()
, neighborsNamesIntVec.begin(), std::atoi );
IntegerVector topNeighborsColumn( k );
topNeighborsColumn =
neighborsNamesIntVec[ rows_idx_vec - 1 ]; // index starts at \'0\'
NumericVector similaritiesColumn =
sim_matrix( _, colidx );
NumericVector topSimilaritiesColumn =
similaritiesColumn[ rows_idx_vec - 1 ]; // index starts at \'0\'
return DataFrame::create(
Rcpp::Named( "neighbor_ID" ) = topNeighborsColumn
, Rcpp::Named( "similarity" ) = topSimilaritiesColumn
, Rcpp::Named( "stringsAsFactors" ) = false
);
} else {
return DataFrame::create(
Rcpp::Named( "neighbor_ID" ) = IntegerVector::create()
, Rcpp::Named( "similarity" ) = NumericVector::create()
);
}
}
/** *************************************************
* for a given movie, *
* all "k" neighbors rating predictions *
* ( each weighted by similarity) *
*****************************************************
* for each "m movie" => *
* "r" : a matrix of "users" rows, "max_k" columns *
* (for each "k in 1:max_k" neighbors, *
* a vector of length "u users") *
****************************************************/
NumericMatrix movieUsers_neighborsRatings(
const DataFrame& xcpp
, const DataFrame& nncpp // list of nearest neighbors (ID nd similarity)
, const int k
, const IntegerVector movie_users_IDs_idx
) {
NumericMatrix resultMatrix( movie_users_IDs_idx.size(), k );
const CharacterVector neighborsColumn = nncpp[ "neighbor_ID" ];
const NumericVector similaritiesColumn = nncpp[ "similarity" ];
for( int X = 0 ; X < k ; ++X ) {
//printf( "%u - %s - %f\\n", X, as<std::string>( neighborsColumn[ X ] ).c_str(), similaritiesColumn[ X ] );
NumericVector ratingsColmun = xcpp[ as<std::string>( neighborsColumn[ X ] ) ];
NumericVector usersRatingsColmun = ratingsColmun[ movie_users_IDs_idx ];
resultMatrix( _ , X ) = usersRatingsColmun * similaritiesColumn[ X ];
}
return resultMatrix;
}
IntegerVector nonNA_rowCounts( NumericMatrix x ) {
IntegerVector result( x.nrow() );
int rowCount = 0;
for( int i = 0 ; i < x.nrow() ; ++i ) {
LogicalVector nonNA_row = !is_na( x( i, _ ) );
rowCount = 0;
for ( int j = 0 ; j < x.ncol() ; ++j ) {
if( nonNA_row[ j ] == true ) rowCount++;
}
result( i ) = rowCount;
}
return result;
}
/** ***************************************************
* for each "userId"/movieId" pair of the test domain, *
* returns one rating prediction *
* per value of the "ks" vector *
*******************************************************
* inputs : *
* - "ks" list of different values *
* to be considered for "k" (neighbors count) *
* - "test_sim_matrix" similarity matrix *
* for the "test" movies *
* - "test_ratings_matrix" rating matrix *
* for the "test" users, all movies included *
* (from which "neighbor" ratings are picked) *
* - "test_domain" list of "userId"/movieId" pairs *
* (for which a prediction is expected) *
* - "print_comments" do (or not) show *
* progress info on the console *
*******************************************************
* resultset (tidy format ; 4 columns) : *
* - "userId" *
* - "movieId" *
* - "k" *
* - "prediction" *
******************************************************/
// [[Rcpp::export]]
DataFrame get_knn_predictions(
IntegerVector ks
, NumericMatrix test_sim_matrix
, NumericMatrix test_ratings_matrix
, DataFrame test_domain // to extract users list for each movie (pairs for which a prediction is expected)
, bool print_comments = false
) {
clock_t start;
double duration;
if( print_comments ) {
start = clock();
std::string prog_bar_str =
std::string( "Generating the knn predictions :\\n" ) +
"|" + std::string( 33, \'=\' ) + "|\\n|";
printf( prog_bar_str.c_str() );
}
IntegerVector all_test_movies_column = test_domain[ "movieId" ];
IntegerVector movieIds = sort_unique( all_test_movies_column );
const int counter_group_size = ceil( movieIds.size() / 33.0 );
DataFrame test_ratings_matrix_df = DataFrame( test_ratings_matrix );
IntegerVector all_test_users_column = test_domain[ "userId" ];
LogicalVector all_test_rows_idx( all_test_movies_column.size() );
int max_k = max( ks );
NumericVector m_rowSums_k;
NumericVector m_nonNA_rowCounts_k;
NumericVector m_movieReco_k;
NumericVector m_rowSums_prior_k;
NumericVector m_nonNA_rowCounts_prior_k;
IntegerVector result_userId_column =
rep( NA_INTEGER, ks.length() * test_domain.nrow() );
IntegerVector result_movieId_column =
rep( NA_INTEGER, ks.length() * test_domain.nrow() );
IntegerVector result_k_column =
rep( NA_INTEGER, ks.length() * test_domain.nrow() );
NumericVector result_prediction_column =
rep( NA_REAL, ks.length() * test_domain.nrow() );
int firstRowNb = 0;
for( int m = 0 ; m < movieIds.size() ; ++m ) {
int movie_ID = movieIds[ m ];
//printf( "%lli - %u\\n", m, movie_ID );
/** ************************************
* collect the list of users for which *
* the test dataset expect a prediction *
* for this particular movie *
* *************************************/
//printf( "%lli\\n", all_test_movies_column.size() ) ;
for ( int i = 0 ; i < all_test_movies_column.size() ; ++i ) {
all_test_rows_idx[ i ] =
( all_test_movies_column[ i ] == movie_ID );
}
IntegerVector movie_users_IDs =
all_test_users_column[ all_test_rows_idx == true ];
/*
printf(
"(%u) - movie %u ; %lli users\\n"
, ( m + 1 ), movie_ID, movie_users_IDs.size() );
*/
/** ******************************
* retrieve the nearest neighbors *
* for this particular movie *
* *******************************/
DataFrame m_nn =
getMovieKnns( std::to_string( movie_ID )
, max_k, test_sim_matrix );
/** ***************************************
* isolate the subset we\'re interested in *
* for this particular movie *
* ****************************************/
CharacterVector usersNamesVec = rownames( test_ratings_matrix );
IntegerVector usersNamesIntVec( usersNamesVec.size() );
std::transform(
usersNamesVec.begin(), usersNamesVec.end()
, usersNamesIntVec.begin(), std::atoi );
IntegerVector movie_users_IDs_idx( movie_users_IDs.size() );
for( int i = 0 ; i < movie_users_IDs.size() ; i++ ) {
for( int j = 0 ; j < usersNamesIntVec.size() ; j++ ) {
if( usersNamesIntVec( j ) == movie_users_IDs( i ) ) {
movie_users_IDs_idx( i ) = j;
break; // breaks out of the innermost loop
}
}
}
/** ****************************************
* retrieve all neighbors ratings (columns) *
* for the users (rows) for which
* a prediction is expected
* for this particular movie
*******************************************/
NumericMatrix m_r =
movieUsers_neighborsRatings(
test_ratings_matrix_df, m_nn, max_k
, movie_users_IDs_idx );
//printf( "%u - %u\\n", m_r.nrow(), m_r.ncol() );
/*
if( movie_ID == 356 ) {
Environment base = Environment::base_namespace();
Function saveRDS( "saveRDS" );
saveRDS( m_nn, "m_nn356" );
saveRDS( movie_users_IDs_idx, "movie_users_IDs_idx356" );
saveRDS( test_ratings_matrix_df, "test_ratings_matrix_df" );
saveRDS( m_r, "m_r356" );
}
*/
int k;
int prior_k = -1;
m_rowSums_prior_k = rep( 0, movie_users_IDs.size() );
m_nonNA_rowCounts_prior_k = rep( 0, movie_users_IDs.size() );
for ( int X = 0 ; X < ks.length() ; ++ X ) {
k = ks[ X ] - 1; // index starts at \'0\'
m_rowSums_k =
m_rowSums_prior_k + rowSums( m_r( _, Range( prior_k + 1, k ) ), true );
m_nonNA_rowCounts_k =
m_nonNA_rowCounts_prior_k +
as<NumericVector>( nonNA_rowCounts( m_r( _, Range( prior_k + 1, k ) ) ) );
m_movieReco_k =
m_rowSums_k / m_nonNA_rowCounts_k;
//if( movie_ID == 356 ) printf( "\\n%u - %u - %f / %f", ( k + 1 ), movie_users_IDs( 0 ), m_rowSums_k( 0 ), m_nonNA_rowCounts_k( 0 ) );
IntegerVector updated_rows_idx =
seq( firstRowNb, firstRowNb + movie_users_IDs.size() - 1 );
result_userId_column[ updated_rows_idx ] = movie_users_IDs;
result_movieId_column[ updated_rows_idx ] = movie_ID;
result_k_column[ updated_rows_idx ] = k + 1;
result_prediction_column[ updated_rows_idx ] = m_movieReco_k;
firstRowNb = firstRowNb + movie_users_IDs.size();
m_rowSums_prior_k = m_rowSums_k;
m_nonNA_rowCounts_prior_k = m_nonNA_rowCounts_k;
prior_k = k;
}
if( print_comments ) {
if(
( ( ( m + 1 ) % counter_group_size ) == 0 ) &
( ( m + 1 ) != movieIds.size() ) ) { printf( "-" ); }
}
}
DataFrame result = DataFrame::create(
Rcpp::Named( "userId" ) = result_userId_column
, Rcpp::Named( "movieId" ) = result_movieId_column
, Rcpp::Named( "k" ) = result_k_column
, Rcpp::Named( "prediction" ) = result_prediction_column
, Rcpp::Named( "stringsAsFactors" ) = false
);
if( print_comments ) {
printf( "-|" );
duration = ( clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout << " done: " << duration_string( duration ) << \'\\n\';
}
return result;
}
' )
} #
#######################################################
## #######################################################
## 'get_knn_optimization' function ##
##########################################################
# optimization procedure for the hyperparameter "k" #
##########################################################
# inputs : #
# - "train_rating_residuals_matrix" similarity matrix #
# for the "residual ratings" #
# (remainder after "Regularization") #
# on the "training" dataset #
# - "ks" list of different values #
# to be considered for "k" (neighbors count) #
# - "test_set" data points used #
# to compare predictions against 'true ratings' #
# - "mu_hat", "movie_avgs" and "user_avgs" #
# regularization parameters #
# - "print_comments" do (or not) show #
# progress info on the console #
##########################################################
# resultset (list of objects) : #
# - "similarity_matrix" #
# the movies cosine similarity matrix #
# - "k" - the optimum parameter value #
# - "k_optimization" - the "RMSE" versus "k" dataset #
# - "predicted_ratings" #
# the optimized predictions in tidy format #
# with colnames "userId", "movieId" and "pred" #
##########################################################
get_knn_optimization <- function(
train_rating_residuals_matrix
, train_sim_matrix = NULL
, ks
, test_set
, mu_hat , movie_avgs , user_avgs
, print_comments = FALSE
) {
t2 <- proc.time()
optimization_mode <- ( "rating" %in% colnames( test_set ) )
if( !optimization_mode ) ks[ 1 ] -> ks
if( is.null( train_sim_matrix ) ) {
t3 <- proc.time()
if( print_comments ) cat( "KNN - Computing the movies cosine similarity matrix.." )
train_sim_matrix <-
coop::cosine( train_rating_residuals_matrix, use = "pairwise.complete" )
train_sim_matrix - diag( ncol( train_sim_matrix ) ) ->
train_sim_matrix
if( print_comments ) cat( paste0( " done (", duration_string( t3 ), ")\n" ) )
rm( t3 )
}
###############################################
# we're gonna evaluate the prediction-ratings #
# for some pairs of #
# the distinct(test_set$userId), #
# distinct(test_set$movieId) domain. #
###############################################
setDT( test_set, key = c( "movieId", "userId" ) )
test_domain = unique( test_set[ , c( "movieId", "userId" ) ] )
test_userIds <-
as.character( unique( test_domain[ , "userId" ] ) %>% .$userId )
test_movieIds <-
as.character( unique( test_domain[ , "movieId" ] ) %>% .$movieId )
#saveRDS( test_movieIds, "test_movieIds_VIII" )
test_ratings_matrix <-
train_rating_residuals_matrix[ test_userIds, ] # (keep all movies here (all potential neighbors))
test_sim_matrix <- train_sim_matrix[ , test_movieIds ]
#saveRDS( test_sim_matrix, "test_sim_matrix_VIII" )
sort( unique( replace( ks, ks == 1, 2 ) ) ) -> ks
ks[ ks < ncol( train_rating_residuals_matrix ) ] -> ks
rm( train_rating_residuals_matrix )
predictions <-
get_knn_predictions(
ks = ks
, test_sim_matrix = test_sim_matrix
, test_ratings_matrix = test_ratings_matrix
, test_domain = test_domain
, print_comments = print_comments
)
setDT( predictions, key = c( "userId", "movieId" ) )
rm( test_ratings_matrix )
gc( reset = FALSE, full = TRUE, verbose = FALSE )
# what shall we do for users for which the 'X's movie neighbor
# gives an 'NA' prediction (average divided by '0' ;
# none of them has been rated either) ?
# replace 'NA's with 'mu_hat + b_i_hat + b_u_hat' ?
# actually makes zero difference when the value of k is high enough
# (all user/movie pairs has at least one neighbor)
if( optimization_mode ) {
columns <-
c( "userId", "movieId", "k", "prediction", "rating" )
} else {
columns <-
c( "userId", "movieId", "k", "prediction" )
}
result <-
merge( merge(
merge( predictions, test_set
, by = c( "userId", "movieId" )
, all = TRUE # full join (for speed)
)[ , columns, with = FALSE ]
, movie_avgs, by = c( "movieId" ) )
, user_avgs, by = c( "userId" ) ) %>%
mutate( pred =
case_when(