Introduction to SuperML

SuperML R package is designed to unify the model training process in R like Python. Generally, it’s seen that people spend lot of time in searching for packages, figuring out the syntax for training machine learning models in R. This behaviour is highly apparent in users who frequently switch between R and Python. This package provides a python´s scikit-learn interface (fit, predict) to train models faster.

In addition to building machine learning models, there are handy functionalities to do feature engineering

This ambitious package is my ongoing effort to help the r-community build ML models easily and faster in R.

Install

You can install latest cran version using (recommended):

install.packages("superml")

You can install the developmemt version directly from github using:

devtools::install_github("saraswatmks/superml")

Caveats on superml installation

For machine learning, superml is based on the existing R packages. Hence, while installing the package, we don’t install all the dependencies. However, while training any model, superml will automatically install the package if its not found. Still, if you want to install all dependencies at once, you can simply do:

install.packages("superml", dependencies=TRUE)

Examples - Machine Learning Models

This package uses existing r-packages to build machine learning model. In this tutorial, we’ll use data.table R package to do all tasks related to data manipulation.

Regression Data

We’ll quickly prepare the data set to be ready to served for model training.

load("../data/reg_train.rda")
# if the above doesn't work, you can try: load("reg_train.rda")
# superml::check_package("caret")
library(data.table)
library(caret)
#> Loading required package: ggplot2
#> Loading required package: lattice
library(superml)

library(Metrics)
#> 
#> Attaching package: 'Metrics'
#> The following objects are masked from 'package:caret':
#> 
#>     precision, recall

