-
Notifications
You must be signed in to change notification settings - Fork 0
/
pr2.Rmd
636 lines (436 loc) · 24.6 KB
/
pr2.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
---
title: 'Project 2: Modeling and Evaluation'
subtitle: "CSE6242 - Data and Visual Analytics - Fall 2017\n\nDue: Sunday, November 26, 2017 at 11:59 PM UTC-12:00 on T-Square"
output:
html_notebook:
code_folding: none
theme: default
html_document:
code_folding: none
theme: default
pdf_document: default
username: aamster3
---
# Data
We will use the same dataset as Project 1: [`movies_merged`](https://s3.amazonaws.com/content.udacity-data.com/courses/gt-cs6242/project/movies_merged).
# Objective
Your goal in this project is to build a linear regression model that can predict the `Gross` revenue earned by a movie based on other variables. You may use R packages to fit and evaluate a regression model (no need to implement regression yourself). Please stick to linear regression, however.
# Instructions
You should be familiar with using an [RMarkdown](http://rmarkdown.rstudio.com) Notebook by now. Remember that you have to open it in RStudio, and you can run code chunks by pressing *Cmd+Shift+Enter*.
Please complete the tasks below and submit this R Markdown file (as **pr2.Rmd**) containing all completed code chunks and written responses, and a PDF export of it (as **pr2.pdf**) which should include the outputs and plots as well.
_Note that **Setup** and **Data Preprocessing** steps do not carry any points, however, they need to be completed as instructed in order to get meaningful results._
# Setup
Same as Project 1, load the dataset into memory:
```{r}
load('movies_merged')
```
This creates an object of the same name (`movies_merged`). For convenience, you can copy it to `df` and start using it:
```{r}
df = movies_merged
cat("Dataset has", dim(df)[1], "rows and", dim(df)[2], "columns", end="\n", file="")
colnames(df)
```
## Load R packages
Load any R packages that you will need to use. You can come back to this chunk, edit it and re-run to load any additional packages later.
```{r}
library(ggplot2)
library(car)
library(tm)
library(zeallot)
```
If you are using any non-standard packages (ones that have not been discussed in class or explicitly allowed for this project), please mention them below. Include any special instructions if they cannot be installed using the regular `install.packages('<pkg name>')` command.
**Non-standard packages used**: car, tm
# Data Preprocessing
Before we start building models, we should clean up the dataset and perform any preprocessing steps that may be necessary. Some of these steps can be copied in from your Project 1 solution. It may be helpful to print the dimensions of the resulting dataframe at each step.
## 1. Remove non-movie rows
```{r}
# TODO: Remove all rows from df that do not correspond to movies
df = df[df$Type == "movie", ]
dim(df)
```
## 2. Drop rows with missing `Gross` value
Since our goal is to model `Gross` revenue against other variables, rows that have missing `Gross` values are not useful to us.
```{r}
# TODO: Remove rows with missing Gross value
df = df[!is.na(df$Gross), ]
dim(df)
```
## 3. Exclude movies released prior to 2000
Inflation and other global financial factors may affect the revenue earned by movies during certain periods of time. Taking that into account is out of scope for this project, so let's exclude all movies that were released prior to the year 2000 (you may use `Released`, `Date` or `Year` for this purpose).
```{r}
# TODO: Exclude movies released prior to 2000
df = df[df$Year >= 2000, ]
dim(df)
```
## 4. Eliminate mismatched rows
_Note: You may compare the `Released` column (string representation of release date) with either `Year` or `Date` (numeric representation of the year) to find mismatches. The goal is to avoid removing more than 10% of the rows._
```{r}
# TODO: Remove mismatched rows
mismatch = function(row) {
year = as.numeric(row['Year'])
date = as.numeric(row['Date'])
released = as.numeric(format(as.Date(row['Released']), '%Y'))
if (!is.na(year) && !is.na(date)) {
if(abs(year - date) > 1) {
return(TRUE)
}
}
if (!is.na(year) && !is.na(released)) {
if(abs(year - released) > 1) {
return(TRUE);
}
}
if (!is.na(date) && !is.na(released)) {
if(abs(date - released) > 1) {
return(TRUE);
}
}
return(FALSE)
}
df = df[!apply(df, 1, mismatch), ]
dim(df)
```
## 5. Drop `Domestic_Gross` column
`Domestic_Gross` is basically the amount of revenue a movie earned within the US. Understandably, it is very highly correlated with `Gross` and is in fact equal to it for movies that were not released globally. Hence, it should be removed for modeling purposes.
```{r}
# TODO: Exclude the `Domestic_Gross` column
df = df[, !names(df) %in% c('Domestic_Gross')]
```
## 6. Process `Runtime` column
```{r}
# TODO: Replace df$Runtime with a numeric column containing the runtime in minutes
convertToMinutes = function(runtime) {
if(is.na(runtime)) {
return(NA)
}
split = strsplit(runtime, ' ')[[1]]
split = lapply(split, function(x) gsub(',', '', x))
minutes = 0
if (length(split) == 2) {
minutes = as.integer(split[1])
} else if (length(split) == 4) {
minutes = as.integer(split[1]) * 60 + as.integer(split[3])
}
return(minutes)
}
df$Runtime = sapply(df$Runtime, convertToMinutes)
```
Perform any additional preprocessing steps that you find necessary, such as dealing with missing values or highly correlated columns (feel free to add more code chunks, markdown blocks and plots here as necessary).
```{r}
# TODO(optional): Additional preprocessing
df = df[df$Gross != 0, ]
df = df[df$Runtime > 70 & df$Runtime <= 150, ]
df["ReleaseMonth"] = format(df$Released, "%m")
```
_**Note**: Do NOT convert categorical variables (like `Genre`) into binary columns yet. You will do that later as part of a model improvement task._
## Final preprocessed dataset
Report the dimensions of the preprocessed dataset you will be using for modeling and evaluation, and print all the final column names. (Again, `Domestic_Gross` should not be in this list!)
```{r}
# TODO: Print the dimensions of the final preprocessed dataset and column names
print(dim(df))
print(names(df))
```
# Evaluation Strategy
In each of the tasks described in the next section, you will build a regression model. In order to compare their performance, you will compute the training and test Root Mean Squared Error (RMSE) at different training set sizes.
First, randomly sample 10-20% of the preprocessed dataset and keep that aside as the **test set**. Do not use these rows for training! The remainder of the preprocessed dataset is your **training data**.
```{r}
TRAIN_FRACTION = .9
df = sample(df)
train = df[seq(length.out = TRAIN_FRACTION * nrow(df)), ]
test = df[seq(TRAIN_FRACTION * nrow(df) + 1, nrow(df)), ]
print(dim(train))
print(dim(test))
```
Now use the following evaluation procedure for each model:
- Choose a suitable sequence of training set sizes, e.g. 10%, 20%, 30%, ..., 100% (10-20 different sizes should suffice). For each size, sample that many inputs from the training data, train your model, and compute the resulting training and test RMSE.
- Repeat your training and evaluation at least 10 times at each training set size, and average the RMSE results for stability.
- Generate a graph of the averaged train and test RMSE values as a function of the train set size (%), with optional error bars.
You can define a helper function that applies this procedure to a given set of features and reuse it.
```{r}
learning_curve = function(formula, train_data, test_data, responseInvert = function(v) v) {
TRAINING_EXAMPLE_FRACTION = seq(from = .01, to = 1, length.out = 10)
NUM_ITERATIONS = 10
results = data.frame(training_fraction = numeric(0), mean = numeric(0), se = numeric(0), dataset = character(0))
for (training_examples_fraction in TRAINING_EXAMPLE_FRACTION) {
sample_idx = sample(1:nrow(train_data), size = nrow(train_data) * training_examples_fraction)
train_subset = train_data[sample_idx, ]
train_rmse_sum = 0
test_rmse_sum = 0
for (iter in 1:NUM_ITERATIONS) {
model = lm(formula, train_subset)
train_pred = predict.lm(model)
# Remove predictions and corresponding labels which are NA
valid_pred_idx = which(!is.na(train_pred))
train_pred = train_pred[valid_pred_idx]
train_target = train$Gross[valid_pred_idx]
# Make sure test data has same levels as train_subset
if (length(model$xlevels[["ReleaseMonth"]]) > 0) {
model$xlevels[["ReleaseMonth"]] = levels(test$ReleaseMonth)
}
if (length(model$xlevels[["tomatoRating_bin"]]) > 0) {
model$xlevels[["tomatoRating_bin"]] = levels(test$tomatoRating_bin)
}
test_pred = predict.lm(model, test)
# Remove predictions and corresponding labels which are NA
valid_pred_idx = which(!is.na(test_pred))
test_pred = test_pred[valid_pred_idx]
test_target = test$Gross[valid_pred_idx]
train_pred = responseInvert(abs(train_pred))
test_pred = responseInvert(abs(test_pred))
train_rmse = sqrt(mean((train_pred - train_target) ^ 2))
test_rmse = sqrt(mean((test_pred - test_target) ^ 2))
train_rmse_sum = train_rmse_sum + train_rmse
test_rmse_sum = test_rmse_sum + test_rmse
}
train_rmse_mean = train_rmse_sum / NUM_ITERATIONS
test_rmse_mean = test_rmse_sum / NUM_ITERATIONS
results = rbind(results, data.frame(training_fraction = training_examples_fraction, mean = train_rmse_mean, dataset = 'train'))
results = rbind(results, data.frame(training_fraction = training_examples_fraction, mean = test_rmse_mean, dataset = 'test'))
}
return(results)
}
```
# Tasks
Each of the following tasks is worth 20 points, for a total of 100 points for this project. Remember to build each model as specified, evaluate it using the strategy outlined above, and plot the training and test errors by training set size (%).
## 1. Numeric variables
Use Linear Regression to predict `Gross` based on available _numeric_ variables. You can choose to include all or a subset of them.
```{r}
# TODO: Build & evaluate model 1 (numeric variables only)
```
```{r}
model1 = lm(Gross ~ tomatoUserRating + tomatoRating + Budget + Runtime, train)
summary(model1)
residualPlots(model1)
results = learning_curve(model1, train, test)
ggplot(results[results$mean < 10e9, ], aes(x = training_fraction, y = mean, colour=dataset, group=dataset)) +
geom_line() +
geom_point(size=3, shape=21, fill="white") +
ylab('mean RMSE')
print(formatC(min(results[results$dataset == 'test', ]$mean)), format = 'e')
```
**Q**: List the numeric variables you used.
**A**: tomatoUserRating, tomatoRating, imdbRating, Budget, Runtime, Year
**Q**: What is the best mean test RMSE value you observed, and at what training set size?
**A**: Mean RMSE of 8*10^7 at .55 training set size
## 2. Feature transformations
Try to improve the prediction quality from **Task 1** as much as possible by adding feature transformations of the numeric variables. Explore both numeric transformations such as power transforms and non-numeric transformations of the numeric variables like binning (e.g. `is_budget_greater_than_3M`).
```{r}
# TODO: Build & evaluate model 2 (transformed numeric variables only)
```
```{r}
ggplot(train, aes(x = tomatoUserRating, y = Gross)) +
geom_point() +
stat_smooth(color = "red", se = F, method = "loess")
```
```{r}
ggplot(train, aes(x = tomatoRating, y = Gross)) +
geom_point() +
stat_smooth(color = "red", se = F, method = "loess")
```
```{r}
ggplot(train[train$Budget < 1e8, ], aes(x = Budget, y = Gross)) +
geom_point() +
stat_smooth(color = "red", se = F, method = "loess")
```
```{r}
ggplot(train, aes(x = Runtime, y = Gross)) +
geom_point() +
stat_smooth(color = "red", se = F, method = "loess")
```
```{r}
powerTransform(train[, c('Gross', 'Budget', 'Runtime', 'tomatoUserRating', 'tomatoRating')])
```
```{r}
train['tomatoUserRating_bin'] = cut(train$tomatoUserRating, breaks = c(0, 2, 3.4, 4, 4.5, 5))
test['tomatoUserRating_bin'] = cut(test$tomatoUserRating, breaks = c(0, 2, 3.4, 4, 4.5, 5))
train['tomatoRating_bin'] = cut(train$tomatoUserRating, breaks = c(0, 2, 4, 6, 8, 10))
test['tomatoRating_bin'] = cut(test$tomatoUserRating, breaks = c(0, 2, 4, 6, 8, 10))
train['runtime_bin'] = cut(train$Runtime, breaks = c(0, 90, 120, 250))
test['runtime_bin'] = cut(test$Runtime, breaks = c(0, 90, 120, 250))
train['tomatoRating_8'] = train$tomatoRating > 8
test['tomatoRating_8'] = test$tomatoRating > 8
```
```{r}
model2 = lm(I(Gross ^ .23) ~ I(tomatoUserRating ^ 1.29) + tomatoRating_8 + I(Budget ^ .23) + runtime_bin, train)
summary(model2)
residualPlots(model2)
results = learning_curve(model2, train, test, responseInvert = function(v) v ^ 4.34782608696)
ggplot(results, aes(x = training_fraction, y = mean, colour=dataset, group=dataset)) +
geom_line() +
geom_point(size=3, shape=21, fill="white") +
ylab('mean RMSE')
print(formatC(min(results[results$dataset == 'test', ]$mean)), format = 'e')
```
**Q**: Explain which transformations you used and why you chose them.
**A**: I first plotted each independent variable vs the Residuals in order to spot any cases where there was visible trend. There should not be visible trend since we make the assumption of linear relationship and constant variance. We can see in tomatoUserRating, Budget, and fitted values that there is heteroskedacicity. If we plot the independent variables vs Gross we can see non-linear relationships.
I used the box-cox multivariate method to choose transformation powers in order to transform the variables to become normal and to increase the linear relationship. We can see after applying the transformation that the R^2 value increased from 0.6248 to 0.6752, a nice increase. We can also see in the residual plots that the heteroskedacitity is reduced and the plot hugs the mean of zero.
**Q**: How did the RMSE change compared to Task 1?
**A**: It decreased slightly from 7.943e+07 to 7.845e+07, or by ~1 million dollars.
## 3. Non-numeric variables
Write code that converts genre, actors, directors, and other categorical variables to columns that can be used for regression (e.g. binary columns as you did in Project 1). Also process variables such as awards into more useful columns (again, like you did in Project 1). Now use these converted columns only to build your next model.
```{r}
# TODO: Build & evaluate model 3 (converted non-numeric variables only)
numericColumns = names(train)
convertToDummyGenreVariables = function(df) {
df = df[df$Genre != 'N/A', ]
corpus = VCorpus(VectorSource(df$Genre))
dtm = DocumentTermMatrix(corpus, control = list(tokenize = Token_Tokenizer(function(s) unlist(strsplit(gsub( "[^,a-zA-Z\\s]" , "" , gsub("[[:blank:]]", "", s), perl = TRUE ), ',')))))
return(list(df = data.frame(df, as.matrix(dtm)), terms = Terms(dtm)))
}
convertToDummyActorVariables = function(df) {
df = df[df$Actor != 'N/A', ]
corpus = VCorpus(VectorSource(df$Actor))
dtm = DocumentTermMatrix(corpus, control = list(tokenize = Token_Tokenizer(function(s) unlist(strsplit(gsub( "[^,a-zA-Z\\s]" , "" , gsub("[[:blank:]]", "", s) , perl = TRUE ), ',')))))
retainIdx = seq(1, .2 * ncol(dtm))
mostFreq = sort(colSums(as.matrix(dtm)), decreasing = T)[retainIdx]
dtm = dtm[, names(mostFreq)]
return(list(df = data.frame(df, as.matrix(dtm)), terms = Terms(dtm)))
}
convertToDummyDirectorVariables = function(df) {
df = df[df$Director != 'N/A', ]
corpus = VCorpus(VectorSource(df$Director))
dtm = DocumentTermMatrix(corpus, control = list(tokenize = Token_Tokenizer(function(s) unlist(strsplit(gsub( "[^,a-zA-Z\\s]" , "" , gsub("[[:blank:]]", "", s) , perl = TRUE ), ',')))))
retainIdx = seq(1, .2 * ncol(dtm))
mostFreq = sort(colSums(as.matrix(dtm)), decreasing = T)[retainIdx]
dtm = dtm[, names(mostFreq)]
return(list(df = data.frame(df, as.matrix(dtm)), terms = Terms(dtm)))
}
convertAwards = function(df) {
df$Awards = tolower(df$Awards)
df$Nominations = parseNominations(df$Awards)
df$Nominations[is.na(df$Nominations)] = 0
df$Wins = parseWins(df$Awards)
df$Wins[is.na(df$Wins)] = 0
return(df)
}
parseNominations = function(awards) {
pattern = "(\\S+)\\s*nomination*"
match = regexec(pattern, awards)
words = regmatches(awards, match)
return(sapply(words, function(words) as.integer(words[2])))
}
parseWins = function(awards) {
pattern = "(\\S+)\\s*win*"
match = regexec(pattern, awards)
words = regmatches(awards, match)
return(sapply(words, function(words) as.integer(words[2])))
}
c(train, train_genre_terms) %<-% convertToDummyGenreVariables(train)
c(test, test_genre_terms) %<-% convertToDummyGenreVariables(test)
c(train, train_actor_terms) %<-% convertToDummyActorVariables(train)
c(test, test_actor_terms) %<-% convertToDummyActorVariables(test)
c(train, train_director_terms) %<-% convertToDummyDirectorVariables(train)
c(test, test_director_terms) %<-% convertToDummyDirectorVariables(test)
# Drop the train columns not in test
genre_intersection = intersect(train_genre_terms, test_genre_terms)
actor_intersection = intersect(train_actor_terms, test_actor_terms)
director_intersection = intersect(train_director_terms, test_director_terms)
train = train[, names(train) %in% numericColumns | names(train) %in% genre_intersection | names(train) %in% actor_intersection | names(train) %in% director_intersection]
train['winter'] = train$ReleaseMonth %in% c('12', '01', '02')
train['spring'] = train$ReleaseMonth %in% c('03', '04', '05')
train['summer'] = train$ReleaseMonth %in% c('06', '07', '08')
train['fall'] = train$ReleaseMonth %in% c('09', '10', '11')
test['winter'] = test$ReleaseMonth %in% c('12', '01', '02')
test['spring'] = test$ReleaseMonth %in% c('03', '04', '05')
test['summer'] = test$ReleaseMonth %in% c('06', '07', '08')
test['fall'] = test$ReleaseMonth %in% c('09', '10', '11')
train = convertAwards(train)
test = convertAwards(test)
```
```{r}
formulaStr = paste(paste(genre_intersection, collapse='+'), paste(actor_intersection, collapse='+'), paste(director_intersection, collapse='+'), 'Nominations + Wins + winter + fall + spring + summer + ReleaseMonth', sep='+')
formulaStr = paste('Gross', formulaStr, sep=' ~ ')
formula = as.formula(formulaStr)
model3 = lm(formula, train)
summary(model3)
results = learning_curve(formula, train, test)
ggplot(results[results$mean < 5e8, ], aes(x = training_fraction, y = mean, colour=dataset, group=dataset)) +
geom_line() +
geom_point(size=3, shape=21, fill="white") +
ylab('mean RMSE')
print(formatC(min(results[results$dataset == 'test', ]$mean)), format = 'e')
```
**Q**: Explain which categorical variables you used, and how you encoded them into features.
**A**: I used the top 25% in frequency directors and actors and all genres. I also converted released date into a month since release month was shown to be indicative of Gross in the EDA exercise. I binned release month into seasons in case the season is more indicative of Gross than the individual month is. Awards were preprocessed the same as in project 1, using regex to search for the words "win" or "nomination" and added two corresponding columns.
**Q**: What is the best mean test RMSE value you observed, and at what training set size? How does this compare with Task 2?
**A**: The best RMSE is 1.097e+08 at a training set size of .78. This is is an order of magnitude worse than in task 2.
## 4. Numeric and categorical variables
Try to improve the prediction quality as much as possible by using both numeric and non-numeric variables from **Tasks 2 & 3**.
```{r}
# TODO: Build & evaluate model 4 (numeric & converted non-numeric variables)
formulaStr = paste('I(tomatoUserRating ^ 1.29) + tomatoRating_8 + I(Budget ^ .23) + Nominations', paste(genre_intersection, collapse='+'), sep='+')
formulaStr = paste('I(Gross ^ .23)', formulaStr, sep=' ~ ')
formula = as.formula(formulaStr)
model4 = lm(formula, train)
summary(model4)
results = learning_curve(formula, train, test, responseInvert = function(v) v ^ 4.34782608696)
ggplot(results[results$mean < 5e8, ], aes(x = training_fraction, y = mean, colour=dataset, group=dataset)) +
geom_line() +
geom_point(size=3, shape=21, fill="white") +
ylab('mean RMSE')
print(formatC(min(results[results$dataset == 'test', ]$mean)), format = 'e')
```
**Q**: Compare the observed RMSE with Tasks 2 & 3.
**A**: The RMSE did not decrease much from task 2 however as expected increased from task 3 since the RMSE of task 3 was much lower than in task 2. However the R^2 increased from .67 to .7 indicating a better fit.
## 5. Additional features
Now try creating additional features such as interactions (e.g. `is_genre_comedy` x `is_budget_greater_than_3M`) or deeper analysis of complex variables (e.g. text analysis of full-text columns like `Plot`).
```{r}
# TODO: Build & evaluate model 5 (numeric, non-numeric and additional features)
ggplot(train[train$tomatoRating > 2.5, ], aes(x = tomatoRating, y = Gross, colour=runtime_bin, group=runtime_bin)) +
geom_point()
ggplot(train, aes(x = tomatoRating, y = Gross, colour=drama, group=drama)) +
geom_point()
ggplot(train, aes(x = tomatoRating, y = Gross, colour=comedy, group=comedy)) +
geom_point()
ggplot(train, aes(x = tomatoRating, y = Gross, colour=horror, group=horror)) +
geom_point()
```
```{r}
ggplot(train[train$tomatoUserRating > 2, ], aes(x = tomatoUserRating, y = Gross, colour=runtime_bin, group=runtime_bin)) +
geom_point()
ggplot(train, aes(x = tomatoUserRating, y = Gross, colour=drama, group=drama)) +
geom_point()
ggplot(train, aes(x = tomatoUserRating, y = Gross, colour=comedy, group=comedy)) +
geom_point()
ggplot(train, aes(x = tomatoUserRating, y = Gross, colour=horror, group=horror)) +
geom_point()
```
```{r}
train['budget_bin'] = cut(train$Budget, breaks = quantile(train$Budget))
test['budget_bin'] = cut(test$Budget, breaks = quantile(test$Budget))
ggplot(train, aes(x = tomatoUserRating, y = Gross, colour=budget_bin, group=budget_bin)) +
geom_point()
ggplot(train, aes(x = tomatoRating, y = Gross, colour=budget_bin, group=budget_bin)) +
geom_point()
```
```{r}
ggplot(train, aes(x = Nominations, y = Gross, colour=tomatoRating_bin, group=tomatoRating_bin)) +
geom_point()
ggplot(train, aes(x = Nominations, y = Gross, colour=tomatoUserRating_bin, group=tomatoUserRating_bin)) +
geom_point()
ggplot(train, aes(x = Nominations, y = Gross, colour=drama, group=drama)) +
geom_point()
ggplot(train, aes(x = Nominations, y = Gross, colour=comedy, group=comedy)) +
geom_point()
ggplot(train, aes(x = Nominations, y = Gross, colour=horror, group=horror)) +
geom_point()
ggplot(train, aes(x = Nominations, y = Gross, colour=action, group=action)) +
geom_point()
```
```{r}
formulaStr = paste('I(tomatoUserRating ^ 1.29) + tomatoRating_8 + I(Budget ^ .23) + Nominations + tomatoRating:drama + tomatoRating:horror + tomatoRating:Nominations', paste(genre_intersection, collapse='+'), sep='+')
formulaStr = paste('I(Gross ^ .23)', formulaStr, sep=' ~ ')
formula = as.formula(formulaStr)
model4 = lm(formula, train)
summary(model4)
results = learning_curve(formula, train, test, responseInvert = function(v) v ^ 4.34782608696)
ggplot(results[results$mean < 5e8, ], aes(x = training_fraction, y = mean, colour=dataset, group=dataset)) +
geom_line() +
geom_point(size=3, shape=21, fill="white") +
ylab('mean RMSE')
print(formatC(min(results[results$dataset == 'test', ]$mean)), format = 'e')
```
**Q**: Explain what new features you designed and why you chose them.
**A**: I added interactions terms between variables. The ones I added were tomatoRating:drama, tomatoRating:horror, tomatoRating:Nominations. The reason why I added these is because I plotted several variables against Gross, using a third variable as a color-coding. I was looking for situations where the third variable impacted the response based on the dependent variable on the x axis. Examples of this include tomatoRating and drama, where if the movie is drama and the tomatoRating is high, it looks like the Gross is less than if the movie is not drama and the tomato rating is low. Another example is Nominations and drama, where if the movie is drama and has a lot of nominations, the Gross is less than a non-drama movie with fewer nominations.
**Q**: Comment on the final RMSE values you obtained, and what you learned through the course of this project.
**A**: The final RMSE is 7.479e+07 which is a decrease from the previous best of 7.498e+07, or a decrease of about 200 thousand dollars. Through this project I learned how to analyze a multivariate linear regression to determine if the assumptions of the linear model are met, and if they are not how to fix them. I learned how to transform numeric variables and categorical variables to include in the model. I also learned how to identify interactions between variables and how to include it in the model.