🔧 tool

相关软件(R代码)

```r # 随机森林 # install.packages("randomForest") library(randomForest) library(caret) # 使用乳腺癌数据( Wisconsin Breast Cancer Dataset) data(iris) # 暂时用iris数据示例 # 划分训练集和测试集 set.seed(123) train_idx <- createD...

📖 定义

# 随机森林
# install.packages("randomForest")
library(randomForest)
library(caret)
# 使用乳腺癌数据( Wisconsin Breast Cancer Dataset)
data(iris)  # 暂时用iris数据示例
# 划分训练集和测试集
set.seed(123)
train_idx <- createDataPartition(iris$Species, p = 0.8, list = FALSE)
train_data <- iris[train_idx, ]
test_data <- iris[-train_idx, ]
# 随机森林
rf_model <- randomForest(Species ~ ., data = train_data, ntree = 500, importance = TRUE)
print(rf_model)
# 预测
predictions <- predict(rf_model, test_data)
confusionMatrix(predictions, test_data$Species)
# 变量重要性
importance(rf_model)
varImpPlot(rf_model)
# SVM
# install.packages("e1071")
library(e1071)
svm_model <- svm(Species ~ ., data = train_data, kernel = "radial", cost = 1, gamma = 0.1)
svm_pred <- predict(svm_model, test_data)
confusionMatrix(svm_pred, test_data$Species)
# 交叉验证
ctrl <- trainControl(method = "cv", number = 5)
model_cv <- train(Species ~ ., data = train_data, method = "rf", trControl = ctrl)
print(model_cv)
# ROC曲线(二分类示例)
# 使用其他二分类数据
data(ROCR.simple, package = "ROCR")
library(ROCR)
pred <- prediction(ROCR.simple$predictions, ROCR.simple$labels)
perf <- performance(pred, "tpr", "fpr")
plot(perf, colorize = TRUE, main = "ROC曲线")
abline(a = 0, b = 1, lty = 2)
# AUC
auc <- performance(pred, "auc")
auc@y.values[[1]]

2.5.2 无监督学习