Лабораторная работа: CARET, FSelector, arules, Boruta

1. CARET: генерация данных и графический анализ

library(caret)
set.seed(123)

x <- matrix(rnorm(50*5), ncol=5)
colnames(x) <- paste0("X", 1:5)
y <- factor(rep(c("A","B"), 25))

# Список моделей CARET (первые 20)
cat("Список первых 20 моделей CARET:\n")
## Список первых 20 моделей CARET:
print(names(getModelInfo())[1:20])
##  [1] "ada"         "AdaBag"      "AdaBoost.M1" "adaboost"    "amdai"      
##  [6] "ANFIS"       "avNNet"      "awnb"        "awtan"       "bag"        
## [11] "bagEarth"    "bagEarthGCV" "bagFDA"      "bagFDAGCV"   "bam"        
## [16] "bartMachine" "bayesglm"    "binda"       "blackboost"  "blasso"
# Сохраняем графики
jpeg("featurePlot_pairs.jpg", width=1200, height=800, quality=95)
featurePlot(x, y, plot="pairs", main="featurePlot: pairs")
dev.off()
## png 
##   2
jpeg("featurePlot_box.jpg", width=1200, height=800, quality=95)
featurePlot(x, y, plot="box", main="featurePlot: box")
dev.off()
## png 
##   2
jpeg("featurePlot_density.jpg", width=1200, height=800, quality=95)
featurePlot(x, y, plot="density", main="featurePlot: density")
dev.off()
## png 
##   2

Вывод: Графики позволяют визуально оценить распределение признаков по классам. Pairs показывает взаимосвязь между признаками, box — распределение по классам, density — плотность распределения.

2. FSelector: оценка важности признаков

library(FSelector)
data(iris)

ig <- information.gain(Species ~ ., iris)
chi <- chi.squared(Species ~ ., iris)
gr <- gain.ratio(Species ~ ., iris)


print(ig)
##              attr_importance
## Sepal.Length       0.4521286
## Sepal.Width        0.2672750
## Petal.Length       0.9402853
## Petal.Width        0.9554360
print(chi)
##              attr_importance
## Sepal.Length       0.6288067
## Sepal.Width        0.4922162
## Petal.Length       0.9346311
## Petal.Width        0.9432359
print(gr)
##              attr_importance
## Sepal.Length       0.4196464
## Sepal.Width        0.2472972
## Petal.Length       0.8584937
## Petal.Width        0.8713692

Вывод: Наиболее информативные признаки для классификации цветов ириса: Petal.Length и Petal.Width. Методы дают согласованные результаты и помогают выбрать признаки для модели.

3. arules: дискретизация переменной

library(arules)
vec <- iris$Sepal.Length

d_interval <- discretize(vec, method="interval", categories=4)
d_freq     <- discretize(vec, method="frequency", categories=4)
d_cluster  <- discretize(vec, method="cluster", categories=4)
d_fixed    <- discretize(vec, method="fixed", breaks=c(min(vec)-1,5,5.8,6.8,max(vec)+1))


print(table(d_interval))
## d_interval
## [4.3,5.2) [5.2,6.1)   [6.1,7)   [7,7.9] 
##        41        48        48        13
print(table(d_freq))
## d_freq
## [4.3,5.1) [5.1,5.8) [5.8,6.4) [6.4,7.9] 
##        32        41        35        42
print(table(d_cluster))
## d_cluster
##  [4.3,5.28) [5.28,6.05) [6.05,6.87)  [6.87,7.9] 
##          45          44          44          17
print(table(d_fixed))
## d_fixed
##   [3.3,5)   [5,5.8) [5.8,6.8) [6.8,8.9] 
##        22        51        57        20

Вывод: Разные методы дискретизации создают категории с равной шириной, равной частотой, с помощью кластеризации или фиксированных границ. Это удобно для дальнейшей классификации и анализа категориальных признаков.

4. Boruta: выбор значимых признаков

library(Boruta)
library(mlbench)

data("Ozone", package="mlbench")
ozone_df <- as.data.frame(Ozone)
ozone_df <- na.omit(ozone_df)  # удаляем пропуски

num_cols <- sapply(ozone_df, is.numeric)
ozone_num <- ozone_df[, num_cols]

target <- "V4"  # целевая переменная

set.seed(123)
boruta_out <- Boruta(ozone_num[[target]] ~ ., data = ozone_num, doTrace = 0, maxRuns = 100)

print(boruta_out)
## Boruta performed 21 iterations in 0.730109 secs.
##  9 attributes confirmed important: V10, V11, V12, V13, V4 and 4 more;
##  1 attributes confirmed unimportant: V6;
plot(boruta_out, las=2, main="Boruta: важность признаков (V4)")

print(attStats(boruta_out))
##       meanImp  medianImp    minImp    maxImp  normHits  decision
## V4  30.140582 29.9381757 28.630971 32.383696 1.0000000 Confirmed
## V5   6.899862  6.9865194  5.591682  8.169510 1.0000000 Confirmed
## V6   1.026869  0.9012775 -1.324166  3.854948 0.1428571  Rejected
## V7   9.267082  9.3645439  8.054472 10.934466 1.0000000 Confirmed
## V8  13.119853 13.1158300 11.881688 14.125725 1.0000000 Confirmed
## V9  14.564120 14.5353470 13.769412 15.441997 1.0000000 Confirmed
## V10  7.684705  7.6228960  6.575850  8.716281 1.0000000 Confirmed
## V11  9.311080  9.2220509  8.434691 10.623484 1.0000000 Confirmed
## V12 11.164337 11.1556660 10.234722 11.968340 1.0000000 Confirmed
## V13  7.575104  7.3743349  6.872954  8.848818 1.0000000 Confirmed

Вывод: Boruta позволяет определить значимые признаки для предсказания целевой переменной V4. Shadow-признаки помогают отделить нерелевантные признаки. На графике boxplot видно, какие признаки подтверждены как важные, а какие — нет.