# Section - 8 Evaluate Model Performance

Now we get to see the results of our hard work! There are some additional data preparation steps we need to take before we can visualize the results in aggregate; if you are just looking for the charts showing the results they are shown later on in the “Visualize Results” section below.

## 8.1 Summarizing models

Because we know what really happened for the target variable in the test data we used in the previous step, we can get a good idea of how good the model performed on a dataset it has never seen before. We do this to avoid overfitting, which is the idea that the model may work really well on the training data we provided, but not on the new data that we want to predictions on. If the performance on the test set is good, that is a good sign. If the data is split into several subsets and each subset has consistent results for the training and test datasets, that is an even better sign the model may perform as expected.

The first row of the data is for the BTC cryptocurrency for the split number 1. For this row of data (and all others), we made predictions for the test_data using a linear regression model and saved the results in the lm_test_predictions column. The models were trained on the train_data and had not yet seen the results from the test_data, so how accurate was the model in its predictions on this data?

### 8.1.1 MAE

Each individual prediction can be compared to the observation of what actually happened, and for each prediction we can calculate the error between the two. We can then take all of the values for the error of the prediction relative to the actual observations, and summarize the performance as a Mean Absolute Error (MAE) of those values, which gives us a single value to use as an indicator of the accuracy of the model. The higher the MAE score, the higher the error, meaning the model performs worse when the value is larger.

### 8.1.2 RMSE

A common metric to evaluate the performance of a model is the Root Mean Square Error, which is similar to the MAE but squares and then takes the square root of the values. An interesting implication of this, is that the RMSE will always be larger or equal to the MAE, where a large degree of error on a single observation would get penalized more by the RMSE. The higher the RMSE value, the worse the performance of the model, and can range from 0 to infinity, meaning there is no defined limit on the amount of error you could have (unlike the next metric).

### 8.1.3 R Squared

The $$R^2$$, also known as the coefficient of determination, is a measure that describes the strength in the correlation between the predictions made and the actual results. A value of 1.0 would mean that the predictions made were exactly identical to the actual results. A perfect score is usually concerning because even a great model shouldn’t be exactly 100% accurate and usually indicates a mistake was made that gave away the results to the model and would not perform nearly as good when put into practice in the real world, but in the case of the $$R^2$$ the higher the score (from 0 to 1) the better.

### 8.1.4 Get Metrics

We can return the RMSE and $$R^2$$ metrics for the BTC cryptocurrency and the split number 1 by using the postResample() function from the caret package:

postResample(pred = cryptodata_nested$lm_test_predictions[[1]], obs = cryptodata_nested$test_data[[1]]$target_price_24h) ## RMSE Rsquared MAE ## 260.560193954 0.002833784 236.892256914 We can extract the first element to return the RMSE metric, and the second element for the R Squared (R^2) metric. We are using [[1]] to extract the first element of the lm_test_predictions and test_data and compare the predictions to the actual value of the target_price24h column. This model used the earliest subset of the data available for the cryptocurrency. How does the same model used to predict this older subset of the data perform when applied to the most recent subset of the data from the holdout? We can get the same summary of results comparing the lm_holdout_predictions to what actually happened to the target_price_24h column of the actual holdout_data: postResample(pred = cryptodata_nested$lm_holdout_predictions[[1]],
obs = cryptodata_nested$holdout_data[[1]]$target_price_24h)
##       RMSE   Rsquared        MAE
##         NA 0.02235188         NA

The result above may show a value of NA for the RMSE metric. We will explain and resolve the issue later on.

### 8.1.5 Comparing Metrics

Why not just pick one metric and stick to it? We certainly could, but these two metrics complement each other. For example, if we had a model that always predicts a 0% price change for the time period, the model may have a low error but it wouldn’t actually be very informative in the direction or magnitude of those movements and the predictions and actuals would not be very correlated with each other which would lead to a low $$R^2$$ value. We are using both because it helps paint a more complete picture in this sense, and depending on the task you may want to use a different set of metrics to evaluate the performance. It is also worth mentioning that if your target variable you are predicting is either 0 or 1, this would be a classification problem where different metrics become more appropriate to use.

