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] 57262.01

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:
#>                 Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)   -8.042e+05  1.502e+06  -0.536 0.592371    
#> MSSubClass    -1.234e+02  4.450e+01  -2.774 0.005652 ** 
#> MSZoning      -6.683e+02  1.371e+03  -0.487 0.626104    
#> LotFrontage   -6.302e+01  3.147e+01  -2.002 0.045536 *  
#> LotArea        4.919e-01  1.229e-01   4.003 6.74e-05 ***
#> Street        -3.809e+04  1.655e+04  -2.302 0.021575 *  
#> LotShape      -4.947e+02  1.996e+03  -0.248 0.804334    
#> LandContour    2.999e+03  1.854e+03   1.617 0.106153    
#> Utilities     -5.601e+04  3.202e+04  -1.749 0.080545 .  
#> LotConfig      3.303e+02  9.997e+02   0.330 0.741143    
#> LandSlope      4.846e+03  4.515e+03   1.073 0.283416    
#> Neighborhood  -5.048e+02  1.878e+02  -2.688 0.007309 ** 
#> Condition1    -1.619e+03  6.993e+02  -2.315 0.020824 *  
#> Condition2     1.612e+03  4.738e+03   0.340 0.733705    
#> BldgType      -9.534e+02  1.874e+03  -0.509 0.611091    
#> HouseStyle     7.493e+02  8.499e+02   0.882 0.378244    
#> OverallQual    1.368e+04  1.322e+03  10.345  < 2e-16 ***
#> OverallCond    6.886e+03  1.130e+03   6.094 1.60e-09 ***
#> YearBuilt      5.525e+02  7.753e+01   7.127 2.03e-12 ***
#> YearRemodAdd  -9.782e+00  7.628e+01  -0.128 0.897996    
#> RoofStyle      1.012e+04  1.919e+03   5.277 1.63e-07 ***
#> RoofMatl      -2.500e+04  2.907e+03  -8.599  < 2e-16 ***
#> Exterior1st   -1.247e+03  6.461e+02  -1.930 0.053884 .  
#> Exterior2nd    1.868e+03  6.046e+02   3.090 0.002061 ** 
#> MasVnrType     3.319e+03  1.567e+03   2.118 0.034450 *  
#> MasVnrArea     6.638e+00  6.755e+00   0.983 0.325992    
#> ExterQual     -1.102e+03  2.344e+03  -0.470 0.638220    
#> ExterCond     -4.842e+02  2.381e+03  -0.203 0.838925    
#> Foundation    -2.390e+03  1.851e+03  -1.292 0.196770    
#> BsmtQual       5.346e+03  1.493e+03   3.582 0.000358 ***
#> BsmtCond      -3.113e+02  1.780e+03  -0.175 0.861173    
#> BsmtExposure   2.797e+03  9.131e+02   3.063 0.002254 ** 
#> BsmtFinType1  -1.451e+03  8.032e+02  -1.806 0.071172 .  
#> BsmtFinSF1     7.414e+00  5.528e+00   1.341 0.180182    
#> BsmtFinType2  -1.088e+03  9.266e+02  -1.174 0.240539    
#> BsmtFinSF2     1.563e+01  9.943e+00   1.572 0.116260    
#> BsmtUnfSF      4.039e+00  5.258e+00   0.768 0.442577    
#> Heating       -2.615e+03  3.565e+03  -0.733 0.463540    
#> HeatingQC     -1.979e+03  1.323e+03  -1.496 0.135001    
#> CentralAir     3.550e+03  5.218e+03   0.680 0.496492    
#> Electrical     2.494e+03  2.076e+03   1.202 0.229841    
#> `1stFlrSF`     5.930e+01  6.911e+00   8.580  < 2e-16 ***
#> `2ndFlrSF`     5.428e+01  5.697e+00   9.528  < 2e-16 ***
#> LowQualFinSF   3.185e+01  2.209e+01   1.442 0.149748    
#> BsmtFullBath   9.851e+03  2.804e+03   3.513 0.000464 ***
#> BsmtHalfBath  -4.255e+03  4.295e+03  -0.990 0.322194    
#> FullBath       8.674e+03  3.015e+03   2.877 0.004108 ** 
#> HalfBath       1.158e+03  2.840e+03   0.408 0.683593    
#> BedroomAbvGr  -4.936e+03  1.834e+03  -2.692 0.007234 ** 
#> KitchenAbvGr  -2.552e+04  5.962e+03  -4.281 2.05e-05 ***
#> KitchenQual    9.128e+03  1.694e+03   5.390 8.88e-08 ***
#> TotRmsAbvGrd   2.068e+03  1.336e+03   1.548 0.122031    
#> Functional    -5.560e+03  1.488e+03  -3.738 0.000197 ***
#> Fireplaces    -4.745e+03  2.446e+03  -1.940 0.052678 .  
#> FireplaceQu    5.241e+03  1.306e+03   4.012 6.51e-05 ***
#> GarageType     9.176e+02  1.263e+03   0.726 0.467814    
#> GarageYrBlt    6.327e+00  5.466e+00   1.157 0.247412    
#> GarageFinish   1.785e+03  1.402e+03   1.273 0.203333    
#> GarageCars     1.683e+04  3.095e+03   5.438 6.85e-08 ***
#> GarageArea    -1.251e+01  1.102e+01  -1.136 0.256393    
#> GarageQual     1.178e+04  3.417e+03   3.447 0.000593 ***
#> GarageCond    -5.041e+03  3.066e+03  -1.644 0.100498    
#> PavedDrive    -3.557e+03  3.052e+03  -1.166 0.244104    
#> WoodDeckSF     2.696e+01  8.604e+00   3.133 0.001781 ** 
#> OpenPorchSF    5.575e+01  1.771e+01   3.148 0.001694 ** 
#> EnclosedPorch  2.653e+01  1.708e+01   1.553 0.120660    
#> `3SsnPorch`    3.226e+01  3.428e+01   0.941 0.346883    
#> ScreenPorch    9.564e+01  1.835e+01   5.212 2.29e-07 ***
#> PoolArea       2.258e+00  2.396e+01   0.094 0.924936    
#> Fence          2.376e+02  1.032e+03   0.230 0.817969    
#> MiscVal       -6.378e+00  3.894e+00  -1.638 0.101777    
#> MoSold         3.176e+01  3.681e+02   0.086 0.931276    
#> YrSold        -1.713e+02  7.483e+02  -0.229 0.818919    
#> SaleType       2.710e+03  1.179e+03   2.298 0.021768 *  
#> SaleCondition  5.445e+02  1.240e+03   0.439 0.660576    
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for gaussian family taken to be 880991878)
#> 
#>     Null deviance: 5.8436e+12  on 1023  degrees of freedom
#> Residual deviance: 8.3606e+11  on  949  degrees of freedom
#> AIC: 24071
#> 
#> Number of Fisher Scoring iterations: 2
predictions <- lf$predict(df = xtest)
rmse(actual = xtest$SalePrice, predicted = predictions)
#> [1] 42695.53

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] 44060.97

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] 44333.7

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                         743435183121
#> GarageCars                          489893879930
#> GarageArea                          441815951053
#> 1stFlrSF                            356161506979
#> YearBuilt                           311939771420
#> FullBath                            262570733229
#> GarageYrBlt                         262170741647
#> ExterQual                           243595350781
#> BsmtFinSF1                          206158738480
#> 2ndFlrSF                            205039183274
#> TotRmsAbvGrd                        196920471625
#> LotArea                             168387251373
#> YearRemodAdd                        144115280224
#> FireplaceQu                         137860325007
#> KitchenQual                         130949040493
#> Fireplaces                          121198451193
#> LotFrontage                          87255005498
#> OpenPorchSF                          81715476429
#> BsmtQual                             80441940801
#> Foundation                           77410109548
#> MasVnrArea                           66689023211
#> WoodDeckSF                           66394649517
#> BsmtUnfSF                            64935206626
#> Exterior2nd                          54026497689
#> Neighborhood                         51883594823
#> BsmtFinType1                         51774434848
#> BedroomAbvGr                         50822093474
#> GarageType                           46439747471
#> MSSubClass                           39588718777
#> HeatingQC                            35934279233
#> Exterior1st                          31866215237
#> MoSold                               29098604606
#> HalfBath                             28535297832
#> OverallCond                          27708096342
#> HouseStyle                           27216690750
#> RoofStyle                            24729897064
#> GarageFinish                         24379790895
#> BsmtFullBath                         23131243845
#> LotShape                             21955245456
#> ScreenPorch                          21507369012
#> YrSold                               20074745966
#> Fence                                19042947761
#> PoolArea                             18742199122
#> BsmtExposure                         18733098697
#> SaleCondition                        17256734176
#> MasVnrType                           16139284583
#> MSZoning                             15806073763
#> LotConfig                            14223809742
#> BldgType                             14148578062
#> SaleType                             13749158274
#> CentralAir                           12603035608
#> LandContour                          11548349636
#> EnclosedPorch                        10647038713
#> LandSlope                            10423464767
#> GarageQual                           10268461948
#> Functional                            8095397342
#> GarageCond                            8065083623
#> BsmtFinSF2                            8044733851
#> BsmtCond                              7109605763
#> KitchenAbvGr                          6424575020
#> Condition1                            6372925405
#> ExterCond                             6061171430
#> LowQualFinSF                          5167996877
#> BsmtFinType2                          5055064611
#> RoofMatl                              4593729712
#> PavedDrive                            4550661205
#> Heating                               3107626404
#> Electrical                            2531439330
#> 3SsnPorch                             1984698586
#> MiscVal                               1916001617
#> BsmtHalfBath                          1858296435
#> Street                                 407115233
#> Condition2                             187123377
#> Utilities                               28297645
rmse(actual = xtest$SalePrice, predicted = pred)
#> [1] 35978.01

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.006828395
#> 
#> $accuracy_sd
#> [1] 0.003366528
#> 
#> $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