head(reg_train)
#>       Id MSSubClass MSZoning LotFrontage LotArea Street  Alley LotShape
#>    <int>      <int>   <char>       <int>   <int> <char> <char>   <char>
#> 1:     1         60       RL          65    8450   Pave   <NA>      Reg
#> 2:     2         20       RL          80    9600   Pave   <NA>      Reg
#> 3:     3         60       RL          68   11250   Pave   <NA>      IR1
#> 4:     4         70       RL          60    9550   Pave   <NA>      IR1
#> 5:     5         60       RL          84   14260   Pave   <NA>      IR1
#> 6:     6         50       RL          85   14115   Pave   <NA>      IR1
#>    LandContour Utilities LotConfig LandSlope Neighborhood Condition1 Condition2
#>         <char>    <char>    <char>    <char>       <char>     <char>     <char>
#> 1:         Lvl    AllPub    Inside       Gtl      CollgCr       Norm       Norm
#> 2:         Lvl    AllPub       FR2       Gtl      Veenker      Feedr       Norm
#> 3:         Lvl    AllPub    Inside       Gtl      CollgCr       Norm       Norm
#> 4:         Lvl    AllPub    Corner       Gtl      Crawfor       Norm       Norm
#> 5:         Lvl    AllPub       FR2       Gtl      NoRidge       Norm       Norm
#> 6:         Lvl    AllPub    Inside       Gtl      Mitchel       Norm       Norm
#>    BldgType HouseStyle OverallQual OverallCond YearBuilt YearRemodAdd RoofStyle
#>      <char>     <char>       <int>       <int>     <int>        <int>    <char>
#> 1:     1Fam     2Story           7           5      2003         2003     Gable
#> 2:     1Fam     1Story           6           8      1976         1976     Gable
#> 3:     1Fam     2Story           7           5      2001         2002     Gable
#> 4:     1Fam     2Story           7           5      1915         1970     Gable
#> 5:     1Fam     2Story           8           5      2000         2000     Gable
#> 6:     1Fam     1.5Fin           5           5      1993         1995     Gable
#>    RoofMatl Exterior1st Exterior2nd MasVnrType MasVnrArea ExterQual ExterCond
#>      <char>      <char>      <char>     <char>      <int>    <char>    <char>
#> 1:  CompShg     VinylSd     VinylSd    BrkFace        196        Gd        TA
#> 2:  CompShg     MetalSd     MetalSd       None          0        TA        TA
#> 3:  CompShg     VinylSd     VinylSd    BrkFace        162        Gd        TA
#> 4:  CompShg     Wd Sdng     Wd Shng       None          0        TA        TA
#> 5:  CompShg     VinylSd     VinylSd    BrkFace        350        Gd        TA
#> 6:  CompShg     VinylSd     VinylSd       None          0        TA        TA
#>    Foundation BsmtQual BsmtCond BsmtExposure BsmtFinType1 BsmtFinSF1
#>        <char>   <char>   <char>       <char>       <char>      <int>
#> 1:      PConc       Gd       TA           No          GLQ        706
#> 2:     CBlock       Gd       TA           Gd          ALQ        978
#> 3:      PConc       Gd       TA           Mn          GLQ        486
#> 4:     BrkTil       TA       Gd           No          ALQ        216
#> 5:      PConc       Gd       TA           Av          GLQ        655
#> 6:       Wood       Gd       TA           No          GLQ        732
#>    BsmtFinType2 BsmtFinSF2 BsmtUnfSF TotalBsmtSF Heating HeatingQC CentralAir
#>          <char>      <int>     <int>       <int>  <char>    <char>     <char>
#> 1:          Unf          0       150         856    GasA        Ex          Y
#> 2:          Unf          0       284        1262    GasA        Ex          Y
#> 3:          Unf          0       434         920    GasA        Ex          Y
#> 4:          Unf          0       540         756    GasA        Gd          Y
#> 5:          Unf          0       490        1145    GasA        Ex          Y
#> 6:          Unf          0        64         796    GasA        Ex          Y
#>    Electrical 1stFlrSF 2ndFlrSF LowQualFinSF GrLivArea BsmtFullBath
#>        <char>    <int>    <int>        <int>     <int>        <int>
#> 1:      SBrkr      856      854            0      1710            1
#> 2:      SBrkr     1262        0            0      1262            0
#> 3:      SBrkr      920      866            0      1786            1
#> 4:      SBrkr      961      756            0      1717            1
#> 5:      SBrkr     1145     1053            0      2198            1
#> 6:      SBrkr      796      566            0      1362            1
#>    BsmtHalfBath FullBath HalfBath BedroomAbvGr KitchenAbvGr KitchenQual
#>           <int>    <int>    <int>        <int>        <int>      <char>
#> 1:            0        2        1            3            1          Gd
#> 2:            1        2        0            3            1          TA
#> 3:            0        2        1            3            1          Gd
#> 4:            0        1        0            3            1          Gd
#> 5:            0        2        1            4            1          Gd
#> 6:            0        1        1            1            1          TA
#>    TotRmsAbvGrd Functional Fireplaces FireplaceQu GarageType GarageYrBlt
#>           <int>     <char>      <int>      <char>     <char>       <int>
#> 1:            8        Typ          0        <NA>     Attchd        2003
#> 2:            6        Typ          1          TA     Attchd        1976
#> 3:            6        Typ          1          TA     Attchd        2001
#> 4:            7        Typ          1          Gd     Detchd        1998
#> 5:            9        Typ          1          TA     Attchd        2000
#> 6:            5        Typ          0        <NA>     Attchd        1993
#>    GarageFinish GarageCars GarageArea GarageQual GarageCond PavedDrive
#>          <char>      <int>      <int>     <char>     <char>     <char>
#> 1:          RFn          2        548         TA         TA          Y
#> 2:          RFn          2        460         TA         TA          Y
#> 3:          RFn          2        608         TA         TA          Y
#> 4:          Unf          3        642         TA         TA          Y
#> 5:          RFn          3        836         TA         TA          Y
#> 6:          Unf          2        480         TA         TA          Y
#>    WoodDeckSF OpenPorchSF EnclosedPorch 3SsnPorch ScreenPorch PoolArea PoolQC
#>         <int>       <int>         <int>     <int>       <int>    <int> <char>
#> 1:          0          61             0         0           0        0   <NA>
#> 2:        298           0             0         0           0        0   <NA>
#> 3:          0          42             0         0           0        0   <NA>
#> 4:          0          35           272         0           0        0   <NA>
#> 5:        192          84             0         0           0        0   <NA>
#> 6:         40          30             0       320           0        0   <NA>
#>     Fence MiscFeature MiscVal MoSold YrSold SaleType SaleCondition SalePrice
#>    <char>      <char>   <int>  <int>  <int>   <char>        <char>     <int>
#> 1:   <NA>        <NA>       0      2   2008       WD        Normal    208500
#> 2:   <NA>        <NA>       0      5   2007       WD        Normal    181500
#> 3:   <NA>        <NA>       0      9   2008       WD        Normal    223500
#> 4:   <NA>        <NA>       0      2   2006       WD       Abnorml    140000
#> 5:   <NA>        <NA>       0     12   2008       WD        Normal    250000
#> 6:  MnPrv        Shed     700     10   2009       WD        Normal    143000