These are indicators that should be taken with a grain of salt individually, but comparing the results across many different models for the same cryptocurrency can help us determine which models work best for the problem, and then comparing those results across many cryptocurrencies can help us understand which cryptocurrencies we can predict with the most accuracy.

Before we can draw these comparisons however, we will need to “standardize” the values to create a fair comparison across all dataasets.

## 8.2 Data Prep - Adjust Prices

Because cryptocurrencies can vary dramatically in their prices with some trading in the tens of thousands of dollars and others trading for less than a cent, we need to make sure to standardize the RMSE columns to provide a fair comparison for the metric.

Therefore, before using the postResample() function, let’s convert both the predictions and the target to be the % change in price over the 24 hour period, rather than the change in price ($). This step is particularly tedious, but it is important. As with the rest of this tutorial, try to understand what we are doing and why even if you find the code overwhelming. All we are doing in this “Adjust Prices” section is we are adjusting all of the prices to be represented as percentage change between observations, which will allow us to draw a fair comparison of the metrics across all cryptocurrencies, which would not be possible using the prices themselves. If you want to skip the tedious steps and want to see the performance of the models visualized, click here to skip ahead. ### 8.2.1 Add Last Price In order to convert the first prediction made to be a percentage, we need to know the previous price, which would be the last observation from the train data. Therefore, let’s make a function to add the last_price_train column and append it to the predictions made so we can calculate the % change of the first element relative to the last observation in the train data, before later removing the value not associated with the predictions: last_train_price <- function(train_data, predictions){ c(tail(train_data$price_usd,1), predictions)
}

We will first perform all steps on the linear regression models to make the code a little more digestible, and we will then perform the same steps for the rest of the models.

#### 8.2.1.1 Test

Overwrite the old predictions for the first 4 splits of the test data using the new function created above:

cryptodata_nested <- mutate(cryptodata_nested,
lm_test_predictions = ifelse(split < 5,
map2(train_data, lm_test_predictions, last_train_price),
NA))

The mutate() function is used to create the new column lm_test_predictions assigning the value only for the first 4 splits where the test data would actually exist (the 5th being the holdout set) using the ifelse() function.

#### 8.2.1.2 Holdout

Do the same but for the holdout now. For the holdout we need to take the last price point of the 5th split:

cryptodata_nested_holdout <- mutate(filter(cryptodata_nested, split == 5),
lm_holdout_predictions = map2(train_data, lm_holdout_predictions, last_train_price))

Now join the holdout data to all rows based on the cryptocurrency symbol alone:

cryptodata_nested <- left_join(cryptodata_nested,
select(cryptodata_nested_holdout, symbol, lm_holdout_predictions),
by='symbol')
# Remove unwanted columns
cryptodata_nested <- select(cryptodata_nested, -lm_holdout_predictions.x, -split.y)
# Rename the columns kept
cryptodata_nested <- rename(cryptodata_nested,
lm_holdout_predictions = 'lm_holdout_predictions.y',
split = 'split.x')
# Reset the correct grouping structure
cryptodata_nested <- group_by(cryptodata_nested, symbol, split)

### 8.2.2 Convert to Percentage Change

Now we have everything we need to accurately calculate the percentage change between observations including the first one. Let’s make a new function to calculate the percentage change:

standardize_perc_change <- function(predictions){
results <- (diff(c(lag(predictions, 1), predictions)) / lag(predictions, 1))*100
# Exclude the first element, next element will be % change of first prediction
}

Overwrite the old predictions with the new predictions adjusted as a percentage now:

cryptodata_nested <- mutate(cryptodata_nested,
lm_test_predictions = ifelse(split < 5,
map(lm_test_predictions, standardize_perc_change),
NA),
# Holdout for all splits
lm_holdout_predictions = map(lm_holdout_predictions, standardize_perc_change))

### 8.2.3 Actuals

