# Introduction to SuperML

#### Manish Saraswat

#### 2020-04-27

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")

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

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)
    #>
    #> Deviance Residuals:
    #>     Min       1Q   Median       3Q      Max
    #> -342200   -14216    -1480    13463   245838
    #>
    #> Coefficients:
    #>                 Estimate Std. Error t value Pr(>|t|)
    #> (Intercept)   -2.305e+05  1.632e+06  -0.141 0.887743
    #> MSSubClass    -1.813e+02  5.370e+01  -3.375 0.000767 ***
    #> MSZoning       1.225e+03  1.759e+03   0.696 0.486333
    #> LotFrontage   -7.683e+00  3.326e+01  -0.231 0.817388
    #> LotArea        2.416e-01  1.190e-01   2.031 0.042486 *
    #> Street        -2.528e+04  1.577e+04  -1.603 0.109193
    #> LotShape       2.484e+03  2.084e+03   1.192 0.233505
    #> LandContour   -3.151e+03  1.966e+03  -1.603 0.109201
    #> Utilities     -6.564e+04  3.447e+04  -1.904 0.057157 .
    #> LotConfig      1.708e+03  1.457e+03   1.173 0.241265
    #> LandSlope      1.137e+04  4.738e+03   2.400 0.016564 *
    #> Neighborhood   3.162e+02  2.001e+02   1.580 0.114487
    #> Condition1    -2.336e+03  7.744e+02  -3.017 0.002625 **
    #> Condition2    -1.040e+04  2.956e+03  -3.517 0.000457 ***
    #> BldgType      -7.246e+02  2.121e+03  -0.342 0.732673
    #> HouseStyle     1.270e+03  1.135e+03   1.119 0.263355
    #> OverallQual    1.537e+04  1.446e+03  10.630  < 2e-16 ***
    #> OverallCond    6.011e+03  1.273e+03   4.720 2.71e-06 ***
    #> YearBuilt      4.013e+02  8.225e+01   4.879 1.25e-06 ***
    #> YearRemodAdd   1.197e+02  8.127e+01   1.473 0.141139
    #> RoofStyle      7.258e+03  2.051e+03   3.539 0.000421 ***
    #> RoofMatl      -2.095e+04  2.710e+03  -7.732 2.69e-14 ***
    #> Exterior1st   -2.725e+02  5.223e+02  -0.522 0.602018
    #> Exterior2nd    3.827e+02  5.561e+02   0.688 0.491527
    #> MasVnrType     3.070e+03  1.659e+03   1.851 0.064529 .
    #> MasVnrArea     2.379e+01  7.045e+00   3.377 0.000762 ***
    #> ExterQual      2.751e+03  2.423e+03   1.136 0.256450
    #> ExterCond      1.855e+03  2.697e+03   0.688 0.491792
    #> Foundation    -6.744e+02  1.041e+03  -0.648 0.517211
    #> BsmtQual       4.414e+03  1.504e+03   2.936 0.003408 **
    #> BsmtCond      -2.998e+03  2.060e+03  -1.456 0.145804
    #> BsmtExposure   5.088e+03  1.009e+03   5.044 5.47e-07 ***
    #> BsmtFinType1  -7.513e+02  8.441e+02  -0.890 0.373714
    #> BsmtFinSF1     5.249e+00  5.935e+00   0.884 0.376696
    #> BsmtFinType2  -2.122e+03  1.443e+03  -1.471 0.141549
    #> BsmtFinSF2     1.701e+01  9.997e+00   1.702 0.089119 .
    #> BsmtUnfSF      3.625e+00  5.608e+00   0.647 0.518111
    #> Heating        4.859e+03  5.226e+03   0.930 0.352707
    #> HeatingQC     -2.789e+03  1.473e+03  -1.893 0.058691 .
    #> CentralAir     9.743e+03  5.777e+03   1.686 0.092059 .
    #> Electrical     1.737e+03  1.510e+03   1.150 0.250232
    #> `1stFlrSF`     4.560e+01  7.435e+00   6.134 1.26e-09 ***
    #> `2ndFlrSF`     5.598e+01  6.169e+00   9.074  < 2e-16 ***
    #> LowQualFinSF   4.220e+01  2.107e+01   2.003 0.045452 *
    #> BsmtFullBath   9.524e+03  3.083e+03   3.089 0.002064 **
    #> BsmtHalfBath   4.079e+03  4.459e+03   0.915 0.360529
    #> FullBath       6.131e+03  3.273e+03   1.873 0.061336 .
    #> HalfBath      -2.286e+03  3.030e+03  -0.754 0.450806
    #> BedroomAbvGr  -5.536e+03  1.937e+03  -2.858 0.004359 **
    #> KitchenAbvGr  -1.535e+04  6.145e+03  -2.498 0.012660 *
    #> KitchenQual    8.386e+03  1.564e+03   5.363 1.03e-07 ***
    #> TotRmsAbvGrd   2.330e+03  1.445e+03   1.613 0.107047
    #> Functional    -4.940e+03  1.530e+03  -3.229 0.001285 **
    #> Fireplaces    -1.561e+03  2.673e+03  -0.584 0.559417
    #> FireplaceQu    3.874e+03  1.370e+03   2.827 0.004799 **
    #> GarageType    -1.041e+03  9.860e+02  -1.056 0.291409
    #> GarageYrBlt    1.124e+00  5.971e+00   0.188 0.850699
    #> GarageFinish   4.476e+02  1.517e+03   0.295 0.767971
    #> GarageCars     1.296e+04  3.387e+03   3.827 0.000138 ***
    #> GarageArea     1.308e+01  1.145e+01   1.143 0.253427
    #> GarageQual     7.405e+03  3.456e+03   2.143 0.032401 *
    #> GarageCond    -9.136e+02  2.294e+03  -0.398 0.690543
    #> PavedDrive    -3.015e+03  3.372e+03  -0.894 0.371518
    #> WoodDeckSF     2.585e+01  8.821e+00   2.930 0.003469 **
    #> OpenPorchSF   -7.037e-01  1.730e+01  -0.041 0.967564
    #> EnclosedPorch -7.141e+00  2.055e+01  -0.347 0.728358
    #> `3SsnPorch`    5.197e+01  4.075e+01   1.275 0.202543
    #> ScreenPorch    6.234e+01  1.879e+01   3.317 0.000943 ***
    #> PoolArea       3.706e+01  2.669e+01   1.389 0.165266
    #> Fence         -2.369e+03  1.358e+03  -1.745 0.081312 .
    #> MiscVal       -7.650e-01  2.015e+00  -0.380 0.704273
    #> MoSold        -3.008e+02  3.920e+02  -0.767 0.443126
    #> YrSold        -4.324e+02  8.147e+02  -0.531 0.595781
    #> SaleType       2.057e+03  1.339e+03   1.536 0.124885
    #> SaleCondition  1.024e+03  1.241e+03   0.826 0.409259
    #> ---
    #> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
    #>
    #> (Dispersion parameter for gaussian family taken to be 1042176816)
    #>
    #>     Null deviance: 6.5520e+12  on 1023  degrees of freedom
    #> Residual deviance: 9.8903e+11  on  949  degrees of freedom
    #> AIC: 24243
    #>
    #> Number of Fisher Scoring iterations: 2
    predictions <- lf$predict(df = xtest)
    rmse(actual = xtest$SalePrice, predicted = predictions)
    #> [1] 31444.3

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

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

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                         806429001574
    #> GarageCars                          514930089326
    #> GarageArea                          477243445509
    #> 1stFlrSF                            432517479568
    #> YearBuilt                           358248448858
    #> FullBath                            301425527294
    #> KitchenQual                         300103186644
    #> GarageYrBlt                         272675268003
    #> 2ndFlrSF                            258245739868
    #> ExterQual                           223237069256
    #> BsmtFinSF1                          198350632427
    #> TotRmsAbvGrd                        190770130705
    #> YearRemodAdd                        172029162481
    #> LotArea                             168886829326
    #> FireplaceQu                         167059277652
    #> Fireplaces                          161457140551
    #> MasVnrArea                          123525744395
    #> BsmtQual                             98629991433
    #> OpenPorchSF                          90468152090
    #> LotFrontage                          85832302736
    #> WoodDeckSF                           77688299712
    #> HeatingQC                            67258379025
    #> Foundation                           65382098600
    #> BsmtUnfSF                            63289097509
    #> Neighborhood                         60544343321
    #> BedroomAbvGr                         55533166596
    #> BsmtFinType1                         50990775237
    #> GarageType                           41772112087
    #> Exterior2nd                          40330143410
    #> BsmtExposure                         40104367529
    #> MoSold                               38855636050
    #> MSSubClass                           38650931883
    #> OverallCond                          34833193956
    #> HalfBath                             32241782664
    #> HouseStyle                           29979016930
    #> Exterior1st                          29092430396
    #> LotShape                             26889365788
    #> GarageFinish                         26274340608
    #> RoofStyle                            26212549983
    #> YrSold                               23276775094
    #> BsmtFullBath                         20186362425
    #> SaleCondition                        18449885260
    #> PoolArea                             17713804419
    #> LandContour                          16429903396
    #> RoofMatl                             15416822915
    #> ScreenPorch                          15244718786
    #> MSZoning                             14675692653
    #> MasVnrType                           14550979527
    #> LandSlope                            12991083252
    #> BsmtHalfBath                         12809765117
    #> LotConfig                            12520012881
    #> GarageQual                           11739965065
    #> Fence                                11703049011
    #> Condition1                           10885036153
    #> SaleType                             10882105335
    #> BldgType                             10589459949
    #> BsmtCond                              9917213827
    #> BsmtFinSF2                            8289027381
    #> EnclosedPorch                         8152482434
    #> GarageCond                            7907840713
    #> CentralAir                            7824960809
    #> BsmtFinType2                          6972322859
    #> Functional                            5741981926
    #> KitchenAbvGr                          5656757289
    #> PavedDrive                            5094126962
    #> ExterCond                             4585540342
    #> 3SsnPorch                             3509837398
    #> Electrical                            3425486950
    #> LowQualFinSF                          3282677678
    #> Condition2                            2945720294
    #> Heating                               2073545813
    #> MiscVal                               1488548092
    #> Street                                 348080224
    #> Utilities                               23425353
    rmse(actual = xtest$SalePrice, predicted = pred)
    #> [1] 29082.98

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)
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:179201.328125    val-rmse:177621.484375
    #> Multiple eval metrics are present. Will use val_rmse for early stopping.
    #> Will train until val_rmse hasn't improved in 50 rounds.
    #>
    #> [51] train-rmse:8308.346680  val-rmse:26317.550781
    #> [101]    train-rmse:4910.869141  val-rmse:25718.234375
    #> [151]    train-rmse:3218.866211  val-rmse:25672.822266
    #> Stopping. Best iteration:
    #> [131]    train-rmse:3860.479004  val-rmse:25638.552734
    pred <- xgb$predict(xtest)
    rmse(actual = xtest$SalePrice, predicted = pred)
    #> [1] 25638.56

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")
    #> [1] "entering grid search"
    #> [1] "In total, 4 models will be trained"
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:144640.171875
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [10] train-rmse:16937.876953
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:138590.734375
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [10] train-rmse:15151.860352
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:144085.812500
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [10] train-rmse:15885.150391
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:144640.171875
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [50] train-rmse:3556.593506
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:138590.734375
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [50] train-rmse:3428.140137
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:144085.812500
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [50] train-rmse:3331.416748
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:145535.093750
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [10] train-rmse:32374.402344
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:139217.687500
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [10] train-rmse:30047.097656
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:144978.218750
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [10] train-rmse:29365.738281
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:145535.093750
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [50] train-rmse:17672.855469
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:139217.687500
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [50] train-rmse:17387.134766
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-rmse:144978.218750
    #> Will train until train_rmse hasn't improved in 50 rounds.
    #>
    #> [50] train-rmse:15668.986328
    gst$best_iteration()
    #> $n_estimators
    #> [1] 10
    #>
    #> $max_depth
    #> [1] 5
    #>
    #> $accuracy_avg
    #> [1] 0
    #>
    #> $accuracy_sd
    #> [1] 0
    #>
    #> $auc_avg
    #> [1] NaN
    #>
    #> $auc_sd
    #> [1] NA

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.009772447
    #>
    #> $accuracy_sd
    #> [1] 0.004508824
    #>
    #> $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
    #> 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
    #> 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
    #> 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)
    #>
    #> Deviance Residuals:
    #>     Min       1Q   Median       3Q      Max
    #> -2.6102  -0.6018  -0.4367   0.7038   2.4493
    #>
    #> 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                                67.80128
    #> Fare                               57.97193
    #> Age                                48.37045
    #> Pclass                             24.64915
    #> Cabin                              21.45972
    #> SibSp                              13.51637
    #> Parch                              10.45743
    #> Embarked                           10.23844

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

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)
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-auc:0.886258  val-auc:0.879085
    #> Multiple eval metrics are present. Will use val_auc for early stopping.
    #> Will train until val_auc hasn't improved in 50 rounds.
    #>
    #> [51] train-auc:0.972938  val-auc:0.866370
    #> Stopping. Best iteration:
    #> [1]  train-auc:0.886258  val-auc:0.879085

    pred <- xgb$predict(xtest)
    auc(actual = xtest$Survived, predicted = pred)
    #> [1] 0.879085

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")
    #> [1] "entering grid search"
    #> [1] "In total, 4 models will be trained"
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.144231
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [10] train-error:0.108173
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.134615
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [10] train-error:0.112981
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.115385
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [10] train-error:0.084135
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.144231
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [50] train-error:0.045673
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.134615
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [50] train-error:0.045673
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.115385
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [50] train-error:0.038462
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.211538
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [10] train-error:0.158654
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.201923
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [10] train-error:0.168269
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.206731
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [10] train-error:0.141827
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.211538
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [50] train-error:0.127404
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.201923
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [50] train-error:0.132212
    #> converting the data into xgboost format..
    #> starting with training...
    #> [1]  train-error:0.206731
    #> Will train until train_error hasn't improved in 50 rounds.
    #>
    #> [50] train-error:0.108173
    gst$best_iteration()
    #> $n_estimators
    #> [1] 10
    #>
    #> $max_depth
    #> [1] 5
    #>
    #> $accuracy_avg
    #> [1] 0
    #>
    #> $accuracy_sd
    #> [1] 0
    #>
    #> $auc_avg
    #> [1] 0.8619512
    #>
    #> $auc_sd
    #> [1] 0.02280628

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.7964744
    #>
    #> $accuracy_sd
    #> [1] 0.03090914
    #>
    #> $auc_avg
    #> [1] 0.7729436
    #>
    #> $auc_sd
    #> [1] 0.04283084

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                               69.787235
    #> Fare                              60.832089
    #> Age                               52.982604
    #> Pclass                            24.419818
    #> Cabin                             21.419274
    #> SibSp                             13.112177
    #> Parch                             10.175269
    #> feat_01                            6.675399
    #> Embarked                           6.450819

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