split <- createDataPartition(y = reg_train$SalePrice, p = 0.7)
xtrain <- reg_train[split$Resample1]
xtest <- reg_train[!split$Resample1]
# remove features with 90% or more missing values
# we will also remove the Id column because it doesn't contain
# any useful information
na_cols <- colSums(is.na(xtrain)) / nrow(xtrain)
na_cols <- names(na_cols[which(na_cols > 0.9)])

xtrain[, c(na_cols, "Id") := NULL]
xtest[, c(na_cols, "Id") := NULL]

# encode categorical variables
cat_cols <- names(xtrain)[sapply(xtrain, is.character)]

for(c in cat_cols){
    lbl <- LabelEncoder$new()
    lbl$fit(c(xtrain[[c]], xtest[[c]]))
    xtrain[[c]] <- lbl$transform(xtrain[[c]])
    xtest[[c]] <- lbl$transform(xtest[[c]])
}
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA' 
#> The data contains NA values. Imputing NA with 'NA'

# removing noise column
noise <- c('GrLivArea','TotalBsmtSF')

xtrain[, c(noise) := NULL]
xtest[, c(noise) := NULL]

# fill missing value with  -1
xtrain[is.na(xtrain)] <- -1
xtest[is.na(xtest)] <- -1

KNN Regression

knn <- KNNTrainer$new(k = 2,prob = T,type = 'reg')
knn$fit(train = xtrain, test = xtest, y = 'SalePrice')
probs <- knn$predict(type = 'prob')
labels <- knn$predict(type='raw')
rmse(actual = xtest$SalePrice, predicted=labels)
#> [1] 46861.85

SVM Regression

svm <- SVMTrainer$new()
svm$fit(xtrain, 'SalePrice')
pred <- svm$predict(xtest)
rmse(actual = xtest$SalePrice, predicted = pred)

Simple Regresison

