-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecommendation-system.Rmd
2082 lines (1356 loc) · 76.5 KB
/
recommendation-system.Rmd
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
---
title: "Harvard Capstone Project - Movie Recommendation System"
author: "HA W.M.ALEX"
date: "2024-10-16"
output: pdf_document
latex_engine: xelatex
toc: true
toc_depth: 2
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
message = FALSE,
warning = FALSE
)
# Note: It takes approx. 4 Minutes to generate the Data Science Report.
```
\newpage
```{r packages and libraries, include=FALSE}
#############################################
# Installing Packages and Loading Libraries #
#############################################
# Install Necessary Packages if required
if(!require(tidyverse)) install.packages("tidyverse",
repos = "http://cran.us.r-project.org")
if(!require(tidyr)) install.packages("tidyr",
repos = "http://cran.us.r-project.org")
if(!require(dplyr)) install.packages("dplyr",
repos = "http://cran.us.r-project.org")
if(!require(lubridate)) install.packages("lubridate",
repos = "http://cran.us.r-project.org")
if(!require(stringr)) install.packages("stringr",
repos = "http://cran.us.r-project.org")
if(!require(ggplot2)) install.packages("ggplot2",
repos = "http://cran.us.r-project.org")
if(!require(gridExtra)) install.packages("gridExtra",
repos = "http://cran.us.r-project.org")
if(!require(knitr)) install.packages("knitr",
repos = "http://cran.us.r-project.org")
if(!require(rstudioapi)) install.packages("rstudioapi",
repos = "http://cran.us.r-project.org")
if(!require(caret)) install.packages("caret",
repos = "http://cran.us.r-project.org")
if(!require(tinytex)){
install.packages("tinytex", repos = "http://cran.us.r-project.org")
tinytex::install_tinytex()
}
# Loading Necessary Libraries
library(dslabs)
library(tidyverse)
library(dplyr)
library(tidyr)
library(lubridate)
library(stringr)
library(ggplot2)
library(gridExtra)
library(knitr)
library(rstudioapi)
library(caret)
library(tinytex)
# Set number of significant digits=6 globally
options(digits=6)
set.seed(1990)
# Loading rda files which previously generated after running recommendation-system.R
load("rda/edx-original-rda.rda")
load("rda/edx-rda.rda")
load("rda/final-holdout-test.rda")
load("rda/min-lambda.rda")
```
# 1 Executive Summary
The Objective of Capstone Project is to develop a **Recommendation System** that **Predict Movie ratings** using a **Machine Learning Model** based on subset of **MovieLens** datasets. This subset represents a smaller portion of much larger datasets containing several Millions of **rating**. This datasets encompasses approximately **10 Millions Movies ratings**. The Primary task is to leverage this data to **Predict Movie ratings**.
For this endeavor, this **MovieLens** datasets is partitioned into **edx** sets for developing the Algorithm , comprising approximately **9 Million** Rows and **final_holdout_test** sets for **Testing on Final Model**, consisting approximately **1 Millions** Rows. The **edx** datasets includes **69,878 Unique Users**, **10,677 Unique Movies** and **797 Combined genres**. Each **Movie** is also categorized by its **Combined genres** and **ratings** range from **0.5** and **5.0** with increment of **0.5**.
Prior to Models Building, **Data exploration Analysis (EDA)** were conducted which encompassing Data cleaning,
Data pre-processing/Featuring Engineering, Data Visualization, Stratification Analysis, Distributions Analysis and Frequency Analysis. The Model employs a **Collaborative Filtering Approach**, augmented by **Regularization Method** to estimate the **Movie Effects**, **User Effects**, **Genres Effects** and **Time Effects**. These Methods are instrumental in penalizing the magnitude of the **Parameters** to avoid **Overfitting**.
The **edx** datasets is also split into **train sets** and **test sets** for training and testing the **Algorithm** using **Cross-Validation Method**. Our ultimate goal is to construct a Model that minimizes the loss, measured by our **loss function, Root Mean Squared Error (RMSE)**.
If $N$ is the **number of User-Movie combinations**, $y_{u,i}$ is the **rating** for **Movie** $i$ by **User** $u$, and $\hat{y}_{u,i}$ is our **Prediction**, the **RMSE** is defined as follow:
$$RMSE=\sqrt{\frac{1}{N}\sum_{u,i}(\hat{y}_{u,i}-y_{u,i})^2}$$
**Regularized Movie+User+Time Based Model** comply with an **Lowest RMSE** of **0.863759**.
The **Final Model** is defined as follow:
$$Y_{u,i}=\mu+b_i+b_u+ f(bt_i)+\varepsilon_{u,i}\text{ with } f\text{ a smooth function of }bt_i$$
$$\hat{bt}_{i}(\lambda) = \frac{1}{\lambda + n_{i}}\sum_{u=1}^{n_{i}} (Y_{u,i} - \hat{\mu{t}}_i-\hat{b}_u(\lambda))\text{ ,with }\text{ }\hat{\mu{t}}_i = \hat{f}(x_0) = \frac{1}{N_0}\sum_{i\in A_0}Y_i\text{ }\text{ ,}\left| x_i - x_0 \right| \le 7$$
The Model's **Performance** was evaluated using the Metric - **Root Mean Squared Error**. The **reliability** and **trustworthiness** of the Model are substantiated through incorporating **Regularization** and **Cross-Validation Method** during Model development.
**Optimal Machine Learning Model achieved an RMSE of 0.863759, Signifying a Remarkable Outcome. Thus, I firmly assert our confidence in adopting the ultimate Model and Algorithm to construct the Movie Recommendation System.**
\newpage
# 2 Introduction
## 2.1 Movie Recommendation System
Purpose of the Project is to build a **Recommendation System** based on **MovieLens** Dataset that **Predict Movie ratings** using **Machine Learning Algorithm**. The **Movie ratings** are on a **0.5-5.0** scale, where **5.0** represents the **best Movie** and **0.5** suggests it to be a **bad Movie**. **Movie Recommendation System** are more complicated Machine Learning challenges because each Outcome has a different set of **Features/Predictors**. For example, different Users Rate a different number of Movies and Rate different Movies. Consider the following scenario:
* If the average **rating** for all **Movies** is **3.7**, and **"Jurassic Park"** is better than an average **Movie**. User **"A"** might Rate it **0.5** points above the average.
* User **"B"** is a cranky User, tends to Rate **0.8** points lower than average. Thus, the estimate for **"Jurassic Park"** by User **"B"** would be calculated as **3.7-0.8+0.5=3.4**.
## 2.2 Overview
Many of the Movie **ratings** are influenced by **Effects** associated with either **Users** and **Movies** of their interactions. Different **Users** employ different **rating** scales, and a **User** can change their **rating** scales over **time** or **genres**. A **Movie's** popularity may also change over **time** or **genres** due to external events. For example, cranky **User** who tended to Rate an average Movie **4.0**, may now Rate such a movie **3.0** or even lower. But in some occasion, those user may Rate much higher.
To address this, we add **Time Effects** and **Genres Effects** to the baseline **features/predictors**. Including **Time Specific Effects** does not attempt to capture future changes but aims to capture transient effects that significantly influenced past User feedback. Some people may like a **Movie** and remember it as my most favorites because of it's **genres**. While others may dislike it and forget about it. Thus only those liking them will mark the **Movie** as favorites, while those disliking them will not mention them at all. This behavior is expected towards most popular Movies, which can be either remembered as very good or not to be remembered.
However,some Movies are known to be bad and people who did not like them always give them a lower scores, indicating what they do not want to watch. However, for the other part of the population, who liked those Movies, they are not going to be remembered long Time as notable. Thus, long Time after watching the Movie, only those who disliked the Movie will Rate it. Some Movies are natural selection of Movies to be Rated. some Movies are natural candidates as bad Movies, while others are natural candidates as good Movies.
Thus, **Time Effects** and **Genres Effects** can explain **Portion of Variability** of the Movie **ratings**.
\newpage
# 3 Data Exploration Analysis (EDA)
## 3.1 Data Explorations
The **MovieLens** datasets comprises approximately **10 Million** Rows of data. This datasets is randomly split into two separated datasets, **edx** and **final_holdout_test**. The **edx** datasets serves as the **training sets**, while the **final_holdout_test** datasets is used for **Final Model Testing** Purpose. Both datasets contain **6 Columns/Features/Predictors**. The **edx** datasets includes approximately **9 Millions** of Rows with **69,878 Unique Users**, **10,677 Unique Movies** and **797 combined genres**. Movie **rating** in this datasets range from **0.5** and **5.0** with increments of **0.5**.
\
**A) Dimension**
\
```{r rows and columns, echo=FALSE}
# - generate dimension of edx: number of rows and columns
# - display output using kable function
dim_df <- data.frame(Rows = dim(edx_original)[1], Columns = dim(edx_original)[2])
dim_df %>% knitr::kable(caption="edx datasets")
```
There are **`r dim_df$Rows`** Rows and **`r dim_df$Columns`** Columns in the **edx** datasets.
\
**B) Column Name and Class**
\
```{r class, echo=FALSE}
# - generate column name and class of edx
# - display output using kable function
class_results <- data.frame(Class=sapply(edx_original, class))
class_results %>% knitr::kable(caption="edx datasets")
```
There are **6** Columns and Class in the **edx** datasets.
\
**C) Number of Unique movieId, userId and genres.**
\
```{r movieId userId genres, include=FALSE}
# compute number of unique movieId, userId and genres
u_movie_n <- length(unique(edx_original$movieId))
u_user_n <- length(unique(edx_original$userId))
u_genres_n <- length(unique(edx_original$genres))
```
```{r um_result, echo=FALSE}
# - generate table - Number of Unique movieId, userId and genres.
# - display output using kable function
um_result <- data.frame(Description="Number of Unique movieId", Count=u_movie_n )
um_result <- bind_rows(um_result,
data.frame(Description="Number of unique userId", Count=u_user_n))
um_result <- bind_rows(um_result,
data.frame(Description="Number of unique combined genres", Count=u_genres_n))
um_result %>% knitr::kable(caption="edx datsets")
```
\
There are **`r u_movie_n`** Unique **Movies**, **`r u_user_n`** Unique **Users** and **`r u_genres_n`** Unique **Combined genres** in the **edx** datasets.
\newpage
**List of 10 Examples - Counting the Occurrences of rating (By movieId)**
```{r occurences of rating movieId, echo=TRUE}
# - generate 10 examples - counting the Occurrences of rating by movieId
# - display output using kable function
m_result <- edx %>% count(movieId,name="Occurency") %>%
count(Occurency, name="Count") %>%
arrange(desc(Count)) %>%
dplyr::slice(1:10)
m_result %>% knitr::kable(caption="edx datasets")
```
**List of 10 Examples - Counting the Occurrences of rating (By userId)**
```{r occurences of rating userId, echo=TRUE}
# - generate 10 examples - counting the occurrences of rating by userId
# - display output using kable function
u_result <- edx %>% count(userId,name="Occurency") %>%
count(Occurency, name="Count") %>%
dplyr::slice(30:40)
u_result %>% knitr::kable(caption="edx datasets")
```
\newpage
**Plot Distributions (Number of Occurrence) - movieId and userId**
```{r ggplot m1 and m2, echo=TRUE}
# - generate distributions (number of occurrence) using movieId and userId
# - ggplot histogram - m1 and m2
m1 <- edx %>%
dplyr::count(movieId) %>%
ggplot(aes(n)) +
geom_histogram(bins = 50, fill="#006EBB", color="black") +
labs(y="Count",x="Number of Occurrence") +
scale_x_log10() +
ggtitle("Movies")
m2 <- edx %>%
dplyr::count(userId) %>%
ggplot(aes(n)) +
geom_histogram(bins = 200, fill="cyan", color="#D883B7" ) +
labs(y="Count",x="Number of Occurrence") +
scale_x_log10()+
ggtitle("Users")
grid.arrange(m1, m2, ncol = 2)
```
**It is evident from the distributions plotted above that some Movies are rated more than the other Movies and some Users are more active and Rate more number of Movies than the other Users do.**
\newpage
\
### 3.1.1 Description of Columns/Features/Predictors
* **movieId** : A Unique identification number assigned to each **Movie**.
* **title** : The **title** for each **Movie** follow by the Release Year inside the parentheses "(1996)".
* **genres** : The **Combined genres** of each **Movie**, where each **genres** are separated by a pipe "|".
* **userId** : A unique identification assigned to each **User**.
* **rating** : The **rating** given by a Unique **User** for specific **Movie**.
* **timestamp** : The **timestamp** associated with a User's **rating** for a particular **Movie**.
### 3.1.2 Data Cleaning
**R Codes check columns with "NA" values in "edx" datasets**
```{r na_results, echo=TRUE}
# - generate missing value (if any) in column rating of edx
# - display output using kable function
na_results <- edx[apply(is.na(edx),1,any),]
na_results %>% select(userId,movieId,rating,timestamp,title,genres) %>%
knitr::kable(caption="Columns with NA values in edx datasets")
```
As we can see from the output above, there are **NO missing value** in **rating** Column of **edx** datasets.
\
\
**R Code check "rating" column for "Zeros" value in the "edx" datasets**
```{r zeros value, echo=TRUE}
# generate and display zeros value (if any) in column rating of edx
length(which(edx$rating==0))
```
There are also **No zeros value** were given as **rating** in the **edx** datasets.
\newpage
**List of 8 Examples - edx datasets**
```{r original edx, echo=TRUE}
# - generate 8 examples: the original edx - rating given by one User to one movie
# - display output of edx using kable function
edx %>%
group_by(title) %>%
mutate(f=length(rating)) %>% ungroup() %>%
filter(f > 10000) %>%
distinct(title, .keep_all=TRUE) %>%
arrange(desc(f)) %>%
select(movieId,title,genres,userId,rating,timestamp) %>%
dplyr::slice(1:8) %>%
knitr::kable(caption="edx datasets")
```
\
**Each Row in "edx" represents a "rating" given by one User to one Movie.**
\newpage
### 3.1.3 Pre-Processing/Feature Engineering
The **edx** datasets contain **Columns/Features/Predictors** like **timestamp**, **genres**, **rating**. Not all **Features** may be useful for **Prediction** and some may even be detrimental. Therefore we will select the most important **Features**. We will Transform and Extract the **timestamp** Column into **Week of Date** and **Year of Date** for readable format that better represent the underlying problem to the Model. Additionally, We will compute the **Mean of rating** by **genres**, **Week of Date** and **Year of Date**. These **new Features** are important for the Predictive Model as they provide insights into the problem, potentially **improving the Model Performance**.
\
**3.1.3.1 Column genres**
\
The **genres** Column includes every Genre that applies to **Movie** so I will define it as **Combined genres**.
Some **Movies** also fall under several **genres**. The Extraction of **Combined genres** from the **Movie** into separate Rows is **NOT Necessary**, even those each Genre is separated by a pipe "|". In reality, **Movies** often belong to multiple **genres** simultaneously. Manipulating the original **Combined genres** Column by splitting it into individual Genre per Row could lead to **Data Misrepresentation**. It might introduce data bias when the **combined genres** of a **Movie** are artificially separated.
In truth, the **combined genres** for each **Movie** provide a more **Accurate Representation of Data**.
\
Following Example explain why Extraction of **Combined genres** into separate Rows is **Not Necessary**
\
**3.1.3.1.1 Mean of rating by genres BEFORE Combined genres Separation**
\
\
**List Mean of rating by genres in descending order by Number of rating (count > 10000)**
```{r mean of rating genres, echo=FALSE}
# - mean of rating by genres bEFORE combined genres separation
# - generate 20 examples-mean of rating by genres
# in descending order by number of rating(count > 10000)
genres_avg <- edx %>%
group_by(genres) %>%
summarize(average_rating_genres=mean(rating, na.rm=TRUE ),
se=sd(rating, na.rm=TRUE)/sqrt(n()), count=n()) %>%
filter(count > 10000) %>%
arrange(desc(average_rating_genres)) %>%
mutate(rank=rownames(.))
# display output of genres_avg
genres_avg %>% select(rank, genres, average_rating_genres, count) %>%
dplyr::slice(1:20)
# prepare genres_avg_-plot for ggplot
genres_avg_plot <- genres_avg %>% dplyr::slice(1:20)
```
\newpage
**Mean of rating by genres (genres="Drama")**
```{r genres drama, echo=FALSE}
# display mean of rating by genres (genres="Drama")
genres_avg %>% select(rank, genres, average_rating_genres, count) %>%
dplyr::slice(48)
```
\
**Mean of rating by genres (genres="Comedy")**
```{r genres comedy, echo=FALSE}
# display mean of rating by genres (genres="Comedy")
genres_avg %>% select(rank, genres, average_rating_genres, count) %>%
dplyr::slice(131)
```
```{r rank comedy and drama before separated, include=FALSE}
# generate and display rank, Combined genres, Mean of rating by genres
# and number of rating of "Comedy" and "Drama"
genres_t1 <- genres_avg %>%
filter(genres%in%c("Comedy","Drama")) %>%
select(rank, genres, average_rating_genres, count)
```
\
**3.1.3.1.2 Plot Mean of rating by genres with error bars BEFORE genres Separated**
\
\
```{r ggplot before genres separated, echo=FALSE}
# ggplot mean of rating by genres with error bars before genres separation
genres_avg_plot %>%
ggplot(aes(x=genres, y=average_rating_genres)) +
geom_errorbar(aes(ymin=average_rating_genres - se,
ymax=average_rating_genres + se),color="#7977B8") +
geom_point(color="#F89E78") +
theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1)) +
labs(x="Combined genres", y="Mean of rating",
title="(Original Combined genres) Mean of rating by genres with Error Bars")
```
\newpage
**3.1.3.1.3 Mean of rating by genres AFTER Combined genres Separated**
**List of 15 Examples - Mean of rating by genres in descending order. (count > 20000)**
```{r after genres separated, echo=FALSE}
# - mean of rating by genres after Combined genres separation
# - data Wrangling: 1) separate combined genres into several Rows
# and each row contains only one genre
# 2) use data frame edx_original
# - generate mean of rating by genres in descending order(count > 20000)
genres_avg <- edx_original %>%
separate_longer_delim(genres, delim="|") %>%
group_by(genres) %>%
summarize(average_rating_genres=mean(rating, na.rm=TRUE ),
se=sd(rating, na.rm=TRUE)/sqrt(n()), count=n()) %>%
filter(count > 200000) %>%
arrange(desc(average_rating_genres)) %>%
mutate(rank=rownames(.))
# display output of genres_avg
genres_avg %>% select(rank, genres, average_rating_genres, count) %>%
dplyr::slice(1:20)
# generate rank, combined genres, mean of rating by genres
# and number of rating of "Comedy" and "Drama"
genres_t2 <- genres_avg %>%
filter(genres%in%c("Comedy","Drama")) %>%
select(rank, genres, average_rating_genres,count)
# Prepare genres_avg_plot for ggplot
genres_avg_plot <- genres_avg %>% dplyr::slice(1:20)
```
**3.1.3.1.4 Plot Mean of rating by genres with Error Bars AFTER genres Separated**
```{r ggplot genres after separated, echo=FALSE}
# ggplot mean of rating by genres with error bars after genres separated into several rows
genres_avg_plot %>%
ggplot(aes(x=genres, y=average_rating_genres)) +
geom_errorbar(aes(ymin= average_rating_genres- se,
ymax= average_rating_genres+ se),color="#7977B8") +
geom_point(color="#F89E78") +
theme(axis.text.x=element_text(angle=90, vjust=0.5, hjust=1)) +
labs(x="Separated genres", y="Mean of rating",
title="(After genres Separated) Mean of rating by genres with Error Bars") +
scale_y_continuous(breaks=seq(0.5,5,by=0.1))
```
\newpage
\
**List of rank, genres, Mean of rating by genres & Number of rating of "Comedy" and "Drama"**
\
```{r list before combined genres separated, echo=FALSE}
# display output table of genres_t1 using kable function
genres_t1 %>% knitr::kable(caption="BEFORE Combined genres Separated")
```
\
```{r list after combined genres separated, echo=FALSE}
# display output table of genres_t2 using kable function
genres_t2 %>% knitr::kable(caption="After Combined genres Separated")
```
\
\
**As illustrated by above Example, Data Misrepresentation is observed in Column of "rank", "Mean of rating" by "genres" and "Number of rating" after the Separation of "Combined genres" in edx datasets.**
\newpage
**3.1.3.2 Column timestamp**
Create **new Features** based on **timestamp** to capture insights related to **Time Effects**.
\
* **Week of the Date** (d_w): Transform & Extract the **Week of the Date** in **timestamp** column.
\
* **Month of the Date** (d_m): Transform & Extract the **Month of the Date** in **timestamp** column.
\
* **Year of the Date** (d_y): Transform & Extract the **Year of the Date** in **timestamp** column.
These **new Features** will enhance our Models ability to capture **Time Effects patterns**.
**R codes generate new Columns (d_w, d_m, d_y)**
```{r generate new columns d_w d_y, echo=TRUE, eval=FALSE}
# data Wrangling: generate new columns (d_w, d_m, d_y) from column timestamp
edx <- edx %>% mutate(d_w=format(round_date(as_datetime(timestamp),"week"),"%Y-%m-%d"))
edx <- edx %>% mutate(d_m=format(round_date(as_datetime(timestamp),"month"),"%Y-%m-%d"))
edx <- edx %>% mutate(d_y=format(round_date(as_datetime(timestamp),"year"),"%Y-%m-%d"))
```
**3.1.3.3 Column rating**
Create **new Features/Predictors** can provide more detailed insights into **Mean of rating** by various dimensions such as **Week of Date**, **Week of Year**, **genres**. Additionally, I will also capture the total **Number of rating** by **movieId**.
The following steps outline the Feature Engineering process:
* Compute **Mean of rating** by **movieId** and generate a new Column **m_r**.
* Compute **Mean of rating** by **movieId**, **Week of the Date** and generate a new Column **m_rw**.
* Compute **Mean of rating** by **movieId**, **Year of the Date** and generate a new Column **m_ry**.
* Compute **Mean of rating** by **userId**, **genres** and generate a new Column **m_rg**.
* Compute Total **Number of rating** by **movieId** and generate a new Column **tot_nr**.
**new Features** enable us to capture more information & improve the **robustness** of **Data Analysis**.
**R codes generate new Columns (m_r, m_rw, m_ry, m_rg, tot_nr)**
```{r generate new columns m_r m_rw m_ry m_rg tot_nr,echo=TRUE, eval=FALSE}
# data Wrangling: generate new columns (m_r, m_rw, m_ry, m_rg, tot_nr) from column rating
edx <- edx %>% group_by(movieId) %>% mutate(m_r = mean(rating, na.rm=TRUE))
edx <- edx %>% group_by(movieId,d_w) %>% mutate(m_rw= mean(rating, na.rm=TRUE))
edx <- edx %>% group_by(movieId,d_y) %>% mutate(m_ry= mean(rating, na.rm=TRUE))
edx <- edx %>% group_by(userId,genres) %>% mutate(m_rg=mean(rating, na.rm=TRUE))
edx <- edx %>% group_by(movieId) %>% mutate(tot_nr=n()) %>% ungroup()
```
\newpage
**3.1.3.4 Column title**
To facilitate easier interpretation and explanation, we will also create the **new Features** that capture more information than original **Features**.
* Extract the **Release Year** of **Movie** from **title** column and generate a **new** column **release**.
This **new Feature** will enhance our datasets by providing a clear and easily interpretable attribute related to the **Movie's Release Year**.
**R codes generate new column "release" from column "title"**
```{r generate column release, echo=TRUE, eval=FALSE}
# data wrangling: generate new column release from column title
edx <- edx %>% mutate(release = str_extract(title,"\\d{4}")) %>%
mutate(title = str_replace(title,"\\s*\\(\\d{4}\\)",""))
```
### 3.1.4 New Features/Predictors
**List 10 Examples encompassing new Features (d_w)**
```{r new features d_w, echo=FALSE}
# generate and display 10 examples encompassing new features (d_w)
edx %>% group_by(title) %>%
mutate(f=length(rating)) %>% ungroup() %>%
filter(f > 15000) %>%
arrange(desc(f),timestamp) %>%
distinct(title, .keep_all=TRUE) %>%
select(userId,movieId,title,d_w,rating) %>%
dplyr::slice(10:20)
```
**List 8 Examples encompassing new Features (release, m_r, m_rw, m_ry, m_rg)**
```{r new features other, echo=FALSE}
# generate 8 examples encompassing new features (release, m_r, m_rw, m_ry, m_rg, tot_nr)
edx %>% group_by(title) %>%
mutate(f=length(rating)) %>% ungroup() %>%
filter(f > 20000) %>%
arrange(desc(f),timestamp) %>%
distinct(title, .keep_all=TRUE) %>%
select(userId,release,title,rating,m_r,m_rw,m_ry,m_rg) %>%
dplyr::slice(1:8)
```
\newpage
## 3.2 Data Visualization and Analysis
### 3.2.1 Frequency Analysis
**3.2.1.1 Frequency of rating By title**
**List of 20 Movies which is most frequently Rated by User with frequency > 10000**
```{r frequency movies, echo=TRUE}
# generate 20 movies: most frequently rated by User with frequency > 10000
c_1 <- edx %>%
group_by(title) %>%
mutate(frequency=length(rating)) %>% ungroup() %>%
filter(frequency > 10000) %>%
distinct(title, .keep_all=TRUE) %>%
arrange(desc(frequency)) %>%
mutate(rank=rownames(.)) %>%
select(rank,title,frequency) %>%
dplyr::slice(1:20)
# display c_1 using kable function
c_1 %>% knitr::kable(caption="Frequency of rating By title")
```
\
**The Movie "Pulp Fiction" has the greatest Number of rating and is most frequently Rated by User.**
\newpage
**3.2.1.2 Plot - Frequency of rating By title**
\
```{r ggplot frequency movies, echo=TRUE}
# ggplot frequency of rating By title
c_1 %>% mutate(title=reorder(title,frequency)) %>%
ggplot(aes(title,frequency)) +
geom_bar(stat="identity",fill="#D883B7",color="white") +
labs(y="Frequency",x="Moive title",title="Frequency of User rating By Movie title") +
theme(axis.text.x=element_text(angle=90)) +
scale_y_continuous(breaks=seq(0,33000,by=3000)) +
coord_flip()
```
\newpage
**3.2.1.3 Frequency of rating By genres**
**List of 20 genres which is most frequently Rated by User with frequency > 10000**
```{r frequency rating genres, echo=TRUE}
# generate 20 genres: most frequently rated by User with frequency > 10000
c_2 <- edx %>%
group_by(genres) %>%
mutate(frequency=length(rating)) %>% ungroup() %>%
filter(frequency > 10000) %>%
distinct(genres, .keep_all=TRUE) %>%
arrange(desc(frequency)) %>%
mutate(rank=rownames(.)) %>%
select(rank,genres,frequency) %>%
dplyr::slice(1:20)
# display c_2
print_df <- function(title,df)
{
cat(title, "\n\n")
cat(capture.output(print(n=50,df)), sep="\n")
}
print_df("List of 20 genres - Frequency of rating By genres ",c_2)
```
\
**The genres "Drama" has the greatest Number of rating and is most frequently Rated by User.**
\newpage
**3.2.1.4 Plot - Frequency of rating By genres**
\
```{r ggplot frequency rating genres, echo=TRUE}
# ggplot frequency of rating By genres
c_2 %>% mutate(genres=reorder(genres,frequency)) %>%
ggplot(aes(genres,frequency)) +
geom_bar(stat="identity",fill="#584298",color="white") +
labs(y="Frequency",x="genres",title="Frequency of User rating By genres") +
theme(axis.text.x=element_text(angle=90)) +
scale_y_continuous(breaks=seq(0,800000,by=80000)) +
coord_flip()
```
\newpage
### 3.2.2 Stratification Analysis
**Correlation** is only meaningful in a particular context. **Stratification** is used to identifying the **Correlation** is meaningful as a summary statistic for **Prediction**. I stratify a **rating** into groups and compute the **Mean** summaries in each group (**Mean of rating**, **Mean of rating** by **Week of Date**, **Mean of rating** by **Year of Date**, **Mean of rating** by **genres**). After normalizing the **rating** and **Mean of rating**, the **Mean of rating** will be equal to **0** and the **Standard Deviation** will be equal to **1**.
Therefore, I will set **intercept** to **0** and **slope** to **Correlation coefficient** ($\rho$).
**3.2.2.1 Plot - Correlation of Normalized Mean of rating and rating**
```{r ggplot correlation mean of rating, echo=TRUE}
# compute correlation coefficient (r) of rating and m_r with 6 decimals place
r <- edx %>%
summarize(r=cor(rating,m_r)) %>%
pull(r)
r <- round(r,6)
# ggplot correlation of Normalized Mean of rating and rating
edx %>% mutate(rating=scale(rating),m_r=scale(m_r)) %>%
group_by(rating) %>%
summarize(m_r=mean(m_r)) %>%
ggplot(aes(rating,m_r)) + geom_point()+
geom_abline(intercept=0, slope=r,color="#F89E78")+
labs(x="scale(rating)",y="scale(m_r)",
title=paste("Normalized Mean of rating vs rating [cor =",r,"]"))
```
\newpage
**3.2.2.2 Plot - Correlation of Normalized Mean by Week of Date and rating**
\
\
\
```{r ggplot correlation mean week of date, echo=FALSE}
# compute correlation coefficient (r) of rating and m_rw with 6 decimals place
r <- edx %>%
summarize(r=cor(rating,m_rw)) %>%
pull(r)
r <- round(r,6)
# ggplot correlation of normalized mean by week of date and rating
edx %>% mutate(rating=scale(rating),m_rw=scale(m_rw)) %>%
group_by(rating) %>%
summarize(m_rw=mean(m_rw)) %>%
ggplot(aes(rating,m_rw)) + geom_point()+
geom_abline(intercept=0, slope=r,color="#F89E78")+
labs(x="scale(rating)",y="scale(m_rw)",
title=paste("Normalized Mean of rating by Week of Date vs rating [cor =",r,"]"))
```
\newpage
**3.2.2.3 Plot - Correlation of Normalized Mean by Year of Date and rating**
\
\
\
```{r ggplot correlation mean year of date, echo=FALSE}
# compute correlation coefficient (r) of rating and m_ry with 6 decimals place
r <- edx %>%
summarize(r=cor(rating,m_ry)) %>%
pull(r)
r <- round(r,6)
# ggplot correlation of normalized mean by year of date and rating
edx %>% mutate(rating=scale(rating),m_ry=scale(m_ry)) %>%
group_by(rating) %>%
summarize(m_ry=mean(m_ry)) %>%
ggplot(aes(rating,m_ry)) + geom_point()+
geom_abline(intercept=0, slope=r,color="#F89E78")+
labs(x="scale(rating)",y="scale(m_ry)",
title=paste("Normalized Mean of rating by Year of Date vs rating [cor =",r,"]"))
```
\newpage
\
**3.2.2.4 Plot - Correlation of Normalized Mean of rating by genres and rating**
\
\
\
```{r ggplot correlation mean of rating genres, echo=FALSE}
# compute correlation coefficient (r) of rating and m_rg with 6 decimals place
r <- edx %>%
summarize(r=cor(rating,m_rg)) %>%
pull(r)
r <- round(r,6)
# ggplot correlation of normalized mean of rating by genres and rating
edx %>% mutate(rating=scale(rating),m_rg=scale(m_rg)) %>%
group_by(rating) %>%
summarize(m_rg=mean(m_rg)) %>%
ggplot(aes(rating,m_rg)) + geom_point()+
geom_abline(intercept=0, slope=r,color="#F89E78") +
labs(x="scale(rating)",y="scale(m_rg)",
title=paste("Normalized Mean of rating by genres vs rating [cor =",r,"]"))
```
\newpage
**3.2.2.5 Correlation table - new Features (m_r, m_rw, m_ry, m_rg) of "edx" dataset**
```{r correlaton table, echo=TRUE}
# generate correlation coefficient table (m_r, m_rw, m_ry, m_rg) of edx
avg_r_all <- edx %>%
select(rating,m_r,m_rw,m_ry,m_rg)
cor_r_all <- cor(na.omit(avg_r_all[, unlist(lapply(avg_r_all, is.numeric))]))
# display correlation coefficient table using kable function
cor_r_all %>% knitr::kable(caption="Correlation - new Features of edx dataset")
```
\
**Data Visualization** reveals that **Mean** of each group appear to follow a **linear relationship**.
**Mean of rating** By **genres** seems to have more predictive power than **Mean of rating**, **Mean of rating** By **Week of Date** and **Mean of rating** By **Year of Date**. The **rating** to **Mean of rating** By **Week of Date** and **Mean of rating** By **genres** variability are quite large and this implies that they should explain a **lot of variability**.
\
Hence, I will add **Mean of rating** By **genres** as a **Parameter** for **Genres Effects** in Model building. Adding extra **Features/Predictors** can improve **Root Mean Squared Error(RMSE)**, but may not when the added **Features** that are highly correlated with other **Features**. From **Correlation** table, I also observe that the **Correlation** between **rating** and **Mean of rating** By **Week of Date** is second greatest. Therefore, I will also add **Mean of rating** By **Week of Date** as **Parameter** for **Time Effects** in Model building.
\newpage
### 3.2.3 Distributions Analysis
**3.2.3.1 Plot - rating Distributions of Movie**
\
\
\
```{r ggplot distributions movie, echo=FALSE}
# ggplot rating distributions of movie
edx %>% ggplot(aes(rating)) +
geom_histogram(binwidth=0.5,fill="#7977B8",color="black") +
labs(y="Frequency",x="rating",title="rating Distributions of Movie") +
scale_x_continuous(breaks=seq(0.5,5,by=0.5))
```
\newpage
**3.2.3.2 Plot - Distributions of Movie (Most Given rating in order from Most to Least)**
```{r ggplot distribution movie most given rating, echo=TRUE}
# generate frequency group by rating
edx_asc <- edx %>%
group_by(rating) %>%
summarise(Frequency = n()) %>%
arrange(Frequency)
# ggplot distributions of movie from most given rating in order from most to least
edx_asc %>%
ggplot(aes(x=reorder(rating, Frequency), y=Frequency)) +
geom_bar(stat="identity", width=0.5, aes(fill=Frequency)) +
scale_fill_gradient(low="red", high="blue") +
coord_flip() +
labs(y="Frequency",
x="rating",
title = "Distributions of Movie (Most Given rating in order from Most to Least)")
```
\
**The Five most given rating in order from most to least are (4.0, 3.0, 5.0, 3.5, 2.0).**
In general, half score **rating** are less common than whole score **rating**. For example, there are fewer **rating** of **3.5** than there are **rating** of **3.0** or **4.0**
\newpage
\
**3.2.3.3 Plot - Mean of rating Distributions**
\
\
\
```{r ggplot distributions mean of rating, echo=FALSE}
# ggplot mean of rating distributions
edx %>% ggplot(aes(m_r)) +
geom_histogram(binwidth=0.1,fill="#C6DC67",color="black") +
labs(y="Frequency",x="Mean of rating",title="Mean of rating Distributions") +
theme(axis.text.x=element_text(angle=90)) +
scale_x_continuous(breaks=seq(0.5,5,by=0.1))