Introduction to SuperML

Manish Saraswat

2022-05-23

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: 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 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

SVM Regression

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  
#> -139243   -13025     -186    12472   158743  
#> 
#> Coefficients:
#>                 Estimate Std. Error t value Pr(>|t|)    
#> (Intercept)   -2.008e+06  1.260e+06  -1.593 0.111462    
#> MSSubClass    -3.830e+01  4.350e+01  -0.880 0.378829    
#> MSZoning      -1.445e+02  1.162e+03  -0.124 0.901098    
#> LotFrontage    6.473e+01  2.697e+01   2.400 0.016598 *  
#> LotArea        4.401e-01  1.168e-01   3.767 0.000176 ***
#> Street        -3.784e+04  1.182e+04  -3.201 0.001414 ** 
#> LotShape       3.651e+03  1.641e+03   2.225 0.026301 *  
#> LandContour    2.807e+03  1.842e+03   1.524 0.127719    
#> Utilities     -2.701e+04  2.727e+04  -0.991 0.322180    
#> LotConfig      3.069e+02  8.777e+02   0.350 0.726639    
#> LandSlope      1.813e+03  4.229e+03   0.429 0.668286    
#> Neighborhood  -3.361e+02  1.538e+02  -2.186 0.029074 *  
#> Condition1    -1.932e+03  6.913e+02  -2.795 0.005297 ** 
#> Condition2    -4.259e+03  3.532e+03  -1.206 0.228200    
#> BldgType      -2.483e+03  1.668e+03  -1.488 0.136958    
#> HouseStyle     2.632e+02  8.262e+02   0.319 0.750084    
#> OverallQual    1.336e+04  1.120e+03  11.930  < 2e-16 ***
#> OverallCond    6.068e+03  9.974e+02   6.084 1.70e-09 ***
#> YearBuilt      4.657e+02  6.701e+01   6.950 6.80e-12 ***
#> YearRemodAdd   1.766e+02  6.343e+01   2.784 0.005477 ** 
#> RoofStyle     -1.631e+02  1.564e+03  -0.104 0.916996    
#> RoofMatl      -9.933e+02  2.137e+03  -0.465 0.642230    
#> Exterior1st   -4.735e+02  5.755e+02  -0.823 0.410843    
#> Exterior2nd    9.892e+02  5.221e+02   1.895 0.058425 .  
#> MasVnrType     4.333e+03  1.360e+03   3.186 0.001489 ** 
#> MasVnrArea     1.631e+01  5.720e+00   2.852 0.004438 ** 
#> ExterQual      3.787e+03  1.960e+03   1.932 0.053642 .  
#> ExterCond      1.081e+03  1.979e+03   0.547 0.584829    
#> Foundation     3.883e+02  1.450e+03   0.268 0.788846    
#> BsmtQual       7.885e+03  1.226e+03   6.429 2.03e-10 ***
#> BsmtCond      -1.370e+03  1.557e+03  -0.880 0.379040    
#> BsmtExposure   2.390e+03  8.087e+02   2.956 0.003198 ** 
#> BsmtFinType1  -2.546e+02  6.252e+02  -0.407 0.683943    
#> BsmtFinSF1     5.254e+01  4.982e+00  10.544  < 2e-16 ***
#> BsmtFinType2  -9.432e+02  9.958e+02  -0.947 0.343782    
#> BsmtFinSF2     4.247e+01  8.402e+00   5.055 5.16e-07 ***
#> BsmtUnfSF      3.213e+01  4.503e+00   7.136 1.90e-12 ***
#> Heating        1.569e+03  3.627e+03   0.433 0.665359    
#> HeatingQC     -2.590e+03  1.113e+03  -2.326 0.020214 *  
#> CentralAir     4.251e+03  4.370e+03   0.973 0.330970    
#> Electrical     2.337e+03  1.815e+03   1.287 0.198278    
#> `1stFlrSF`     5.243e+01  5.824e+00   9.002  < 2e-16 ***
#> `2ndFlrSF`     6.578e+01  5.045e+00  13.038  < 2e-16 ***
#> LowQualFinSF   2.598e+00  1.859e+01   0.140 0.888898    
#> BsmtFullBath   1.516e+03  2.452e+03   0.618 0.536538    
#> BsmtHalfBath  -8.169e+03  3.729e+03  -2.191 0.028694 *  
#> FullBath       3.146e+03  2.583e+03   1.218 0.223441    
#> HalfBath      -1.372e+03  2.416e+03  -0.568 0.570139    
#> BedroomAbvGr  -1.173e+04  1.594e+03  -7.358 4.05e-13 ***
#> KitchenAbvGr  -2.394e+04  4.839e+03  -4.948 8.89e-07 ***
#> KitchenQual    7.690e+03  1.521e+03   5.057 5.11e-07 ***
#> TotRmsAbvGrd   3.323e+03  1.160e+03   2.865 0.004266 ** 
#> Functional    -8.284e+03  1.356e+03  -6.110 1.45e-09 ***
#> Fireplaces     8.055e+02  2.159e+03   0.373 0.709194    
#> FireplaceQu    1.473e+03  1.181e+03   1.248 0.212406    
#> GarageType     1.958e+03  1.083e+03   1.808 0.070876 .  
#> GarageYrBlt    1.195e+00  4.366e+00   0.274 0.784395    
#> GarageFinish   2.291e+03  1.200e+03   1.910 0.056460 .  
#> GarageCars     4.727e+03  2.887e+03   1.637 0.101914    
#> GarageArea     1.305e+01  9.440e+00   1.383 0.167042    
#> GarageQual     4.180e+03  2.532e+03   1.651 0.099071 .  
#> GarageCond    -3.997e+03  2.491e+03  -1.604 0.108970    
#> PavedDrive    -3.272e+03  2.625e+03  -1.246 0.212904    
#> WoodDeckSF     1.629e+01  7.618e+00   2.138 0.032734 *  
#> OpenPorchSF    2.127e+01  1.437e+01   1.479 0.139374    
#> EnclosedPorch  3.056e+00  1.515e+01   0.202 0.840151    
#> `3SsnPorch`    1.704e+01  3.440e+01   0.495 0.620553    
#> ScreenPorch    3.825e+01  1.530e+01   2.500 0.012578 *  
#> PoolArea       1.092e+02  2.295e+01   4.758 2.26e-06 ***
#> Fence         -1.986e+03  1.152e+03  -1.724 0.085018 .  
#> MiscVal       -1.095e+00  4.416e+00  -0.248 0.804163    
#> MoSold        -2.236e+02  3.141e+02  -0.712 0.476744    
#> YrSold         3.308e+02  6.273e+02   0.527 0.598066    
#> SaleType       1.091e+03  1.100e+03   0.992 0.321271    
#> SaleCondition  1.645e+03  9.888e+02   1.663 0.096558 .  
#> ---
#> Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
#> 
#> (Dispersion parameter for gaussian family taken to be 648612116)
#> 
#>     Null deviance: 6.2335e+12  on 1023  degrees of freedom
#> Residual deviance: 6.1553e+11  on  949  degrees of freedom
#> AIC: 23757
#> 
#> Number of Fisher Scoring iterations: 2
predictions <- lf$predict(df = xtest)
rmse(actual = xtest$SalePrice, predicted = predictions)
#> [1] 51530.25