lf <- LMTrainer$new(family="gaussian")
lf$fit(X = xtrain, y = "SalePrice")
summary(lf$model)
#> 
#> Call:
#> stats::glm(formula = f, family = self$family, data = X, weights = self$weights)
#> 
#> Coefficients: (1 not defined because of singularities)
#>                 Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)   -9.803e+05  1.331e+06  -0.737 0.461603    
#> MSSubClass    -1.162e+02  4.481e+01  -2.594 0.009638 ** 
#> MSZoning      -7.596e+02  1.237e+03  -0.614 0.539376    
#> LotFrontage    7.689e+01  2.755e+01   2.790 0.005369 ** 
#> LotArea        5.475e-01  1.085e-01   5.047 5.38e-07 ***
#> Street        -5.022e+04  1.433e+04  -3.506 0.000477 ***
#> LotShape      -1.546e+03  1.656e+03  -0.933 0.351002    
#> LandContour    8.270e+02  1.790e+03   0.462 0.644146    
#> Utilities             NA         NA      NA       NA    
#> LotConfig      3.058e+02  1.020e+03   0.300 0.764467    
#> LandSlope     -3.559e+03  4.461e+03  -0.798 0.425149    
#> Neighborhood  -2.853e+02  1.729e+02  -1.650 0.099225 .  
#> Condition1    -2.418e+03  6.602e+02  -3.662 0.000264 ***
#> Condition2    -1.689e+03  2.679e+03  -0.630 0.528576    
#> BldgType      -4.932e+02  1.735e+03  -0.284 0.776221    
#> HouseStyle    -2.151e+02  8.004e+02  -0.269 0.788214    
#> OverallQual    9.515e+03  1.191e+03   7.987 3.97e-15 ***
#> OverallCond    7.189e+03  1.057e+03   6.802 1.83e-11 ***
#> YearBuilt      3.760e+02  7.050e+01   5.334 1.20e-07 ***
#> YearRemodAdd   2.135e+02  6.546e+01   3.261 0.001149 ** 
#> RoofStyle      1.407e+03  1.731e+03   0.812 0.416742    
#> RoofMatl      -1.901e+03  1.880e+03  -1.011 0.312338    
#> Exterior1st   -6.420e+02  4.562e+02  -1.407 0.159636    
#> Exterior2nd    5.089e+02  4.973e+02   1.023 0.306441    
#> MasVnrType    -3.328e+03  1.439e+03  -2.313 0.020940 *  
#> MasVnrArea     3.145e+01  6.345e+00   4.957 8.49e-07 ***
#> ExterQual      1.012e+04  2.000e+03   5.062 4.97e-07 ***
#> ExterCond     -1.199e+03  1.971e+03  -0.608 0.543012    
#> Foundation    -1.608e+03  9.433e+02  -1.704 0.088646 .  
#> BsmtQual       2.772e+03  1.253e+03   2.212 0.027187 *  
#> BsmtCond      -5.408e+02  2.127e+03  -0.254 0.799413    
#> BsmtExposure   5.993e+03  8.397e+02   7.137 1.89e-12 ***
#> BsmtFinType1  -1.608e+02  5.700e+02  -0.282 0.777950    
#> BsmtFinSF1     4.891e+01  4.896e+00   9.988  < 2e-16 ***
#> BsmtFinType2  -2.123e+02  8.811e+02  -0.241 0.809663    
#> BsmtFinSF2     3.328e+01  8.103e+00   4.107 4.35e-05 ***
#> BsmtUnfSF      2.726e+01  4.541e+00   6.004 2.74e-09 ***
#> Heating       -4.176e+03  2.951e+03  -1.415 0.157345    
#> HeatingQC     -7.145e+02  1.276e+03  -0.560 0.575542    
#> CentralAir     3.896e+03  4.590e+03   0.849 0.396194    
#> Electrical     2.125e+03  1.852e+03   1.148 0.251357    
#> `1stFlrSF`     6.030e+01  5.896e+00  10.226  < 2e-16 ***
#> `2ndFlrSF`     7.234e+01  5.232e+00  13.827  < 2e-16 ***
#> LowQualFinSF   2.232e+01  1.827e+01   1.222 0.222123    
#> BsmtFullBath   1.890e+03  2.511e+03   0.753 0.451827    
#> BsmtHalfBath  -4.010e+03  3.905e+03  -1.027 0.304781    
#> FullBath       3.612e+02  2.704e+03   0.134 0.893777    
#> HalfBath      -1.713e+03  2.535e+03  -0.676 0.499402    
#> BedroomAbvGr  -1.039e+04  1.702e+03  -6.106 1.49e-09 ***
#> KitchenAbvGr  -2.465e+04  5.175e+03  -4.762 2.21e-06 ***
#> KitchenQual    1.173e+04  1.383e+03   8.485  < 2e-16 ***
#> TotRmsAbvGrd   2.919e+03  1.198e+03   2.437 0.014991 *  
#> Functional    -4.968e+03  1.301e+03  -3.818 0.000143 ***
#> Fireplaces     2.859e+03  1.840e+03   1.554 0.120592    
#> FireplaceQu    3.904e+00  9.929e+02   0.004 0.996863    
#> GarageType    -7.973e+02  1.152e+03  -0.692 0.488991    
#> GarageYrBlt   -2.514e+00  5.069e+00  -0.496 0.620042    
#> GarageFinish  -1.025e+03  1.478e+03  -0.694 0.488020    
#> GarageCars     5.084e+03  2.935e+03   1.732 0.083544 .  
#> GarageArea     1.449e+01  9.405e+00   1.541 0.123650    
#> GarageQual     7.368e+03  2.931e+03   2.514 0.012112 *  
#> GarageCond    -4.444e+03  2.569e+03  -1.730 0.083970 .  
#> PavedDrive    -1.943e+03  2.708e+03  -0.717 0.473314    
#> WoodDeckSF     1.210e+01  7.513e+00   1.611 0.107553    
#> OpenPorchSF    1.572e+01  1.416e+01   1.110 0.267341    
#> EnclosedPorch -6.549e+00  1.530e+01  -0.428 0.668665    
#> `3SsnPorch`    1.480e+01  3.150e+01   0.470 0.638645    
#> ScreenPorch    4.097e+01  1.558e+01   2.629 0.008700 ** 
#> PoolArea       8.162e+01  2.230e+01   3.659 0.000267 ***
#> Fence         -1.981e+03  1.202e+03  -1.648 0.099735 .  
#> MiscVal       -9.256e+00  4.827e+00  -1.917 0.055474 .  
#> MoSold        -2.638e+02  3.185e+02  -0.828 0.407654    
#> YrSold        -1.153e+02  6.597e+02  -0.175 0.861285    
#> SaleType       1.397e+03  1.008e+03   1.387 0.165866    
#> SaleCondition  6.168e+03  1.561e+03   3.953 8.31e-05 ***
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for gaussian family taken to be 700265710)
#> 
#>     Null deviance: 7.1596e+12  on 1023  degrees of freedom
#> Residual deviance: 6.6525e+11  on  950  degrees of freedom
#> AIC: 23835
#> 
#> Number of Fisher Scoring iterations: 2
predictions <- lf$predict(df = xtest)
#> Warning in predict.lm(object, newdata, se.fit, scale = 1, type = if (type == :
#> prediction from rank-deficient fit; attr(*, "non-estim") has doubtful cases
rmse(actual = xtest$SalePrice, predicted = predictions)
#> [1] 50727.11

