Установка пакетов выполняется один раз.

install.packages(c(
  "caret",
  "FSelectorRcpp",
  "arules",
  "Boruta",
  "mlbench",
  "randomForest",
  "rmarkdown",
  "knitr"
))
library(caret)
library(FSelectorRcpp)
library(arules)
library(Boruta)
library(mlbench)

set.seed(123)

if (!dir.exists("figs")) {
  dir.create("figs")
}

1. Пакет CARET

names(getModelInfo())
##   [1] "ada"                 "AdaBag"              "AdaBoost.M1"        
##   [4] "adaboost"            "amdai"               "ANFIS"              
##   [7] "avNNet"              "awnb"                "awtan"              
##  [10] "bag"                 "bagEarth"            "bagEarthGCV"        
##  [13] "bagFDA"              "bagFDAGCV"           "bam"                
##  [16] "bartMachine"         "bayesglm"            "binda"              
##  [19] "blackboost"          "blasso"              "blassoAveraged"     
##  [22] "bridge"              "brnn"                "BstLm"              
##  [25] "bstSm"               "bstTree"             "C5.0"               
##  [28] "C5.0Cost"            "C5.0Rules"           "C5.0Tree"           
##  [31] "cforest"             "chaid"               "CSimca"             
##  [34] "ctree"               "ctree2"              "cubist"             
##  [37] "dda"                 "deepboost"           "DENFIS"             
##  [40] "dnn"                 "dwdLinear"           "dwdPoly"            
##  [43] "dwdRadial"           "earth"               "elm"                
##  [46] "enet"                "evtree"              "extraTrees"         
##  [49] "fda"                 "FH.GBML"             "FIR.DM"             
##  [52] "foba"                "FRBCS.CHI"           "FRBCS.W"            
##  [55] "FS.HGD"              "gam"                 "gamboost"           
##  [58] "gamLoess"            "gamSpline"           "gaussprLinear"      
##  [61] "gaussprPoly"         "gaussprRadial"       "gbm_h2o"            
##  [64] "gbm"                 "gcvEarth"            "GFS.FR.MOGUL"       
##  [67] "GFS.LT.RS"           "GFS.THRIFT"          "glm.nb"             
##  [70] "glm"                 "glmboost"            "glmnet_h2o"         
##  [73] "glmnet"              "glmStepAIC"          "gpls"               
##  [76] "hda"                 "hdda"                "hdrda"              
##  [79] "HYFIS"               "icr"                 "J48"                
##  [82] "JRip"                "kernelpls"           "kknn"               
##  [85] "knn"                 "krlsPoly"            "krlsRadial"         
##  [88] "lars"                "lars2"               "lasso"              
##  [91] "lda"                 "lda2"                "leapBackward"       
##  [94] "leapForward"         "leapSeq"             "Linda"              
##  [97] "lm"                  "lmStepAIC"           "LMT"                
## [100] "loclda"              "logicBag"            "LogitBoost"         
## [103] "logreg"              "lssvmLinear"         "lssvmPoly"          
## [106] "lssvmRadial"         "lvq"                 "M5"                 
## [109] "M5Rules"             "manb"                "mda"                
## [112] "Mlda"                "mlp"                 "mlpKerasDecay"      
## [115] "mlpKerasDecayCost"   "mlpKerasDropout"     "mlpKerasDropoutCost"
## [118] "mlpML"               "mlpSGD"              "mlpWeightDecay"     
## [121] "mlpWeightDecayML"    "monmlp"              "msaenet"            
## [124] "multinom"            "mxnet"               "mxnetAdam"          
## [127] "naive_bayes"         "nb"                  "nbDiscrete"         
## [130] "nbSearch"            "neuralnet"           "nnet"               
## [133] "nnls"                "nodeHarvest"         "null"               
## [136] "OneR"                "ordinalNet"          "ordinalRF"          
## [139] "ORFlog"              "ORFpls"              "ORFridge"           
## [142] "ORFsvm"              "ownn"                "pam"                
## [145] "parRF"               "PART"                "partDSA"            
## [148] "pcaNNet"             "pcr"                 "pda"                
## [151] "pda2"                "penalized"           "PenalizedLDA"       
## [154] "plr"                 "pls"                 "plsRglm"            
## [157] "polr"                "ppr"                 "pre"                
## [160] "PRIM"                "protoclass"          "qda"                
## [163] "QdaCov"              "qrf"                 "qrnn"               
## [166] "randomGLM"           "ranger"              "rbf"                
## [169] "rbfDDA"              "Rborist"             "rda"                
## [172] "regLogistic"         "relaxo"              "rf"                 
## [175] "rFerns"              "RFlda"               "rfRules"            
## [178] "ridge"               "rlda"                "rlm"                
## [181] "rmda"                "rocc"                "rotationForest"     
## [184] "rotationForestCp"    "rpart"               "rpart1SE"           
## [187] "rpart2"              "rpartCost"           "rpartScore"         
## [190] "rqlasso"             "rqnc"                "RRF"                
## [193] "RRFglobal"           "rrlda"               "RSimca"             
## [196] "rvmLinear"           "rvmPoly"             "rvmRadial"          
## [199] "SBC"                 "sda"                 "sdwd"               
## [202] "simpls"              "SLAVE"               "slda"               
## [205] "smda"                "snn"                 "sparseLDA"          
## [208] "spikeslab"           "spls"                "stepLDA"            
## [211] "stepQDA"             "superpc"             "svmBoundrangeString"
## [214] "svmExpoString"       "svmLinear"           "svmLinear2"         
## [217] "svmLinear3"          "svmLinearWeights"    "svmLinearWeights2"  
## [220] "svmPoly"             "svmRadial"           "svmRadialCost"      
## [223] "svmRadialSigma"      "svmRadialWeights"    "svmSpectrumString"  
## [226] "tan"                 "tanSearch"           "treebag"            
## [229] "vbmpRadial"          "vglmAdjCat"          "vglmContRatio"      
## [232] "vglmCumulative"      "widekernelpls"       "WM"                 
## [235] "wsrf"                "xgbDART"             "xgbLinear"          
## [238] "xgbTree"             "xyf"
x <- matrix(rnorm(50 * 5), ncol = 5)
colnames(x) <- paste0("X", 1:5)
y <- factor(rep(c("A", "B"), 25))
jpeg("figs/caret_pairs.jpg", width = 1200, height = 900, quality = 95)
print(featurePlot(x = x, y = y, plot = "pairs", auto.key = list(columns = 2)))
dev.off()
## png 
##   2
jpeg("figs/caret_density.jpg", width = 1200, height = 900, quality = 95)
print(featurePlot(x = x, y = y, plot = "density",
                  scales = list(x = list(relation = "free"))))