Lasso Regression

Ridge Regression

Logistic Regression with CV

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                         833350284068
#> GarageCars                          465479127916
#> 1stFlrSF                            445606600578
#> GarageArea                          396242047750
#> YearBuilt                           364988991992
#> FullBath                            286370539079
#> BsmtFinSF1                          284612099870
#> GarageYrBlt                         254491890949
#> ExterQual                           223773978981
#> TotRmsAbvGrd                        219141701180
#> 2ndFlrSF                            189706505897
#> LotArea                             169461096779
#> Fireplaces                          141235914606
#> YearRemodAdd                        134142408678
#> KitchenQual                         132732494284
#> FireplaceQu                         131673516393
#> MasVnrArea                          107853599183
#> Foundation                          104223221462
#> BsmtQual                             99876088175
#> OpenPorchSF                          83642601447
#> BsmtFinType1                         78327672652
#> LotFrontage                          77809357818
#> BsmtUnfSF                            63322066423
#> Neighborhood                         61053253580
#> WoodDeckSF                           59661913778
#> HeatingQC                            51360521952
#> GarageType                           47242624339
#> BedroomAbvGr                         41064075573
#> Exterior2nd                          38308339821
#> Exterior1st                          35097827861
#> MSSubClass                           34774064972
#> OverallCond                          33679741152
#> RoofStyle                            31494089946
#> HalfBath                             30374947665
#> MoSold                               30024831953
#> GarageFinish                         29552460141
#> HouseStyle                           26939781931
#> BsmtExposure                         22214362388
#> MSZoning                             21832228050
#> BsmtFullBath                         21242098578
#> LotShape                             20582280804
#> YrSold                               18993656717
#> MasVnrType                           16121832830
#> LandContour                          15579897406
#> LotConfig                            14240812890
#> GarageQual                           14017925183
#> SaleType                             13991450447
#> SaleCondition                        13697063876
#> GarageCond                           12968703189
#> ScreenPorch                          12669353846
#> CentralAir                           12257009224
#> LandSlope                            11752540501
#> BldgType                             10826146503
#> PoolArea                              9881220379
#> BsmtCond                              9136680119
#> Fence                                 8706441341
#> ExterCond                             8230230400
#> EnclosedPorch                         8095663365
#> BsmtFinSF2                            6653807222
#> Functional                            6329620593
#> KitchenAbvGr                          5895685275
#> BsmtFinType2                          5833219898
#> LowQualFinSF                          4879512060
#> Condition1                            4860876751
#> RoofMatl                              3785085428
#> PavedDrive                            3709917158
#> Electrical                            3491437439
#> BsmtHalfBath                          3357275107
#> MiscVal                               2143773519
#> 3SsnPorch                             2123549514
#> Heating                               1308976630
#> Street                                 830618588
#> Condition2                             201504146
#> Utilities                               54630098
rmse(actual = xtest$SalePrice, predicted = pred)
#> [1] 35475.5

Xgboost

Grid Search

Random Search

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

Naive Bayes Classification

SVM Classification

Logistic Regression

Lasso Logistic Regression

Ridge Logistic Regression

Random Forest

Xgboost

Grid Search

Random Search

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