Lasso Regression

lf <- LMTrainer$new(family = "gaussian", alpha = 1, lambda = 1000)
lf$fit(X = xtrain, y = "SalePrice")
predictions <- lf$predict(df = xtest)
rmse(actual = xtest$SalePrice, predicted = predictions)
#> [1] 55306.37

Ridge Regression

lf <- LMTrainer$new(family = "gaussian", alpha=0)
lf$fit(X = xtrain, y = "SalePrice")
predictions <- lf$predict(df = xtest)
rmse(actual = xtest$SalePrice, predicted = predictions)
#> [1] 56136.12

Logistic Regression with CV

lf <- LMTrainer$new(family = "gaussian")
lf$cv_model(X = xtrain, y = 'SalePrice', nfolds = 5, parallel = FALSE)
predictions <- lf$cv_predict(df = xtest)
coefs <- lf$get_importance()
rmse(actual = xtest$SalePrice, predicted = predictions)

Random Forest

rf <- RFTrainer$new(n_estimators = 500,classification = 0)
rf$fit(X = xtrain, y = "SalePrice")
pred <- rf$predict(df = xtest)
rf$get_importance()
#>               tmp.order.tmp..decreasing...TRUE..
#> OverallQual                         908484694653
#> GarageCars                          547567392469
#> 1stFlrSF                            489764442491
#> GarageArea                          481000546170
#> ExterQual                           477104170705
#> YearBuilt                           371038709543
#> BsmtFinSF1                          340597056492
#> FullBath                            303287368592
#> GarageYrBlt                         292617742191
#> 2ndFlrSF                            272923836090
#> TotRmsAbvGrd                        240077565621
#> LotArea                             219518965182
#> YearRemodAdd                        179045361183
#> Fireplaces                          155786517652
#> KitchenQual                         154406026146
#> MasVnrArea                          146892841302
#> BsmtQual                            143508692645
#> FireplaceQu                         114763286444
#> LotFrontage                          97128728545
#> OpenPorchSF                          93859417090
#> Neighborhood                         77888636697
#> BsmtUnfSF                            69192856824
#> WoodDeckSF                           62987211669
#> GarageFinish                         57216739851
#> BsmtExposure                         53099539167
#> BedroomAbvGr                         48828540451
#> GarageType                           44795887238
#> MoSold                               40294262110
#> RoofStyle                            36695887964
#> Exterior2nd                          34853516867
#> MSSubClass                           34088166842
#> OverallCond                          33461789883
#> HouseStyle                           31054279131
#> MasVnrType                           30258946528
#> HeatingQC                            28825259357
#> Exterior1st                          28402667316
#> HalfBath                             26550565923
#> BsmtFinType1                         24900660996
#> Foundation                           23531134076
#> SaleCondition                        22564742496
#> BsmtFullBath                         21570893359
#> YrSold                               21123778917
#> ScreenPorch                          18670240606
#> GarageCond                           18360764024
#> MSZoning                             17940361365
#> LotShape                             17201485087
#> LandContour                          15954040699
#> GarageQual                           15292927043
#> LandSlope                            14626568360
#> LotConfig                            14125623673
#> EnclosedPorch                        13274858663
#> BsmtCond                             12741238364
#> CentralAir                           12490111225
#> PoolArea                             12196562239
#> RoofMatl                             11277404072
#> Fence                                11236546727
#> BsmtHalfBath                         11012044716
#> BldgType                             10895089687
#> BsmtFinSF2                            9580171052
#> SaleType                              9573230882
#> ExterCond                             9401498637
#> PavedDrive                            7409085898
#> BsmtFinType2                          6854882176
#> Functional                            6667538404
#> Condition1                            6167731532
#> KitchenAbvGr                          5050205847
#> LowQualFinSF                          4492805884
#> Electrical                            2868657385
#> Heating                               2214232162
#> MiscVal                               2043128944
#> 3SsnPorch                             1511071145
#> Street                                 819143544
#> Condition2                             630608694
#> Utilities                                      0
rmse(actual = xtest$SalePrice, predicted = pred)
#> [1] 31809.2

