> library(pacman)
> p_load(dplyr, caret)
决策树有多种实现算法,它们之间的区别主要是分裂准则的选择和剪枝过程。
ID3算法采用的分裂准则是加权的熵约简,也被称为信息增益。这个准则存在选择性偏误的问题,即它会有利于类别变量,因为和连续特征能找到的线性的分裂范围相比,类别变量的分组数量可能非常大。
C4.5算法将信息增益改进为信息增益率,这是信息增益的归一化版本。
C5.0算法采用的分裂准则为熵或信息统计量,它的根源来自信息论。C5.0是一种非常强大的算法,它还包含了对速度、内存使用、局部增强能力的改进,以及指定一个成本矩阵的成立,让算法避免做出某些类型的错误分类。
1、数据准备与数据理解
使用纸币真实性验证数据集,该数据集的创建者从真实和伪造两种纸币中各挑选了一些样本,并用工业相机对它们拍照,产生的灰度图用小波变换的时间-频率变换进行处理。
> bnote <- read.csv("data_set/data_banknote_authentication.txt", header = F)
> str(bnote)
## 'data.frame': 1372 obs. of 5 variables:
## $ V1: num 3.622 4.546 3.866 3.457 0.329 ...
## $ V2: num 8.67 8.17 -2.64 9.52 -4.46 ...
## $ V3: num -2.81 -2.46 1.92 -4.01 4.57 ...
## $ V4: num -0.447 -1.462 0.106 -3.594 -0.989 ...
## $ V5: int 0 0 0 0 0 0 0 0 0 0 ...
5个变量分别表示:小波变换后图像的方差、小波变换后图像的偏斜度、小波变换后图像的峰度、图像的熵和纸币真实性,其中0代表真实,1代表伪造。
> names(bnote) <- c("wavelet_var", "wavelet_Skew", "wavelet_Curt",
+ "entropy", "class")
> bnote$class <- as.factor(bnote$class)
>
> DataExplorer::profile_missing(bnote)
## feature num_missing pct_missing
## 1 wavelet_var 0 0
## 2 wavelet_Skew 0 0
## 3 wavelet_Curt 0 0
## 4 entropy 0 0
## 5 class 0 0
数据集不存在缺失值。
2、拆分训练集和测试集
> ind <- createDataPartition(bnote$class, p = 0.8, list = F)
> dtrain <- bnote[ind, ]
> dtest <- bnote[-ind, ]
3、建模
使用C5.0算法建模。
> set.seed(123)
> fit.c5 <- train(class ~ ., data = dtrain, method = "C5.0")
> fit.c5$finalModel
##
## Call:
## (function (x, y, trials = 1, rules = FALSE, weights = NULL, control = C5.0Control(), costs = NULL, ...) {
## TRUE, bands = 0, winnow = TRUE, noGlobalPruning = FALSE, CF = 0.25, minCases = 2, fuzzyThreshold =
## FALSE, sample = 0, earlyStopping = TRUE, label = "outcome", seed = 404L))
##
## Classification Tree
## Number of samples: 1098
## Number of predictors: 4
##
## Number of boosting iterations: 20
## Average tree size: 8.2
##
## Non-standard options: attempt to group attributes, winnowing
查看准确率:
> mean(predict(fit.c5, newdata = dtrain, type = "raw") == dtrain$class)
## [1] 1
> mean(predict(fit.c5, newdata = dtest, type = "raw") == dtest$class)
## [1] 0.9963504
> confusionMatrix(predict(fit.c5, newdata = dtest, type = "raw"), dtest$class)
## Confusion Matrix and Statistics
##
## Reference
## Prediction 0 1
## 0 152 1
## 1 0 121
##
## Accuracy : 0.9964
## 95% CI : (0.9798, 0.9999)
## No Information Rate : 0.5547
## P-Value [Acc > NIR] : <2e-16
##
## Kappa : 0.9926
##
## Mcnemar's Test P-Value : 1
##
## Sensitivity : 1.0000
## Specificity : 0.9918
## Pos Pred Value : 0.9935
## Neg Pred Value : 1.0000
## Prevalence : 0.5547
## Detection Rate : 0.5547
## Detection Prevalence : 0.5584
## Balanced Accuracy : 0.9959
##
## 'Positive' Class : 0
##
训练集全对,测试集只有三个预测错误,模型接近完美。
网友评论