dev.off()
## png 
##   2
jpeg("figs/caret_box.jpg", width = 1200, height = 900, quality = 95)
print(featurePlot(x = x, y = y, plot = "box"))
dev.off()
## png 
##   2

Вывод: признаки сгенерированы случайно, поэтому классы A и B на графиках сильно перекрываются. Явного разделения классов по признакам не наблюдается.

2. Важность признаков для iris

Обычный пакет FSelector на данном компьютере не запускается из-за ошибки Java, поэтому использован совместимый пакет FSelectorRcpp.

data(iris)
ig <- information_gain(Species ~ ., data = iris, type = "infogain")
gr <- information_gain(Species ~ ., data = iris, type = "gainratio")
su <- information_gain(Species ~ ., data = iris, type = "symuncert")
rel <- relief(Species ~ ., data = iris, neighboursCount = 5, sampleSize = 20)

importance <- data.frame(
  Feature = ig$attributes,
  Information_Gain = ig$importance,
  Gain_Ratio = gr$importance,
  Symmetrical_Uncertainty = su$importance,
  Relief = rel$importance
)

importance[order(-importance$Information_Gain), ]
##        Feature Information_Gain Gain_Ratio Symmetrical_Uncertainty    Relief
## 4  Petal.Width        0.9554360  0.8713692               0.8705214 0.3502083
## 3 Petal.Length        0.9402853  0.8584937               0.8571872 0.3440678
## 1 Sepal.Length        0.4521286  0.4196464               0.4155563 0.1645833
## 2  Sepal.Width        0.2672750  0.2472972               0.2452743 0.1356250
barplot(
  importance$Information_Gain,
  names.arg = importance$Feature,
  las = 2,
  col = "lightblue",
  main = "Важность признаков iris",
  ylab = "Information Gain"
)

Вывод: наиболее важными признаками для классификации ирисов являются Petal.Length и Petal.Width. Признаки Sepal.Length и Sepal.Width менее информативны.

3. Дискретизация признаков

