数据科学中,数据集的拆分是建模的重要一部分。一个常见的问题是:该怎样决定数据拆分的比例?很多学生只会从网上照抄代码,网上的代码有时候三七分,有时候二八分,当然会让初学者好奇这是为什么?今天我们将详细解答这个问题,并以支持向量机(SVM)算法为例,展示数据集拆分、建模、评价和可视化的完整过程。
数据集拆分的重要性
为什么选择70:30?
训练效果:大多数情况下,70%的数据用于训练模型足以捕捉数据的模式。 评估效果:30%的数据用于测试模型,可以有效评估模型的泛化能力。 数据量:如果数据量较大,70:30的比例可以确保训练和测试集都有足够的数据。
支持向量机(SVM)分类模型示例
步骤一:加载必要的包和数据
# 加载必要的包
library(caret)
library(e1071)
library(ggplot2)
# 设置随机种子以确保可重复性
set.seed(123)
# 加载数据集
data(iris)
X <- iris[, 1:4]
Y <- iris[, 5]
步骤二:数据集拆分为训练集和测试集
# 数据集拆分为训练集和测试集(70:30)
trainIndex <- createDataPartition(Y, p = 0.7, list = FALSE)
trainData <- X[trainIndex, ]
testData <- X[-trainIndex, ]
trainLabel <- Y[trainIndex]
testLabel <- Y[-trainIndex]
步骤三:构建支持向量机模型
# 构建支持向量机模型
svm_model <- svm(trainData, as.factor(trainLabel), kernel = "linear")
步骤四:预测测试集并评价模型
# 预测测试集
test_predictions <- predict(svm_model, newdata = testData)
# 模型评价
confusion_matrix <- table(Predicted = test_predictions, Actual = testLabel)
accuracy <- sum(diag(confusion_matrix)) / sum(confusion_matrix)
cat("Confusion Matrix:\n")
## Confusion Matrix:
print(confusion_matrix)
## Actual
## Predicted setosa versicolor virginica
## setosa 15 0 0
## versicolor 0 15 1
## virginica 0 0 14
cat("\nAccuracy:", accuracy, "\n")
##
## Accuracy: 0.9777778
步骤五:可视化预测结果
# 绘制预测结果的散点图
testData_with_labels <- data.frame(testData, Predicted = test_predictions, Actual = testLabel)
ggplot(testData_with_labels, aes(x = Petal.Length, y = Petal.Width, color = Actual, shape = Predicted)) +
geom_point(size = 3) +
theme_minimal() +
ggtitle("SVM Classification: Test Set Predictions vs Actual Labels") +
theme(
plot.title = element_text(hjust = 0.5, size = 16, face = "bold"),
axis.title = element_text(size = 14, face = "bold"),
legend.title = element_text(size = 12, face = "bold"),
legend.position = "right"
) +
labs(
x = "Petal Length",
y = "Petal Width",
color = "Actual Species",
shape = "Predicted Species"
)