- Introduction
- Installation and Startup

- Cover Type Dataset
- Multinomial Model
- Binomial Model
- Adding extra features

- Multinomial Model Revisited

## Introduction

this tutorial shows how a h2o model can be used to do binary and multi-class classification. this tutorial covers usage of h2o from r. a python version of this tutorial will be available as well in a separate document. this file is available in plain r, r markdown and regular markdown formats, and the plots are available as pdf files. all documents are available .

If run from plain R, execute R in the directory of this script. If run from RStudio, be sure to `setwd()`

to the location of this script. `h2o.init()`

宁夏微乐滑水麻将下载 starts H2O in R's current working directory. h2o.importFile() looks for files from the perspective of where H2O was started.

more examples and explanations can be found in our and on our .

### H2O R Package

load the h2o r package:

```
## R installation instructions are at http://sunuq.icu/download
library(h2o)
```

### Start H2O

宁夏微乐滑水麻将下载start up a 1-node h2o server on your local machine, and allow it to use all cpu cores and up to 2gb of memory:

```
h2o.init(nthreads=-1, max_mem_size="2G")
h2o.removeAll() ## clean slate - just in case the cluster was already running
```

## Cover Type Data

predicting forest cover type from cartographic variables only (no remotely sensed data). let's import the dataset:

```
D = h2o.importFile(path = normalizePath("../data/covtype.full.csv"))
h2o.summary(D)
```

we have 11 numeric and two categorical features. response is "cover_type" and has 7 classes. let's split the data into train/test/validation with train having 70% and test and validation 15% each:

```
data = h2o.splitFrame(D,ratios=c(.7,.15),destination_frames = c("train","test","valid"))
names(data)
```

## Multinomial Model

we imported our data, so let's run glm. as we mentioned previously, cover_type is the response and we use all other columns as predictors. we have multi-class problem so we pick family=multinomial. l-bfgs solver tends to be faster on multinomial problems, so we pick l-bfgs for our first try. the rest can use the default settings.

```
m1 = h2o.glm(training_frame = data$Train, validation_frame = data$Valid, x = x, y = y,family='multinomial',solver='L_BFGS')
h2o.confusionMatrix(m1, valid=TRUE)
```

the model predicts only the majority class so it's not useful at all! maybe we regularized it too much, let's try again without regularization:

```
m2 = h2o.glm(training_frame = data$Train, validation_frame = data$Valid, x = x, y = y,family='multinomial',solver='L_BFGS', lambda = 0)
h2o.confusionMatrix(m2, valid=FALSE) # get confusion matrix in the training data
h2o.confusionMatrix(m2, valid=TRUE) # get confusion matrix in the validation data
```

宁夏微乐滑水麻将下载no overfitting (as train and test performance are the same), regularization is not needed in this case.

宁夏微乐滑水麻将下载this model is actually useful. it got 28% classification error, down from 51% obtained by predicting majority class only.

## Binomial Model

Since multinomial models are difficult and time consuming, let's try a simpler binary classification.
We'll take a subset of the data with only `class_1`

and `class_2`

(the two majority classes) and build a binomial model deciding between them.

```
D_binomial = D[D$Cover_Type %in% c("class_1","class_2"),]
h2o.setLevels(D_binomial$Cover_Type,c("class_1","class_2"))
# split to train/test/validation again
data_binomial = h2o.splitFrame(D_binomial,ratios=c(.7,.15),destination_frames = c("train_b","test_b","valid_b"))
names(data_binomial)
```

we can run a binomial model now:

```
m_binomial = h2o.glm(training_frame = data_binomial$Train, validation_frame = data_binomial$Valid, x = x, y = y, family='binomial',lambda=0)
h2o.confusionMatrix(m_binomial, valid = TRUE)
h2o.confusionMatrix(m_binomial, valid = TRUE)
```

the output for a binomial problem is slightly different from multinomial. the confusion matrix now has a threshold attached to it.

The model produces probability of `class_1`

and `class_2`

similarly to multinomial example earlier. However, this time we only have two classes and we can tune the classification to our needs.

宁夏微乐滑水麻将下载the classification errors in binomial cases have a particular meaning: we call them false-positive and false negative. in reality, each can have a different cost associated with it, so we want to tune our classifier accordingly.

the common way to evaluate a binary classifier performance is to look at its . the roc curve plots the true positive rate versus false positive rate. we can plot it from the h2o model output:

```
fpr = m_binomial@model$training_metrics@metrics$thresholds_and_metric_scores$fpr
tpr = m_binomial@model$training_metrics@metrics$thresholds_and_metric_scores$tpr
fpr_val = m_binomial@model$validation_metrics@metrics$thresholds_and_metric_scores$fpr
tpr_val = m_binomial@model$validation_metrics@metrics$thresholds_and_metric_scores$tpr
plot(fpr,tpr, type='l')
title('AUC')
lines(fpr_val,tpr_val,type='l',col='red')
legend("bottomright",c("Train", "Validation"),col=c("black","red"),lty=c(1,1),lwd=c(3,3))
```