sl <- iris$Sepal.Length
d_interval <- discretize(sl, method = "interval", breaks = 3)
table(d_interval)
## d_interval
## [4.3,5.5) [5.5,6.7) [6.7,7.9] 
##        52        70        28
d_frequency <- discretize(sl, method = "frequency", breaks = 3)
table(d_frequency)
## d_frequency
## [4.3,5.4) [5.4,6.3) [6.3,7.9] 
##        46        53        51
d_cluster <- discretize(sl, method = "cluster", breaks = 3)
table(d_cluster)
## d_cluster
##  [4.3,5.33) [5.33,6.27)  [6.27,7.9] 
##          46          53          51
d_fixed <- discretize(sl, method = "fixed", breaks = c(5.5, 6.5))
table(d_fixed)
## d_fixed
## [5.5,6.5] 
##        68
head(data.frame(
  Sepal.Length = sl,
  interval = d_interval,
  frequency = d_frequency,
  cluster = d_cluster,
  fixed = d_fixed
))
##   Sepal.Length  interval frequency     cluster fixed
## 1          5.1 [4.3,5.5) [4.3,5.4)  [4.3,5.33)  <NA>
## 2          4.9 [4.3,5.5) [4.3,5.4)  [4.3,5.33)  <NA>
## 3          4.7 [4.3,5.5) [4.3,5.4)  [4.3,5.33)  <NA>
## 4          4.6 [4.3,5.5) [4.3,5.4)  [4.3,5.33)  <NA>
## 5          5.0 [4.3,5.5) [4.3,5.4)  [4.3,5.33)  <NA>
## 6          5.4 [4.3,5.5) [5.4,6.3) [5.33,6.27)  <NA>

Вывод: метод interval делит значения на интервалы равной ширины, frequency делает группы примерно равными по числу объектов, cluster использует кластеризацию, а fixed применяет заранее заданные границы.

4. Выбор признаков с помощью Boruta

data("Ozone", package = "mlbench")
ozo <- na.omit(Ozone)
boruta_ozo <- Boruta(V4 ~ ., data = ozo, doTrace = 0, maxRuns = 100)
boruta_final <- TentativeRoughFix(boruta_ozo)
## Warning in TentativeRoughFix(boruta_ozo): There are no Tentative attributes!
## Returning original object.
boruta_final
## Boruta performed 21 iterations in 0.1828592 secs.
##  9 attributes confirmed important: V1, V10, V11, V12, V13 and 4 more;
##  3 attributes confirmed unimportant: V2, V3, V6;
attStats(boruta_final)
##         meanImp   medianImp      minImp     maxImp   normHits  decision
## V1   0.40539847  0.40642988  0.33443318 0.46794786 1.00000000 Confirmed
## V2   0.04694280  0.03996016 -0.01933979 0.11724390 0.04761905  Rejected
## V3  -0.05868909 -0.07569424 -0.11701706 0.03393198 0.00000000  Rejected
## V5   0.38618563  0.39003277  0.34188322 0.42571719 1.00000000 Confirmed
## V6   0.04184227  0.03949771 -0.02048419 0.13561582 0.14285714  Rejected
## V7   0.51827308  0.51510008  0.44684417 0.59395833 1.00000000 Confirmed
## V8   0.77327105  0.78086300  0.69631396 0.82506181 1.00000000 Confirmed
## V9   0.87164021  0.86647893  0.79318976 0.93859006 1.00000000 Confirmed
## V10  0.44857358  0.44882788  0.41852372 0.48910026 1.00000000 Confirmed
## V11  0.54561567  0.55227270  0.44966453 0.63220513 1.00000000 Confirmed
## V12  0.65892780  0.64623327  0.58965492 0.71349070 1.00000000 Confirmed
## V13  0.40205675  0.40106143  0.35016242 0.45802074 1.00000000 Confirmed
jpeg("figs/boruta_ozone_boxplot.jpg", width = 1200, height = 900, quality = 95)
plot(boruta_ozo, las = 2, cex.axis = 0.7)
dev.off()
## png 
##   2

getSelectedAttributes(boruta_final, withTentative = FALSE)
## [1] "V1"  "V5"  "V7"  "V8"  "V9"  "V10" "V11" "V12" "V13"

Вывод: признаки со статусом Confirmed являются значимыми для предсказания переменной V4. Признаки со статусом Rejected можно исключить из модели.