Xgboost

xgb <- XGBTrainer$new(objective = "reg:linear"
                      , n_estimators = 500
                      , eval_metric = "rmse"
                      , maximize = F
                      , learning_rate = 0.1
                      ,max_depth = 6)
xgb$fit(X = xtrain, y = "SalePrice", valid = xtest)
pred <- xgb$predict(xtest)
rmse(actual = xtest$SalePrice, predicted = pred)

Grid Search

xgb <- XGBTrainer$new(objective = "reg:linear")

gst <- GridSearchCV$new(trainer = xgb,
                             parameters = list(n_estimators = c(10,50), max_depth = c(5,2)),
                             n_folds = 3,
                             scoring = c('accuracy','auc'))
gst$fit(xtrain, "SalePrice")
gst$best_iteration()

Random Search

rf <- RFTrainer$new()
rst <- RandomSearchCV$new(trainer = rf,
                             parameters = list(n_estimators = c(5,10),
                             max_depth = c(5,2)),
                             n_folds = 3,
                             scoring = c('accuracy','auc'),
                             n_iter = 3)
rst$fit(xtrain, "SalePrice")
#> [1] "In total, 3 models will be trained"
rst$best_iteration()
#> $n_estimators
#> [1] 10
#> 
#> $max_depth
#> [1] 2
#> 
#> $accuracy_avg
#> [1] 0.007805912
#> 
#> $accuracy_sd
#> [1] 0.004469349
#> 
#> $auc_avg
#> [1] NaN
#> 
#> $auc_sd
#> [1] NA

Binary Classification Data

Here, we will solve a simple binary classification problem (predict people who survived on titanic ship). The idea here is to demonstrate how to use this package to solve classification problems.

Data Preparation

# load class
load('../data/cla_train.rda')
# if the above doesn't work, you can try: load("cla_train.rda")

