R语言 验证集方法
验证集方法 是机器学习中的一种交叉验证技术。交叉验证技术通常被用来判断机器学习模型的性能和准确性。在验证集方法中,用于建立模型的数据集被随机分为两部分,即训练集和验证集(或测试集)。模型在训练数据集上进行训练,并通过预测训练期间不存在的数据点(即验证集)的目标变量来计算其准确性。这个分割数据、训练模型、测试模型的整个过程是一项复杂的任务。但R语言由许多库和内置函数组成,可以非常容易和有效地执行所有任务。
验证集方法中涉及的步骤
- 将数据集按一定比例随机分割(一般是70-30或80-20的比例)。
- 在训练数据集上训练模型
- 将得到的模型应用于验证集。
- 通过使用模型性能指标的预测误差来计算模型的准确性。
本文讨论了 一步步实现验证集方法 的方法,作为 分类 和 回归 机器学习模型的交叉验证技术。
对于分类机器学习模型
这种类型的机器学习模型用于目标变量是一个分类变量,如正、负,或糖尿病、非糖尿病等。该模型预测因变量的类别标签。这里,Logistic回归算法将被用于建立分类模型。
第1步:加载数据集和其他所需软件包
在做任何探索性或操作性任务之前,必须包括所有需要的库和包,以使用各种内置的功能和数据集,这将使整个过程更容易进行。
# loading required packages
# package to perform data manipulation
# and visualization
library(tidyverse)
# package to compute
# cross - validation methods
library(caret)
# package Used to split the data
# used during classification into
# train and test subsets
library(caTools)
# loading package to
# import desired dataset
library(ISLR)
第2步:探索数据集
了解数据集的结构和维度是非常必要的,因为这将有助于建立一个正确的模型。此外,由于这是一个分类模型,人们必须了解目标变量中存在的不同类别。
# assigning the complete dataset
# Smarket to a variable
dataset <- Smarket[complete.cases(Smarket), ]
# display the dataset with details
# like column name and its data type
# along with values in each row
glimpse(dataset)
# checking values present
# in the Direction column
# of the dataset
table(dataset$Direction)
输出
Rows: 1,250
Columns: 9
Year <dbl> 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, 2001, ... Lag1 <dbl> 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0.546, -1...
Lag2 <dbl> -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0... Lag3 <dbl> -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -...
Lag4 <dbl> -1.055, -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, ... Lag5 <dbl> 5.010, -1.055, -2.624, -0.192, 0.381, 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, ...
Volume <dbl> 1.19130, 1.29650, 1.41120, 1.27600, 1.20570, 1.34910, 1.44500, 1.40780, 1.16400, 1.23260, 1.30900, 1.25800, 1.09800, 1.05310, ... Today <dbl> 0.959, 1.032, -0.623, 0.614, 0.213, 1.392, -0.403, 0.027, 1.303, 0.287, -0.498, -0.189, 0.680, 0.701, -0.562, 0.546, -1.747, 0...
Direction <fct> Up, Up, Down, Up, Up, Up, Down, Up, Up, Up, Down, Down, Up, Up, Down, Up, Down, Up, Down, Down, Down, Down, Up, Down, Down, Up...
> table(datasetDirection)
Down Up
602 648
根据上述信息,导入的数据集有250行和9列。列的数据类型为 < dbl> **表示双精度浮点数(dbl来自double)。在分类模型中,目标变量必须是 **因子 数据类型。由于 “方向 “列的数据类型已经是 **< fct>,所以 **不需要再做任何改变。
此外, 响应变量 或目标变量是一个二元分类变量(因为该列中的值只有Down和Up),两个类标签的比例大约是1:1,这意味着它们是平衡的。如果出现类别不平衡的情况,如类别标签的比例为1:2,我们必须确保两个类别的比例大致相等。为此,有许多技术,如。
- 下抽样
- 上抽样
- 使用SMOTE和ROSE的混合取样
第3步:建立模型和生成验证集
这一步包括随机分割数据集,开发训练和验证集,以及训练模型。以下是实现情况。
# setting seed to generate a
# reproducible random sampling
set.seed(100)
# dividing the complete dataset
# into 2 parts having ratio of
# 70% and 30%
spl = sample.split(dataset$Direction, SplitRatio = 0.7)
# selecting that part of dataset
# which belongs to the 70% of the
# dataset divided in previous step
train = subset(dataset, spl == TRUE)
# selecting that part of dataset
# which belongs to the 30% of the
# dataset divided in previous step
test = subset(dataset, spl == FALSE)
# checking number of rows and column
# in training and testing dataset
print(dim(train))
print(dim(test))
# Building the model
# training the model by assigning Direction column
# as target variable and rest other columns
# as independent variables
model_glm = glm(Direction ~ . , family = "binomial",
data = train, maxit = 100)
输出
> print(dim(train))
[1] 875 9
> print(dim(test))
[1] 375 9
第4步:预测目标变量
随着模型训练的完成,现在是对未见过的数据进行预测的时候了。在这里,目标变量只有两个可能的值,所以在 predict() 函数中,最好使用 type = response ,这样模型就可以预测目标分类变量的概率分数为0或1。
还有一个可选的步骤是将响应变量转化为1和0的因子变量,这样,如果一个数据点的概率得分高于某个阈值,它将被视为1,如果低于该阈值,它将被视为0 。
# predictions on the validation set
predictTest = predict(model_glm, newdata = test,
type = "response")
# assigning the probability cutoff as 0.5
predicted_classes <- as.factor(ifelse(predictTest >= 0.5,
"Up", "Down"))
第5步:评估模型的准确性
判断一个分类机器学习模型准确性的最好方法是通过混淆矩阵。这个矩阵给了我们一个数值,表明有多少数据点通过参考测试数据集中的目标变量的实际值而被预测为正确或不正确。除了混淆矩阵,模型的其他统计细节,如准确率和卡帕,可以使用下面的代码计算。
# generating confusion matrix and
# other details from the
# prediction made by the model
print(confusionMatrix(predicted_classes, test$Direction))
输出
Confusion Matrix and Statistics
Reference
Prediction Down Up
Down 177 5
Up 4 189
Accuracy : 0.976
95% CI : (0.9549, 0.989)
No Information Rate : 0.5173
P-Value [Acc > NIR] : <2e-16
Kappa : 0.952
Mcnemar's Test P-Value : 1
Sensitivity : 0.9779
Specificity : 0.9742
Pos Pred Value : 0.9725
Neg Pred Value : 0.9793
Prevalence : 0.4827
Detection Rate : 0.4720
Detection Prevalence : 0.4853
Balanced Accuracy : 0.9761
'Positive' Class : Down
对于回归机器学习模型
回归模型用于预测性质连续的数量,如房子的价格、产品的销售等。一般来说,在回归问题中,目标变量是一个实数,如整数或浮点值。这类模型的准确性是通过对不同数据点的输出预测的误差平均值来计算的。以下是在线性回归模型中实现验证集方法的步骤。
第1步:加载数据集和所需软件包
R语言包含各种数据集。这里我们使用 树木 数据集,它是线性回归模型的一个内置数据集。下面是导入所需数据集和包的代码,以执行各种操作来建立模型。
# loading required packages
# package to perform data manipulation
# and visualization
library(tidyverse)
# package to compute
# cross - validation methods
library(caret)
# access the data from R’s datasets package
data(trees)
# look at the first several rows of the data
head(trees)
输出
Girth Height Volume
1 8.3 70 10.3
2 8.6 65 10.3
3 8.8 63 10.2
4 10.5 72 16.4
5 10.7 81 18.8
6 10.8 83 19.7
因此,在这个数据集中,总共有3列,其中 体积 是目标变量。由于该变量是连续性质的,因此可以使用线性回归算法来预测结果。
第2步:建立模型并生成验证集
在这一步,模型被随机分割成80-20的比例。80%的数据点将被用于训练模型,而20%作为验证集,这将给我们提供模型的准确性。下面是相同的代码。
# reproducible random sampling
set.seed(123)
# creating training data as 80% of the dataset
random_sample <- createDataPartition(trees $ Volume,
p = 0.8, list = FALSE)
# generating training dataset
# from the random_sample
training_dataset <- trees[random_sample, ]
# generating testing dataset
# from rows which are not
# included in random_sample
testing_dataset <- trees[-random_sample, ]
# Building the model
# training the model by assigning sales column
# as target variable and rest other columns
# as independent variables
model <- lm(Volume ~., data = training_dataset)
第3步:预测目标变量
在建立和训练模型后,将对属于验证集的数据点的目标变量进行预测。
# predicting the target variable
predictions <- predict(model, testing_dataset)
第4步:评估模型的准确性
用于评估线性回归模型性能的统计指标有 平均平方误差(RMSE)、平均平方误差(MAE) 、 和 **R 2 误差。 **在所有R2 误差中,指标做出了最准确的判断,其值必须高,以获得更好的模型。下面是计算模型预测误差的代码。
# computing model performance metrics
data.frame(R2 = R2(predictions, testing_dataset Volume),
RMSE = RMSE(predictions, testing_dataset Volume),
MAE = MAE(predictions, testing_dataset $ Volume))
输出
R2 RMSE MAE
1 0.9564487 5.274129 4.73567
验证集方法的优点
- 评价一个模型的最基本和最简单的技术之一。
- 没有复杂的实现步骤。
验证集方法的缺点
- 模型所做的预测高度依赖于用于训练和验证的观察子集。
- 只使用一个数据子集进行训练会使模型出现偏差。