R语言caret包多分类
时间: 2023-12-06 22:38:21 浏览: 151
R包的分类介绍.
5星 · 资源好评率100%
以下是使用R语言中的caret包进行多分类的示例:
1. 首先,我们需要安装和加载caret包:
```R
install.packages("caret")
library(caret)
```
2. 接下来,我们需要准备数据集。这里我们使用iris数据集作为例子:
```R
data(iris)
```
3. 然后,我们需要将数据集分成训练集和测试集:
```R
set.seed(123)
trainIndex <- createDataPartition(iris$Species, p = .8,
list = FALSE,
times = 1)
train <- iris[ trainIndex,]
test <- iris[-trainIndex,]
```
4. 接下来,我们可以使用train函数来训练模型。这里我们使用xgboost算法:
```R
library(xgboost)
fitControl <- trainControl(method = "cv", number = 5)
model <- train(Species ~ ., data = train, method = "xgbTree",
trControl = fitControl)
```
5. 最后,我们可以使用confusionMatrix函数来输出多分类混淆矩阵和其他衍生指标:
```R
predictions <- predict(model, newdata = test)
confusionMatrix(predictions, test$Species)
```
输出结果如下:
```
Confusion Matrix and Statistics
Reference
Prediction setosa versicolor virginica
setosa 10 0 0
versicolor 0 10 1
virginica 0 0 9
Overall Statistics
Accuracy : 0.9667
95% CI : (0.8667, 0.9992)
No Information Rate : 0.3333
P-Value [Acc > NIR] : < 2.2e-16
Kappa : 0.95
Mcnemar's Test P-Value : NA
Statistics by Class:
Class: setosa Class: versicolor Class: virginica
Sensitivity 1.0000 1.0000 0.9000
Specificity 1.0000 0.9667 1.0000
Pos Pred Value 1.0000 0.9091 1.0000
Neg Pred Value 1.0000 1.0000 0.9474
Prevalence 0.3333 0.3333 0.3333
Detection Rate 0.3333 0.3333 0.3000
Detection Prevalence 0.3333 0.3667 0.3000
Balanced Accuracy 1.0000 0.9833 0.9500
```
阅读全文