the area under the roc curve (auc) is a common "good fit" metric for binary classifiers. for this example, the results were:

```
h2o.auc(m_binomial,valid=FALSE) # on train
h2o.auc(m_binomial,valid=TRUE) # on test
```

宁夏微乐滑水麻将下载the default confusion matrix is computed at thresholds that optimize the . we can choose different thresholds - the h2o output shows optimal thresholds for some common metrics.

```
m_binomial@model$training_metrics@metrics$max_criteria_and_metric_scores
```

the model we just built gets 23% classification error at the f1-optimizing threshold, so there is still room for improvement. let's add some features:

- There are 11 numerical predictors in the dataset, we will cut them into intervals and add a categorical variable for each
- We can add interaction terms capturing interactions between categorical variables

Let's make a convenience function to cut the column into intervals working on all three of our datasets (Train/Validation/Test).
We'll use `h2o.hist`

to determine interval boundaries (but there are many more ways to do that!) on the Train set.

宁夏微乐滑水麻将下载We'll take only the bins with non-trivial support:

```
cut_column <- function(data,="" col)="" {="" #="" need="" lower="" upper="" bound="" due="" to="" h2o.cut="" behavior="" (points="" <="" the="" first="" break="" or=""> the last break are replaced with missing value)
min_val = min(data$Train[,col])-1
max_val = max(data$Train[,col])+1
x = h2o.hist(data$Train[, col])
# use only the breaks with enough support
breaks = x$breaks[which(x$counts > 1000)]
# assign level names
lvls = c("min",paste("i_",breaks[2:length(breaks)-1],sep=""),"max")
col_cut
```

Now let's make a convenience function generating interaction terms on all three of our datasets. We'll use `h2o.interaction`

:

`interactions `

finally, let's wrap addition of the features into a separate function call, as we will use it again later. we'll add intervals for each numeric column and interactions between each pair of binary columns.

```
# add features to our cover type example
# let's cut all the numerical columns into intervals and add interactions between categorical terms
add_features
```

now we generate new features and add them to the dataset. we'll also need to generate column names again, as we added more columns:

```
# Add Features
data_binomial_ext
```

let's build the model! we should add some regularization this time because we added correlated variables, so let's try the default:

```
m_binomial_1_ext = try(h2o.glm(training_frame = data_binomial_ext$Train, validation_frame = data_binomial_ext$Valid, x = x, y = y, family='binomial'))
```

oops, doesn't run - well, we know have more features than the default method can solve with 2gb of ram. let's try l-bfgs instead.

```
m_binomial_1_ext = h2o.glm(training_frame = data_binomial_ext$Train, validation_frame = data_binomial_ext$Valid, x = x, y = y, family='binomial', solver='L_BFGS')
h2o.confusionMatrix(m_binomial_1_ext)
h2o.auc(m_binomial_1_ext,valid=TRUE)
```

not much better, maybe too much regularization? let's pick a smaller lambda and try again.

```
m_binomial_2_ext = h2o.glm(training_frame = data_binomial_ext$Train, validation_frame = data_binomial_ext$Valid, x = x, y = y, family='binomial', solver='L_BFGS', lambda=1e-4)
h2o.confusionMatrix(m_binomial_2_ext, valid=TRUE)
h2o.auc(m_binomial_2_ext,valid=TRUE)
```

宁夏微乐滑水麻将下载way better, we got an auc of .91 and classification error of 0.180838. we picked our regularization strength arbitrarily. also, we used only the l2 penalty but we added lot of extra features, some of which may be useless. maybe we can do better with an l1 penalty. so now we want to run a lambda search to find optimal penalty strength and we want to have a non-zero l1 penalty to get sparse solution. we'll use the irlsm solver this time as it does much better with lambda search and l1 penalty. recall we were not able to use it before. we can use it now as we are running a lambda search that will filter out a large portion of the inactive (coefficient==0) predictors.

```
m_binomial_3_ext = h2o.glm(training_frame = data_binomial_ext$Train, validation_frame = data_binomial_ext$Valid, x = x, y = y, family='binomial', lambda_search=TRUE)
h2o.confusionMatrix(m_binomial_3_ext, valid=TRUE)
h2o.auc(m_binomial_3_ext,valid=TRUE)
```

宁夏微乐滑水麻将下载better yet, we have 17% error and we used only 3000 out of 7000 features. ok, our new features improved the binomial model significantly, so let's revisit our former multinomial model and see if they make a difference there (they should!):

```
# Multinomial Model 2
# let's revisit the multinomial case with our new features
data_ext
```

宁夏微乐滑水麻将下载improved considerably, 21% instead of 28%.