2. 可视化(The caret package)

本文介绍如何使用R语言的caret包进行数据可视化,包括散点图矩阵、覆盖密度图、箱线图等,并通过实例展示了如何为连续预测变量创建散点图。

1. 简介(The caret package )

2. 可视化

featurPlot是对lattice包作图的一个包装。例如:下列图表展示了用featurePlot函数画出的连续变量结果的图形。
对于分类的数据集可用iris数据来分析。
str(iris)

## 'data.frame':    150 obs. of  5 variables:
##  $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
##  $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
##  $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
##  $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
##  $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

散点图矩阵

library(AppliedPredictiveModeling)
transparentTheme(trans = 0.4)
library(caret)
featurePlot(x = iris[,1:4],
             y = iris$Species,
             plot = "pairs",
             ## Add a key at the top
             auto.key = list(columns = 3))

这里写图片描述
散点图矩阵加椭圆

featurePlot(x = iris[, 1:4], 
            y = iris$Species, 
            plot = "ellipse",
            ## Add a key at the top
            auto.key = list(columns = 3))

这里写图片描述
覆盖密度图

transparentTheme(trans = .9)
featurePlot(x = iris[, 1:4], 
            y = iris$Species,
            plot = "density", 
            ## Pass in options to xyplot() to 
            ## make it prettier
            scales = list(x = list(relation="free"), 
                          y = list(relation="free")), 
            adjust = 1.5, 
            pch = "|", 
            layout = c(4, 1), 
            auto.key = list(columns = 3))

这里写图片描述
箱线图

featurePlot(x = iris[, 1:4], 
            y = iris$Species, 
            plot = "box", 
            ## Pass in options to bwplot() 
            scales = list(y = list(relation="free"),
                          x = list(rot = 90)),  
            layout = c(4,1 ), 
            auto.key = list(columns = 2))

这里写图片描述
散点图
用Boston Housing数据进行回归:

library(mlbench)
data(BostonHousing)
regVar <- c("age", "lstat", "tax")
str(BostonHousing[, regVar])
## 'data.frame':    506 obs. of  3 variables:
##  $ age  : num  65.2 78.9 61.1 45.8 54.2 58.7 66.6 96.1 100 85.9 ...
##  $ lstat: num  4.98 9.14 4.03 2.94 5.33 ...
##  $ tax  : num  296 242 242 222 222 222 311 311 311 311 ...

当预测子是连续的时候,featurePlot可对每个预测子及结果变量创建散点图。例如:

theme1 <- trellis.par.get()
theme1$plot.symbol$col = rgb(.2, .2, .2, .4)
theme1$plot.symbol$pch = 16
theme1$plot.line$col = rgb(1, 0, 0, .7)
theme1$plot.line$lwd <- 2
trellis.par.set(theme1)
featurePlot(x = BostonHousing[, regVar], 
            y = BostonHousing$medv, 
            plot = "scatter", 
            layout = c(3, 1))

这里写图片描述
注意到x坐标刻度的不同,函数自动的使用scale = list(y = list(relation = "free")),所以你不用加上它。我们也可以向lattice函数xyplot中传递其他选项。例如,我们可以通过传递新选项加入散点图平滑项:

featurePlot(x = BostonHousing[, regVar], 
            y = BostonHousing$medv, 
            plot = "scatter",
            type = c("p", "smooth"),
            span = .5,
            layout = c(3, 1))

这里写图片描述
degreespan选项控制平滑项的平滑度。

# 加载所需包 > library(randomForest) randomForest 4.7-1.2 Type rfNews() to see new features/changes/bug fixes. > library(caret) 载入需要的程序包:ggplot2 载入程序包:‘ggplot2The following object is masked from ‘package:randomForest’: margin 载入需要的程序包:lattice > > # 加载鸢尾花数据集 > data(iris) > > # 设置随机种子确保可复现性 > set.seed(42) > > # 划分训练集和测试集 (70%训练, 30%测试) > train_index <- createDataPartition(iris$Species, p = 0.7, list = FALSE) > train_data <- iris[train_index, ] > test_data <- iris[-train_index, ] > > # 自助法参数设置 > n_iterations <- 300 # 迭代次数 > bootstrap_accuracies <- numeric(n_iterations) # 存储每次迭代的准确率 > > # 自助法迭代过程 > for (i in 1:n_iterations) { + # 1. 有放回抽样生成自助样本 + boot_indices <- sample(nrow(train_data), replace = TRUE) + boot_sample <- train_data[boot_indices, ] + + # 2. 训练随机森林模型 + rf_model <- randomForest( + Species ~ ., + data = boot_sample, + ntree = 100, + importance = TRUE + ) + + # 3. 评估模型性能 + predictions <- predict(rf_model, test_data) + conf_matrix <- confusionMatrix(predictions, test_data$Species) + bootstrap_accuracies[i] <- conf_matrix$overall["Accuracy"] + + # 每50次迭代显示进度 + if (i %% 50 == 0) { + cat("已完成", i, "/", n_iterations, "次迭代,当前准确率:", + round(bootstrap_accuracies[i], 4), "\n") + } + } 已完成 50 / 300 次迭代,当前准确率: 0.8889 已完成 100 / 300 次迭代,当前准确率: 0.9333 已完成 150 / 300 次迭代,当前准确率: 0.9556 已完成 200 / 300 次迭代,当前准确率: 0.9556 已完成 250 / 300 次迭代,当前准确率: 0.9556 已完成 300 / 300 次迭代,当前准确率: 0.9111 > > # 计算最终统计量 > mean_accuracy <- mean(bootstrap_accuracies) > std_accuracy <- sd(bootstrap_accuracies) > confidence_interval <- c( + mean_accuracy - 1.96 * std_accuracy, + mean_accuracy + 1.96 * std_accuracy + ) > > # 输出结果 > cat("\n===== 自助法结果分析 =====\n") ===== 自助法结果分析 ===== > cat("平均准确率:", round(mean_accuracy, 4), "\n") 平均准确率: 0.9313 > cat("准确率标准差:", round(std_accuracy, 4), "\n") 准确率标准差: 0.0234 > cat("95% 置信区间: (", round(confidence_interval[1], 4), ", ", + round(confidence_interval[2], 4), ")\n", sep = "") 95% 置信区间: (0.8854, 0.9771) > cat("最小准确率:", round(min(bootstrap_accuracies), 4), "\n") 最小准确率: 0.8667 > cat("最大准确率:", round(max(bootstrap_accuracies), 4), "\n") 最大准确率: 0.9556 > > # 可视化准确率分布 > hist(bootstrap_accuracies, + main = "300次自助法迭代的准确率分布", + xlab = "准确率", + ylab = "频率", + col = "lightblue", + border = "black") > abline(v = mean_accuracy, col = "red", lwd = 2) > legend("topright", + legend = c(paste("均值 =", round(mean_accuracy, 4))), + col = "red", + lty = 1, + lwd = 2) > 帮我准确,严谨,完整的输出代码
最新发布
08-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值