head(cla_train)
#>    PassengerId Survived Pclass
#>          <int>    <int>  <int>
#> 1:           1        0      3
#> 2:           2        1      1
#> 3:           3        1      3
#> 4:           4        1      1
#> 5:           5        0      3
#> 6:           6        0      3
#>                                                   Name    Sex   Age SibSp Parch
#>                                                 <char> <char> <num> <int> <int>
#> 1:                             Braund, Mr. Owen Harris   male    22     1     0
#> 2: Cumings, Mrs. John Bradley (Florence Briggs Thayer) female    38     1     0
#> 3:                              Heikkinen, Miss. Laina female    26     0     0
#> 4:        Futrelle, Mrs. Jacques Heath (Lily May Peel) female    35     1     0
#> 5:                            Allen, Mr. William Henry   male    35     0     0
#> 6:                                    Moran, Mr. James   male    NA     0     0
#>              Ticket    Fare  Cabin Embarked
#>              <char>   <num> <char>   <char>
#> 1:        A/5 21171  7.2500               S
#> 2:         PC 17599 71.2833    C85        C
#> 3: STON/O2. 3101282  7.9250               S
#> 4:           113803 53.1000   C123        S
#> 5:           373450  8.0500               S
#> 6:           330877  8.4583               Q

# split the data
split <- createDataPartition(y = cla_train$Survived,p = 0.7)
xtrain <- cla_train[split$Resample1]
xtest <- cla_train[!split$Resample1]

# encode categorical variables - shorter way
for(c in c('Embarked','Sex','Cabin')) {
    lbl <- LabelEncoder$new()
    lbl$fit(c(xtrain[[c]], xtest[[c]]))
    xtrain[[c]] <- lbl$transform(xtrain[[c]])
    xtest[[c]] <- lbl$transform(xtest[[c]])
}
#> The data contains blank values. Imputing them with 'NA' 
#> The data contains blank values. Imputing them with 'NA' 
#> The data contains blank values. Imputing them with 'NA' 
#> The data contains blank values. Imputing them with 'NA' 
#> The data contains blank values. Imputing them with 'NA'

# impute missing values
xtrain[, Age := replace(Age, is.na(Age), median(Age, na.rm = T))]
xtest[, Age := replace(Age, is.na(Age), median(Age, na.rm = T))]

# drop these features
to_drop <- c('PassengerId','Ticket','Name')

xtrain <- xtrain[,-c(to_drop), with=F]
xtest <- xtest[,-c(to_drop), with=F]

Now, our data is ready to be served for model training. Let’s do it.

KNN Classification

knn <- KNNTrainer$new(k = 2,prob = T,type = 'class')
knn$fit(train = xtrain, test = xtest, y = 'Survived')
probs <- knn$predict(type = 'prob')
labels <- knn$predict(type = 'raw')
auc(actual = xtest$Survived, predicted = labels)
#> [1] 0.6385027

Naive Bayes Classification

nb <- NBTrainer$new()
nb$fit(xtrain, 'Survived')
pred <- nb$predict(xtest)
#> Warning: predict.naive_bayes(): more features in the newdata are provided as
#> there are probability tables in the object. Calculation is performed based on
#> features to be found in the tables.
auc(actual = xtest$Survived, predicted = pred)
#> [1] 0.7771836

SVM Classification

#predicts labels
svm <- SVMTrainer$new()
svm$fit(xtrain, 'Survived')
pred <- svm$predict(xtest)
auc(actual = xtest$Survived, predicted=pred)

Logistic Regression

lf <- LMTrainer$new(family = "binomial")
lf$fit(X = xtrain, y = "Survived")
summary(lf$model)
#> 
#> Call:
#> stats::glm(formula = f, family = self$family, data = X, weights = self$weights)
#> 
#> Coefficients:
#>              Estimate Std. Error z value Pr(>|z|)    
#> (Intercept)  1.830070   0.616894   2.967  0.00301 ** 
#> Pclass      -0.980785   0.192493  -5.095 3.48e-07 ***
#> Sex          2.508241   0.230374  10.888  < 2e-16 ***
#> Age         -0.041034   0.009309  -4.408 1.04e-05 ***
#> SibSp       -0.235520   0.117715  -2.001  0.04542 *  
#> Parch       -0.098742   0.137791  -0.717  0.47361    
#> Fare         0.001281   0.002842   0.451  0.65230    
#> Cabin        0.008408   0.004786   1.757  0.07899 .  
#> Embarked     0.248088   0.166616   1.489  0.13649    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for binomial family taken to be 1)
#> 
#>     Null deviance: 831.52  on 623  degrees of freedom
#> Residual deviance: 564.76  on 615  degrees of freedom
#> AIC: 582.76
#> 
#> Number of Fisher Scoring iterations: 5
predictions <- lf$predict(df = xtest)
auc(actual = xtest$Survived, predicted = predictions)
#> [1] 0.8832145