Now do the same thing to the actual prices. Let’s make a new column called actuals containing the real price values (rather than the predicted ones):

actuals_create <- function(train_data, test_data){

### 8.5.2 Holdout

Now repeat the same process for the holdout set:

rmse_holdout <- mutate(cryptodata_metrics,
lm = mean(lm_rmse_holdout, na.rm = T),
xgb = mean(xgb_rmse_holdout, na.rm = T),
nnet = mean(nnet_rmse_holdout, na.rm = T),
rf = mean(rf_rmse_holdout, na.rm = T),
pcr = mean(pcr_rmse_holdout, na.rm = T))

Again, use the gather() function to summarize the columns as rows:

rmse_holdout <- unique(gather(select(rmse_holdout, lm:pcr), 'model', 'rmse', -symbol))
# Show results
rmse_holdout
## # A tibble: 430 x 3
## # Groups:   symbol [86]
##    symbol model  rmse
##    <chr>  <chr> <dbl>
##  1 BTC    lm    0.180
##  2 ETH    lm    0.155
##  3 EOS    lm    0.277
##  4 LTC    lm    0.248
##  5 BSV    lm    0.341
##  7 ZEC    lm    0.496
##  8 HT     lm    0.228
##  9 TRX    lm    0.247
## 10 KNC    lm    0.412
## # ... with 420 more rows

Now tag the results as having been for the holdout set:

### 8.6.2 Holdout

Do the same and calculate the averages for the holdout sets:

rsq_holdout <- mutate(cryptodata_metrics,
lm = mean(lm_rsq_holdout, na.rm = T),
xgb = mean(xgb_rsq_holdout, na.rm = T),
nnet = mean(nnet_rsq_holdout, na.rm = T),
rf = mean(rf_rsq_holdout, na.rm = T),
pcr = mean(pcr_rsq_holdout, na.rm = T))

Now we can use the gather() function to summarize the columns as rows:

rsq_holdout <- unique(gather(select(rsq_holdout, lm:pcr), 'model', 'rsq', -symbol))
# Show results
rsq_holdout
## # A tibble: 430 x 3
## # Groups:   symbol [86]
##    symbol model     rsq
##    <chr>  <chr>   <dbl>
##  1 BTC    lm    0.749
##  2 ETH    lm    0.773
##  3 EOS    lm    0.602
##  4 LTC    lm    0.640
##  5 BSV    lm    0.728
##  7 ZEC    lm    0.404
##  8 HT     lm    0.00919
##  9 TRX    lm    0.316
## 10 KNC    lm    0.706
## # ... with 420 more rows

Now tag the results as having been for the holdout set:

rsq_holdout$eval_set <- 'holdout' ### 8.6.3 Union Results rsq_scores <- union(rsq_test, rsq_holdout) ## 8.7 Visualize Results Now we can take the same tools we learned in the Visualization section from earlier and visualize the results of the models. ### 8.7.1 RMSE Visualization ### 8.7.2 Both Now we have everything we need to use the two metrics to compare the results. #### 8.7.2.1 Join Datasets First join the two objects rmse_scores and rsq_scores into the new object **plot_scores: plot_scores <- merge(rmse_scores, rsq_scores) #### 8.7.2.2 Plot Results Now we can plot the results on a chart: ggplot(plot_scores, aes(x=rsq, y=rmse, color = model)) + geom_point() + ylim(c(0,10)) Running the same code wrapped in the ggplotly() function from the plotly package (as we have already done) we can make the chart interactive. Try hovering over the points on the chart with your mouse. ggplotly(ggplot(plot_scores, aes(x=rsq, y=rmse, color = model, symbol = symbol)) + geom_point() + ylim(c(0,10)), tooltip = c("model", "symbol", "rmse", "rsq")) The additional tooltip argument was passed to ggpltoly() to specify the label when hovering over the individual points. ### 8.7.3 Results by the Cryptocurrency We can use the facet_wrap() function from ggplot2 to create an individual chart for each cryptocurrency: ggplot(plot_scores, aes(x=rsq, y=rmse, color = model)) + geom_point() + geom_smooth() + ylim(c(0,10)) + facet_wrap(~symbol) Every 12 hours once this document reaches this point, the results are saved to GitHub using the pins package (which we used to read in the data at the start), and a separate script running on a different server creates the complete dataset in our database over time. You won’t be able to run the code shown below (nor do you have a reason to): # register board board_register("github", repo = "predictcrypto/pins", token=pins_key) # Add current date time plot_scores$last_refreshed <- Sys.time()
# pin data
pin(plot_scores, board='github', name='crypto_tutorial_results_latest')

## 8.8 Interactive Dashboard

Use the interactive app below to explore the results over time by the individual cryptocurrency. Use the filters on the left sidebar to visualize the results you are interested in:

If you have trouble viewing the embedded dashboard you can open it here instead: https://predictcrypto.shinyapps.io/tutorial_latest_model_summary/

The default view shows the holdout results for all models. Another interesting comparison to make is between the holdout and the test set for fewer models (2 is ideal).

The app shown above also has a button to Show Code. If you were to show the code and copy and paste it into an RStudio session on your computer into a file with the .Rmd file extension and you then Knit the file, the same exact app should show up on your computer, no logins or setup outside of the packages required for the code to run; RStudio should automatically prompt you to install packages that are not currently installed on your computer.

## 8.9 Visualizations - Historical Metrics

We can pull the same data into this R session using the pin_get() function:

metrics_historical <- pin_get(name = "full_metrics")

The data is limited to metrics for runs from the past 30 days and includes new data every 12 hours. Using the tools we used in the data prep section, we can answer a couple more questions.

### 8.9.1 Best Models

Overall, which model has the best metrics for all runs from the last 30 days?

#### 8.9.1.1 Summarize the data

# First create grouped data
best_models <- group_by(metrics_historical, model, eval_set)
# Now summarize the data
best_models <- summarize(best_models,
rmse = mean(rmse, na.rm=T),
rsq  = mean(rsq, na.rm=T))
# Show results
best_models
## # A tibble: 10 x 4
## # Groups:   model [5]
##    model eval_set  rmse    rsq
##    <chr> <chr>    <dbl>  <dbl>
##  1 lm    holdout  15.5  0.506
##  2 lm    test      4.07 0.478
##  3 nnet  holdout   4.31 0.149
##  4 nnet  test      4.63 0.164
##  5 pcr   holdout   2.72 0.252
##  6 pcr   test      2.92 0.278
##  7 rf    holdout   3.96 0.114
##  8 rf    test      3.83 0.129
##  9 xgb   holdout   5.01 0.0693
## 10 xgb   test      4.56 0.0885

#### 8.9.1.2 Plot RMSE by Model

ggplot(best_models, aes(model, rmse, fill = eval_set)) +
geom_bar(stat = "identity", position = 'dodge') +
ggtitle('RMSE by Model', 'Comparing Test and Holdout')

#### 8.9.1.3 Plot $$R^2$$ by Model

ggplot(best_models, aes(model, rsq, fill = eval_set)) +
geom_bar(stat = "identity", position = 'dodge') +
ggtitle('R^2 by Model', 'Comparing Test and Holdout')

### 8.9.2 Most Predictable Cryptocurrency

Overall, which cryptocurrency has the best metrics for all runs from the last 30 days?

#### 8.9.2.1 Summarize the data

# First create grouped data
predictable_cryptos <- group_by(metrics_historical, symbol, eval_set)
# Now summarize the data
predictable_cryptos <- summarize(predictable_cryptos,
rmse = mean(rmse, na.rm=T),
rsq  = mean(rsq, na.rm=T))
# Arrange from most predictable (according to R^2) to least
predictable_cryptos <- arrange(predictable_cryptos, desc(rsq))
# Show results
predictable_cryptos
## # A tibble: 178 x 4
## # Groups:   symbol [89]
##    symbol eval_set  rmse   rsq
##    <chr>  <chr>    <dbl> <dbl>
##  1 NAV    test      3.30 0.434
##  2 POA    holdout   4.60 0.423
##  3 CUR    holdout   6.09 0.410
##  4 CND    test      1.84 0.374
##  5 CND    holdout   5.24 0.360
##  6 SEELE  holdout   8.88 0.355
##  7 ADXN   test      9.26 0.348
##  8 RCN    test      5.03 0.337
##  9 BTC    test      1.32 0.331
## 10 SUN    holdout   3.17 0.330
## # ... with 168 more rows

Show the top 15 most predictable cryptocurrencies (according to the $$R^2$$) using the formattable package (Ren and Russell 2016) to color code the cells:

formattable(head(predictable_cryptos ,15),
list(rmse = color_tile("#71CA97", "red"),
rsq = color_tile("firebrick1", "#71CA97")))
symbol eval_set rmse rsq
NAV test 3.299791 0.4338237
POA holdout 4.596582 0.4229192
CUR holdout 6.088416 0.4098434
CND test 1.835020 0.3737691
CND holdout 5.238670 0.3601346
SEELE holdout 8.876745 0.3548372
RCN test 5.030197 0.3367737
BTC test 1.321379 0.3307333
SUN holdout 3.172350 0.3299285
AAB test 39.511003 0.3262746
ETH test 1.721290 0.3197170
LTC test 2.102832 0.3189001
LEO test 1.695632 0.3166553
RCN holdout 7.564985 0.3130917

### 8.9.3 Accuracy Over Time

#### 8.9.3.1 Summarize the data

# First create grouped data
accuracy_over_time <- group_by(metrics_historical, date_utc)
# Now summarize the data
accuracy_over_time <- summarize(accuracy_over_time,
rmse = mean(rmse, na.rm=T),
rsq  = mean(rsq, na.rm=T))
# Ungroup data
accuracy_over_time <- ungroup(accuracy_over_time)
# Convert date/time
accuracy_over_time$date_utc <- anytime(accuracy_over_time$date_utc)
# Show results
accuracy_over_time
## # A tibble: 30 x 3
##    date_utc             rmse   rsq
##    <dttm>              <dbl> <dbl>
##  1 2021-01-12 00:00:00  4.05 0.241
##  2 2021-01-13 00:00:00  4.29 0.236
##  3 2021-01-14 00:00:00  4.06 0.251
##  4 2021-01-16 00:00:00  4.25 0.214
##  5 2021-01-17 00:00:00  3.78 0.199
##  6 2021-01-18 00:00:00  3.88 0.212
##  7 2021-01-19 00:00:00  3.86 0.204
##  8 2021-01-20 00:00:00  4.65 0.207
##  9 2021-01-21 00:00:00  3.41 0.222
## 10 2021-01-22 00:00:00  4.05 0.231
## # ... with 20 more rows

#### 8.9.3.2 Plot RMSE

Remember, for RMSE the lower the score, the more accurate the models were.

ggplot(accuracy_over_time, aes(x = date_utc, y = rmse, group = 1)) +
# Plot RMSE over time
geom_point(color = 'red', size = 2) +
geom_line(color = 'red', size = 1)

#### 8.9.3.3 Plot R^2

For the R^2 recall that we are looking at the correlation between the predictions made and what actually happened, so the higher the score the better, with a maximum score of 1 that would mean the predictions were 100% correlated with each other and therefore identical.

ggplot(accuracy_over_time, aes(x = date_utc, y = rsq, group = 1)) +
# Plot R^2 over time
geom_point(aes(x = date_utc, y = rsq), color = 'dark green', size = 2) +
geom_line(aes(x = date_utc, y = rsq), color = 'dark green', size = 1)

Refer back to the interactive dashboard to take a more specific subset of results instead of the aggregate analysis shown above.

### References

Ren, Kun, and Kenton Russell. 2016. Formattable: Create Formattable Data Structures. https://CRAN.R-project.org/package=formattable.