-
Notifications
You must be signed in to change notification settings - Fork 0
/
Bernauer_Andrew_final.Rmd
1262 lines (674 loc) · 35.1 KB
/
Bernauer_Andrew_final.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: "Final Report"
author: "Andrew Bernauer"
date: "April 30, 2019"
output: html_document
---
#Difficult Learning Problems in Economics: Predicting Ether Price
#a) Introduction
For the semester long project I will be attempting to predict the known response variable ethereum price in terms of the predictors: block size, network hash rate growth rate, transactions, day of the week, and month. The project is regression based and not a classification task. Therefore the project will fall under the umbrella of supervised machine learning.
$$\text{ether price} \approx \beta_{o} + \beta_{1} \times \text{blocksize} + \beta_{2} \times \text{networkhashgrowthrate} + \beta_{3} \times \text{transactions} + \beta_{4} \times \text{day} + \beta_{5} \times \text{month} $$
Ethereum is a decentralized, open source, block chain technology, featuring smart contracts. The crypto currency that fuels the Ethereum block chain is Ether. Block size refers to the size of the Ethereum Block chain. Transactions are the number of transactions approved by the ledger. Hash rate is the rate at which it takes a miner to complete a Cryptographic computation on the block chain.
```{r data carpentry, cache=FALSE}
library(scales)
library(ggplot2)
library(lubridate)
library(purrr)
library(dplyr)
library(readr)
library(tibble)
library(errorist)
library(broom)
library(caret)
library(tidyr)
library(randomForest)
library(gbm)
#substitute in the path on your machine to files
ethereum_transaction_history <- read_csv("C:\\Users\\andre\\Documents\\ECON_490_ML\\ML_report 1\\ethereum-historical-data\\EthereumTransactionHistory.csv")
ethereum_block_size <-read_csv("C:\\Users\\andre\\Documents\\ECON_490_ML\\ML_report 1\\ethereum-historical-data\\EthereumBlockSizeHistory.csv"
)
ethereum_network_hash_rate <- read_csv("C:\\Users\\andre\\Documents\\ECON_490_ML\\ML_report 1\\ethereum-historical-data\\EthereumNetworkHashRateGrowthRate.csv")
ether_price <- read_csv("C:\\Users\\andre\\Documents\\ECON_490_ML\\ML_report 1\\ethereum-historical-data\\EtherPriceHistory(USD).csv")
# creating variable for day
day_of_week <-
lubridate::mdy(ether_price$`Date(UTC)`) %>%
wday( ,label=TRUE) %>%
sort()
# creating variable for month
month_of_year <-
lubridate::mdy(ether_price$`Date(UTC)`) %>%
month( ,label=TRUE) %>%
sort()
signedlog10 <- function(x) {
ifelse(abs(x) <= 1, 0, sign(x)*log10(abs(x)))
}
log_price <- signedlog10(ether_price[[3]])
log_history <- signedlog10(ethereum_transaction_history[[3]])
log_block_size <- signedlog10(ethereum_block_size[[3]])
log_hash_rate <- signedlog10(ethereum_network_hash_rate[[3]])
summary(log_price)
summary(log_history)
# construct list of variables to coerce into a tibble
l_ether <- list( price = ether_price[[3]],
transaction_history = as.integer(ethereum_transaction_history[[3]]),
block_size = as.integer(ethereum_block_size[[3]]),
hash_rate = ethereum_network_hash_rate[[3]],
day = day_of_week,
month = month_of_year,
date_utc = mdy(ethereum_network_hash_rate$`Date(UTC)`),
unix_time_stamp = ethereum_network_hash_rate$UnixTimeStamp,
log_10_price = log_price,
log_10_trans_history = log_history,
log_10_block_size = log_block_size,
log_10_hash_rate = log_hash_rate)
ether_df <- as_tibble(l_ether)
xs <-function(x){(x-mean(x))/(2*sd(x))}
```
```{r price_vs_time, warning=FALSE, cache=TRUE}
price_history <- ggplot(ether_df) +
aes(date_utc, price) +
geom_line(color="purple") +
xlab("Year")+
ggtitle("Ethereum Price USD over time") +
scale_y_log10()
price_history
```
The price doesn't seem move at all significantly until 2016 so I decided to use a log transformation to the y axis. This removed a large amount the visual noise and made the price change overtime more evident. Besides that ethereum price starts to rise from around a dollar price to hovering around the ten dollars between 2016 and 2017. Peaks at a value of 1000 dollars in 2018.
```{r block_size, cache=TRUE}
block_history <- ggplot(ether_df) +
aes(date_utc, block_size) +
geom_line(color ="purple") +
scale_y_log10() +
xlab("Year") +
ylab("Block Size") +
ggtitle("Ethereum Block Size Over Time")
block_history
```
Block size rises exponentially begining in 2017. Prior to this it fluctuates up and down between 1000 and 3000 which might be pointing to autocorrelation. In this same time period it peaks violently at 10000. Reaching a maximum of over 30000 in 2018. Another log tranformation was used in this plot.
```{r network hashrate, cache=TRUE}
hashrate_history <- ggplot(ether_df) +
aes(date_utc, hash_rate) +
geom_line(color="purple") +
scale_y_log10() +
xlab("Year") +
ylab("Network Hash rate Growth rate") +
ggtitle("Ethereum Network Hash rate growth over time")
hashrate_history
```
Network hashrate growth blows up exponentially and seems to follow that trend overtime.
```{r transaction history, warning=FALSE, cache=TRUE}
transaction_history <- ggplot(ether_df) +
aes(date_utc, transaction_history) +
geom_line(color="purple") +
xlab("Year") +
ylab("Transactions") +
scale_y_log10() +
ggtitle("Ethereum Transactions over time")
transaction_history
```
Transactions on the the Ethereum network are growing significantly overtime and more people are embracing it's use.
```{r bonus plot from eda, warning= FALSE, cache=TRUE}
price_plot <- ggplot(ether_df) +
aes(transaction_history, price) +
geom_point(colour="purple") +
facet_wrap(~month) +
geom_smooth(colour="yellow", alpha = 0.25)
price_plot +
scale_x_log10("Transactions") +
scale_y_log10("Ethereum Price USD($)") +
ggtitle("Ethereum Price USD($) vs Transactions facetted by month")
```
There appears to be some clustering of Ether price as transactions increases on the block chain increase isolating by month.
```{r}
library(ggplot2)
p <- ggplot(ether_df) +
aes(x=log_10_hash_rate) +
geom_histogram(bins = 34, fill = "purple") +
ggtitle(label = "Histogram of the distribution of hash rate log 10 scale") +
xlab("Distribution of log 10 transactions") +
ylab("Count")
p
```
Many of the $X_{1}, X_{2}, \dots, X_{n}$ or predictor variables in the dataset follow skewed distribution and feature multiple peaks. This could be pointing to the presence of sub-populations within the underlying data.
```{r hist block_size,}
ggplot(ether_df) +
aes(log_block_size) + geom_histogram(bins = 34, fill = 'purple') +
xlab("Distribution of Ethereum BlockSize log 10 scale") +
ylab("Count") +
ggtitle("Histogram of Ethereum block size")
```
Likewise, blocksize has this similar property this sort of distribution doesn't suit itself well, for standard machine learning algorithms given the multiple peaks. Most of the variables follow gamma distributions in the cartesian coordinate scale. I declined to illustrate those graphs.
#b.) Summary Statistics
```{r tidy_summary_code}
#summary stats for ethereum price
ether_df %>% summarise(mean_price = mean(price, na.rm = TRUE), median_price = median(price), sd_price = sd(price), iqr_price = IQR(price), n = n(), mad_price = mad(price), min_price = min(price), max_price = max(price))
#summary stats for ethereum transaction history
ether_df %>% summarise(mean_transaction_history = mean(transaction_history), median_transaction_history = median(transaction_history), sd_transaction_history = sd(transaction_history), iqr_transaction_history = IQR(transaction_history), n = n(), mad_transaction_history = mad(transaction_history), min_transaction_history = min(transaction_history), max_transaction_history = max(transaction_history))
#summary stats for ethereum block size
ether_df %>% summarise(mean_block_size = mean(block_size), median_block_size = median(block_size), sd_block_size = sd(block_size), iqr_block_size = IQR(block_size), n = n(), mad_block_size = mad(block_size), min_block_size = min(block_size), max_block_size = max(block_size))
#summary stats for hash rate
ether_df %>% summarise(mean_hash_rate = mean(hash_rate), median_hash_rate = median(hash_rate), sd_hash_rate= sd(hash_rate), iqr_hash_rate = IQR(hash_rate), n = n(), mad_hash_rate = mad(hash_rate), min_hash_rate = min(hash_rate), max_hash_rate = max(hash_rate))
```
#c) Linear Regressions
```{r regressions,}
#running five regressions
poly_reg <- lm(price ~ poly(transaction_history, 5) + poly(block_size, 5) + poly(hash_rate, 5), ether_df )
reg_obj <- lm(log(price) ~ log(block_size) + log(transaction_history) + log(hash_rate), data = ether_df, subset = price > 0)
reg_obj_2 <- lm(log(price) ~ log(transaction_history) + log(hash_rate), data = ether_df, subset = price > 0)
reg_obj_3 <- lm(price ~ I(block_size)^2 + sqrt(transaction_history) + hash_rate, data = ether_df)
mols <- lm(price ~ block_size + transaction_history + hash_rate, data = ether_df)
log_ols <- lm(log(price) ~ log(transaction_history), data = ether_df, subset = price > 0)
```
The following code block returns the adjusted $\hat{R}^{2}_{\text{adjusted}}$ statistics for the five regressions I ran.
```{r, cache=TRUE}
tidy_reg_obj <- reg_obj %>%
tidy()
tidy_reg_obj
```
```{r}
glance_tidy_poly <- glance(poly_reg)
glance_reg_obj <- glance(reg_obj)
glance_reg_obj_2 <- glance(reg_obj_2)
glance_reg_obj_3 <- glance(reg_obj_3)
glance_mols <- glance(mols)
glance_log_ols <- glance(log_ols)
glance_tidy_poly$adj.r.squared
glance_reg_obj$adj.r.squared
glance_reg_obj_2$adj.r.squared
glance_reg_obj_3$adj.r.squared
glance_mols$adj.r.squared
glance_log_ols$adj.r.squared
```
All of the coefficients return p values significant at the .10 cut off level while log block size is close. The $F$ statistic is significant; however the BIC and AIC below could be lower.
The log-log model with all the continuous predictors included had the highest adjusted $\,$
$\hat{R}^{2}_{\text{adjusted}} = 0.9363884$ $\,$ of all the regressions ran. A model excluding the log block size term comes in a close second. Another, option is the last model with just log transaction as a predictor.
Predictors performing the best presented the following equation $$ \hat{y} = -10.65 + 0.072 \log(\text{Blocksize}) + 1.0007 \log(\text{TransactionHistory}) + 0.222\log(\text{Hashrate}) $$.
Which can be interpreted as a one percent increase in Blocksize resulting in a 7.2 percent increase in average Ether price holding all other variables equal, or fixed. The same interpretation applies to the other predictors with there respective coefficients.
```{r augment, cache=TRUE}
augmented_reg_obj <- reg_obj %>%
augment()
some_plot <- ggplot(data = augmented_reg_obj, aes(log.price., .hat)) +
geom_point(color = "purple", size = 1) +
labs(x="log(price)", y="y hat") +
ggtitle("Log price vs Y hat")
some_plot
```
The preceding plot points to the non-linear nature of the data set. It may improve modeling results to include a polynomial term in future models.
```{r, warning=FALSE}
tidy_conf_it <- tidy(reg_obj, conf.int = TRUE)
confint_plot <- ggplot(tidy_conf_it, aes(term, estimate, color=term)) +
geom_point() +
geom_errorbar(aes(ymin=estimate - 1.96*std.error, ymax=estimate + 1.96*std.error))
confint_plot +
ggtitle("Coefficients with standard errors") +
scale_x_discrete()
```
The previous graph is misleading due to the scale with a scale adjustment it is more insightful.
```{r proper scale, warning=FALSE}
confint_plot +
scale_y_log10() +
ggtitle("Coefficients with standard errors log-log scale") +
scale_x_discrete()
```
```{r}
some_plot_2 <- ggplot(data = augmented_reg_obj, aes(.resid)) +
geom_histogram(binwidth = .3, fill = "purple") +
labs(x="Residuals", y="Frequency") +
ggtitle("Distribution of Residuals")
some_plot_2
```
The majority of the residuals are distributed between -1 and 1 peaking at zero. This distribution is similar to the laplace distribution.
```{r, warning= FALSE}
some_plot_3 <- ggplot(augmented_reg_obj, aes(log.price., .resid)) +
geom_point(color = "purple", size = 1) +
geom_hline(color = "yellow", yintercept = 0)
some_plot_3 +
labs(x="Log Ether Price", y="Residuals")
```
The Residuals plotted against Ether Price suggest there is possible non-normality in the distribution of the errors.
## d. and e.) Ridge and Lasso Regressions
```{r 1) 2) d) }
library(glmnet)
library(caret)
set.seed(385)
train_df <- ether_df %>% sample_frac(0.75)
test_df <- ether_df %>% setdiff(train_df)
train_df <- train_df[, -9, drop=FALSE]
test_df <- test_df[, -9, drop=FALSE]
covariates_train <- model.matrix(price~. , data = train_df)[, c(-1, -9), drop=FALSE]
covariates_test <- model.matrix(price~. , data=test_df)[, c(-1, -9), drop=FALSE]
response_train <- as.numeric(unlist(train_df[[1]]))
response_test <- as.numeric((unlist(test_df[[1]])))
grid <- 10^seq(5, -5, length.out = 100)
ridge_model <- glmnet(covariates_train, response_train, alpha = 0, family ="gaussian")
plot.glmnet(ridge_model, xvar = "lambda")
lasso_model <- glmnet(covariates_train, response_train, alpha = 1, family = "gaussian")
plot.glmnet(lasso_model, xvar = "lambda", label = "true")
```
A $\lambda = 49.75$, for the hyperparameter of the ridge model significantly penalizes the coefficients of the model. Shrinking all of the coefficients close to zero displayed in the plot above.
Additionally, the lasso model has a $\lambda = 2.26$ which ends up culling eleven of the twenty five coefficients assocaited with the model matrix. Which is evident in the plot above.
```{r 2a)}
set.seed(385)
cv_lasso <- cv.glmnet(covariates_train, train_df$price, alpha=1)
plot(cv_lasso)
set.seed(385)
cv_ridge <- cv.glmnet(covariates_train, train_df$price, alpha=0)
plot(cv_ridge)
best_lambda_ridge <- cv_ridge$lambda.1se
best_lambda_lasso <- cv_lasso$lambda.1se
print(best_lambda_ridge)
print(best_lambda_lasso)
```
I elect to pick a lambda within one standard deviation as a way to avoid overfitting the model to the training data and performing poorly on the test data.
```{r 2) e)}
ridge_coefficients <- coef.glmnet(cv_ridge, newx = covariates_train, s = best_lambda_ridge)
lasso_coef <- coef.glmnet(cv_lasso, newx = covariates_train, s = best_lambda_lasso)
print(lasso_coef)
print(ridge_coefficients)
```
Lasso as an operator ending up culling the following coefficients: day.L, day.Q, day.C, day^4, Month.L, date_utc, unix_timestamp, and the other coefficients for transaction history, block size, hash rate in the log 10 scale. The model coefficients are not the most interpratable as they were produced via the model matrix
The same can be said for the ridge regression model.
```{r 2) g),}
lasso_test_pred = predict.glmnet(lasso_model, newx = covariates_test, s=best_lambda_lasso)
ridge_test_pred = predict.glmnet(ridge_model, newx = covariates_test, s=best_lambda_ridge)
lasso_mse <- mean((response_test - lasso_test_pred) ^ 2)
ridge_mse <- mean((response_test - ridge_test_pred) ^ 2)
```
The **Lasso ** model returned an $MSE$ of 88166.71 while the **Ridge** model returned a more modest $MSE$ of 6682.426 on the test sets respectively. The Ridge regression model returns the lowest $MSE $of the two methods though the performance is not great.
##f.) Regression trees
```{r 3) a-d, }
library(tree)
set.seed(385)
ether_tree <- tree(price~., data = train_df)
cv_tree <- cv.tree(ether_tree, K=10 )
plot(cv_tree$size, cv_tree$dev, type = 'b')
pruned_tree_df <- prune.tree(ether_tree, best = 5)
plot(pruned_tree_df)
text(pruned_tree_df, pretty = 0)
treee_fit = predict(pruned_tree_df, newdata = test_df)
single_tree_fit <- mean((response_test - treee_fit) ^ 2)
single_tree_fit
```
Variables used in the final pruned tree are: transaction history which represent the number of transactions on the Ethereum block chain and unix time stamp which is a running count of the seconds since Jan 01 1970. The root of the tree includes a split with the variable transaction history splitting on the condition that if transaction history is less than one hundred sixty two thousand six hundred and eighty three transactions. After that split follows, another if then style statement with $\text{transaction history} < 162,683$ yielding an average ether price prediction of 13.83. On the other hand if that condition is not satisfied average ether price yields a prediction of 288.50. The splits on the other side of the tree include a split, for $\text{transaction history} < 876,929 $, and if $\text{transaction history} > 867,929$ yields an average ether price prediction of $ 960.40$. Under the split above is another split under unix time which essentially prefers ether price fall over time.
The pruned regression tree contains a total of five terminal nodes each displaying the average prediction based on those splits in the tree. The splits function to partition space into mutually exclusive regions.
The $MSE$ of the bootstrapped trees is a performance upgrade over the results from the previous performance of the single regression tree trained on the training data. This is not completely surprising as we would expect the model to perform better on our training data and to underperform on the test data. Surprisingly though I was able to get an $MSE$ that was significanctly better accross multiple seeds and fitting trees which is promising, for future reports. Of course there is a trade-off in that we don't want our model to overfit the training data and not perform well on the test set.
```{r #1, #2}
set.seed(385)
new_train_ether <- ether_df[, -9, drop=FALSE] %>%
sample_frac(0.7)
new_test_ether <- ether_df[, -9, drop=FALSE] %>%
setdiff(new_train_ether)
bagged.ether <- randomForest(price ~ ., data = new_train_ether,
ntree=400, mtry=4, importance=TRUE)
bagged.ether
```
# g.) Bagging
```{r}
plot(bagged.ether)
```
The Errors start to level off as trees start approaching the 50 to 75 tree range. Increasing the number of trees does not impact the error rate that much, as the number of trees gets large.
```{r}
yhat_bagged <- predict(bagged.ether, newdata = new_test_ether)
ggplot() + geom_point(aes(x = yhat_bagged, y = price), data = new_test_ether, color = "purple", alpha = 0.50) + geom_abline(color = "yellow") +
labs(x="Bagging Estimation of Ether", y="Ether test Price", title="Bagging Estimation of Ether vs Actual Test Ether Price")
```
The Bagging estimation of Ether Price presents some of the best predictions on the test set of all methods. However the fit is not as tight as Ether Price increases. In addition it is an improvement over the bootstrapped version of the trees from my previous report.
```{r}
bagging_mse <- round(mean((new_test_ether$price - yhat_bagged)^2), 2)
bagging_mse
lasso_mse
ridge_mse
```
The bagging model is the best $MSE = 1023.55$; compared to the large $MSE = 5159.674$ for lasso and the large mse of $MSE = 6704.901$ for ridge regression. Meaning that the model has less variance in performance about the mean.
```{r, 2e)}
importance(bagged.ether)
```
```{r}
varImpPlot(bagged.ether)
```
In terms of important variables for the bagging model date, unix time stamp, log_10_transaction history, and transaction history have the largest increased percentage in the mean squared errors. It is a more robust measure of error versus the IncNodePurity.
# h.) Random Forest
```{r}
set.seed(385)
ether_forest <- randomForest(price ~ ., data = new_train_ether,
mtry = 10,
importance = TRUE,
do.trace = 100)
plot(ether_forest)
```
Error mostly flat lines as number of trees approaches 50.
```{r}
y_hat_rf <- predict(ether_forest, newdata = new_test_ether)
```
```{r}
# Set mtry using hyperparamter tuning
oob_err <- double(10)
test_err <- double(10)
#mtry is no of Variables randomly chosen at each split
for(mtry in 1:10)
{
rf_ether <- randomForest(price ~ . , data = new_train_ether, mtry=mtry, ntree=400)
oob_err[mtry] <- rf_ether$mse[400] #Error of all Trees fitted on training
pred <- predict(rf_ether, new_test_ether) #Predictions on Test Set for each Tree
test_err[mtry] <- with(new_test_ether, mean( (price - pred)^2)) # "Test" Mean Squared Error
print(mtry)
}
```
```{r}
round(test_err, 2)
```
```{r}
round(oob_err, 2)
```
An mtry of four returns the lowest out of bag error for random forest.
```{r}
rf.opt <- randomForest(price ~ ., data = new_train_ether, n_tree = 400, mtry = 4)
y_hat_rf_opt <- predict(rf.opt, newdata = new_test_ether)
ggplot() + geom_point(aes(x = y_hat_rf_opt, y = new_test_ether$price), color = "purple", alpha=0.5) + geom_abline(color = "yellow") +
labs(x="Random Forest estimation of Ether Price", y="Ether Price", title = "Random Forest estimation of Ether Price vs Actual Ether Price")
```
The residuals increase as Ether Price increases similar to other tree based methods, but has one of the best fits of all the tree based models.
```{r}
mse_random_forest <- round(mean((new_test_ether$price - y_hat_rf_opt)^2))
lasso_mse
ridge_mse
bagging_mse
mse_random_forest
```
Random forest fits Ether Price really well better than any other models used so far, except bagging.
```{r}
varImpPlot(rf.opt)
```
Like the other tree based models random forest emphasizes the importance of transaction history as well as time.
```{r}
matplot(1:mtry , cbind(oob_err,test_err), pch=20 , col=c("red","blue"),type="b",ylab="Mean Squared Error",xlab="Number of Predictors Considered at each Split")
legend("topright",legend=c("Out of Bag Error","Test Error"),pch=19, col=c("red","blue"))
```
The ideal number of predictors Considered at each split is different depending on whether our goal is to minimize the mean squared error of the test error or the out of bag error the best number of predictors to consider at each split happens to be 4 predictors. While 7 predictors allow for a minimized mean squared error. However; for cross validation we will use the ideal number of predictors based on the out of bag error.
# i.) Boosting
```{r}
set.seed(385)
boosting_ether <- gbm(price ~ . -date_utc,
data = new_train_ether,
distribution = "gaussian",
n.trees = 5000,
interaction.depth = 4)
summary(boosting_ether)
```
Transaction history, Unix time stamp, and hash rate are all displayed as important variables according to the importance matrix. Transaction history carries the largest relative importance of all the variables at a value of 76.36 pecent. While unix time stamp has an importance of 11.67 percent which is not very significant. The only other variable containing a significant amount of importance is network hash rate.
```{r}
yhat_boost <- predict(boosting_ether, newdata = new_test_ether, n.trees = 5000)
ggplot() + geom_point(aes(x = yhat_boost, y = new_test_ether$price), color = "purple", alpha=0.5) + geom_abline(color = "yellow") +
labs(x="Boosting Estimation of Ether Price", y="Ether Price test set", title = "Boosting Estimation of Ether Price vs Actual Ether Price")
```
Boosting is a relatively viable modeling technique, for predicting ether price given the fit above.
```{r}
boosting_mse <- mean((new_test_ether$price - yhat_boost)^2)
boosting_mse
lasso_mse
ridge_mse
bagging_mse
```
Boosting returns a very low Mean Square error of 1023.55.
## j.) XGboost
```{r}
library(xgboost)
f <- price ~ transaction_history + block_size + hash_rate + day + month + unix_time_stamp + log_10_trans_history + log_10_block_size + log_10_hash_rate
X_training <- model.matrix(f, data = new_train_ether)
Y_training <- as.matrix(new_train_ether$price)
d_train <- xgb.DMatrix(data = X_training, label = Y_training)
X_test <- model.matrix(f, data = new_test_ether)
set.seed(385)
ether.xgb = xgboost(data=d_train,
max_depth=5,
eta = 0.1,
nrounds=40,
lambda=0,
print_every_n = 10,
objective="reg:linear")
```
```{r}
yhat_xgboost <- predict(ether.xgb, newdata = X_test)
ggplot() + geom_point(aes(x = yhat_xgboost, y = price), data = new_test_ether, color = "purple", alpha = 0.25) +
geom_abline(color = "yellow") +
labs(x="Xgboost estimation of ether price", y="Actual ether price", title = "Xgboost estimation of Ether price vs Actual Test ether price")
```
The xgboosted model performs relatively strong, but like other tree based models the fit is not as good as Ether Price increases.
```{r}
xg_boosted_mse <- mean((new_test_ether$price - yhat_xgboost)^2)
lasso_mse
ridge_mse
bagging_mse
mse_random_forest
boosting_mse
xg_boosted_mse
```
An MSE of 1415.984 is returned by the xgboosted model is respectable in comparison to boosting and the other tree-based methods, but does not perform aswell as Random Forest or gradient boosting.
```{r}
importance_xgb <- xgb.importance(colnames(X_training), model = ether.xgb)
importance_xgb
xgb.plot.importance(importance_matrix = importance_xgb, rel_to_first = TRUE, xlab="Relative Importance")
```
Transaction history displays an overwhelming level of relative importance for the xgboosted model as shown above. With time or unix time stamp being the only other important variable.
```{r}
library(caret)
f <- price ~ transaction_history + block_size + hash_rate + day + month + unix_time_stamp + log_10_trans_history + log_10_block_size + log_10_hash_rate
X_training <- model.matrix(f, data = new_train_ether)
Y_training <- as.matrix(new_train_ether$price)
d_train <- xgb.DMatrix(data = X_training, label = Y_training)
X_test <- model.matrix(f, data = new_test_ether)
params_xgboost <- list(nrounds = seq(40, 250, 5),
max_depth = 4,
eta = seq(2, 30,5)/60,
gamma = 1,
colsample_bytree = 1,
min_child_weight = 9,
subsample = 1.0
)
hyper_grid_xgboost <- expand.grid(params_xgboost)
xgb_control <- trainControl(method="cv",
number = 3)
set.seed(385)
xgboost_tuned <- train(price~.,
data=new_train_ether,
trControl=xgb_control,
tuneGrid=hyper_grid_xgboost,
lambda=0,
method="xgbTree")
xgboost_tuned$bestTune
```
An $\eta = 0.2$ implies the model starts out as a slow learner and requires a larger number of boosting iterations to perform well, but is more robust to errors as a result.
```{r}
plot(xgboost_tuned)
```
The previous plot shows this as the case.
```{r}
tuned.xgb <- xgb.train(params = xgboost_tuned$bestTune,
data = d_train,
nrounds = 225)
yhat_xgboost_tuned <- predict(tuned.xgb, X_test)
tuned_xgboost_mse <- mean((yhat_xgboost_tuned - new_test_ether$price)^2)
tuned_xgboost_mse
xg_boosted_mse
```
The hyper-paramater tuned model only offers a marginal decrease in the $MSE$ aproximately 56.
```{r}
gbm.grid <- expand.grid(interaction.depth = c(1, 4, 5, 9),
n.trees = (1:100)*50,