Lasso Logistic Regression

lf <- LMTrainer$new(family="binomial", alpha=1)
lf$cv_model(X = xtrain, y = "Survived", nfolds = 5, parallel = FALSE)
pred <- lf$cv_predict(df = xtest)
auc(actual = xtest$Survived, predicted = pred)

Ridge Logistic Regression

lf <- LMTrainer$new(family="binomial", alpha=0)
lf$cv_model(X = xtrain, y = "Survived", nfolds = 5, parallel = FALSE)
pred <- lf$cv_predict(df = xtest)
auc(actual = xtest$Survived, predicted = pred)

Random Forest

rf <- RFTrainer$new(n_estimators = 500,classification = 1, max_features = 3)
rf$fit(X = xtrain, y = "Survived")

pred <- rf$predict(df = xtest)
rf$get_importance()
#>          tmp.order.tmp..decreasing...TRUE..
#> Sex                                69.10742
#> Fare                               57.96084
#> Age                                48.50156
#> Pclass                             23.91175
#> Cabin                              21.19329
#> SibSp                              12.58503
#> Parch                              10.55128
#> Embarked                           10.07059

auc(actual = xtest$Survived, predicted = pred)
#> [1] 0.7988414

Xgboost

xgb <- XGBTrainer$new(objective = "binary:logistic"
                      , n_estimators = 500
                      , eval_metric = "auc"
                      , maximize = T
                      , learning_rate = 0.1
                      ,max_depth = 6)
xgb$fit(X = xtrain, y = "Survived", valid = xtest)

pred <- xgb$predict(xtest)
auc(actual = xtest$Survived, predicted = pred)

Grid Search

xgb <- XGBTrainer$new(objective="binary:logistic")
gst <-GridSearchCV$new(trainer = xgb,
                             parameters = list(n_estimators = c(10,50),
                             max_depth = c(5,2)),
                             n_folds = 3,
                             scoring = c('accuracy','auc'))
gst$fit(xtrain, "Survived")
gst$best_iteration()

Random Search

rf <- RFTrainer$new()
rst <- RandomSearchCV$new(trainer = rf,
                             parameters = list(n_estimators = c(10,50), max_depth = c(5,2)),
                             n_folds = 3,
                             scoring = c('accuracy','auc'),
                             n_iter = 3)
rst$fit(xtrain, "Survived")
#> [1] "In total, 3 models will be trained"
rst$best_iteration()
#> $n_estimators
#> [1] 50
#> 
#> $max_depth
#> [1] 5
#> 
#> $accuracy_avg
#> [1] 0.8028846
#> 
#> $accuracy_sd
#> [1] 0.01733438
#> 
#> $auc_avg
#> [1] 0.7804264
#> 
#> $auc_sd
#> [1] 0.02631447

Let’s create some new feature based on target variable using target encoding and test a model.

# add target encoding features
xtrain[, feat_01 := smoothMean(train_df = xtrain,
                        test_df = xtest,
                        colname = "Embarked",
                        target = "Survived")$train[[2]]]
xtest[, feat_01 := smoothMean(train_df = xtrain,
                               test_df = xtest,
                               colname = "Embarked",
                               target = "Survived")$test[[2]]]

# train a random forest
# Random Forest
rf <- RFTrainer$new(n_estimators = 500,classification = 1, max_features = 4)
rf$fit(X = xtrain, y = "Survived")
pred <- rf$predict(df = xtest)
rf$get_importance()
#>          tmp.order.tmp..decreasing...TRUE..
#> Sex                               71.417138
#> Fare                              61.039958
#> Age                               51.787990
#> Pclass                            24.257112
#> Cabin                             21.549374
#> SibSp                             12.374317
#> Parch                             10.392826
#> feat_01                            6.490151
#> Embarked                           6.270997

auc(actual = xtest$Survived, predicted = pred)
#> [1] 0.7988414