如何在评估机器学习模型时防止数据泄漏

本文讨论了评估模型性能时的数据泄漏问题以及避免数据泄漏的方法。

在模型评估过程中,当训练集的数据进入验证/测试集时,就会发生数据泄漏。这将导致模型对验证/测试集的性能评估存在偏差。让我们用一个使用Scikit-Learn的“波士顿房价”数据集的例子来理解它。数据集没有缺失值,因此随机引入100个缺失值,以便更好地演示数据泄漏。

import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.neighbors import KNeighborsRegressor
from sklearn.model_selection import cross_validate, train_test_split
from sklearn.metrics import mean_squared_error

#Importing the dataset
data = pd.DataFrame(load_boston()['data'],columns=load_boston()['feature_names'])
data['target'] = load_boston()['target']


#Split the input and target features
X = data.iloc[:,:-1].copy()
y = data.iloc[:,-1].copy()


# Adding 100 random missing values
np.random.seed(11)
rand_cols = np.random.randint(0,X.shape[1],100)
rand_rows = np.random.randint(0,X.shape[0],100)
for i,j in zip(rand_rows,rand_cols):
    X.iloc[i,j] = np.nan
    
#Splitting the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=11)

#Initislizing KNN Regressor
knn = KNeighborsRegressor()

#Initializing mode imputer
imp = SimpleImputer(strategy='most_frequent')

#Initializing StandardScaler
standard_scaler = StandardScaler()

#Imputing and scaling X_train
X_train_impute = imp.fit_transform(X_train).copy()
X_train_scaled = standard_scaler.fit_transform(X_train_impute).copy()

#Running 5-fold cross-validation
cv = cross_validate(estimator=knn,X=X_train_scaled,y=y_train,cv=5,scoring="neg_root_mean_squared_error",return_train_score=True)

#Calculating mean of the training scores of cross-validation
print(f'Training RMSE (with data leakage): {-1 * np.mean(cv["train_score"])}')

#Calculating mean of the validation scores of cross-validation
print(f'validation RMSE (with data leakage): {-1 * np.mean(cv["test_score"])}')

#fitting the model to the training data
lr.fit(X_train_scaled,y_train)

#preprocessing the test data
X_test_impute = imp.transform(X_test).copy()
X_test_scaled = standard_scaler.transform(X_test_impute).copy()

#Predictions and model evaluation on unseen data
pred = lr.predict(X_test_scaled)
print(f'RMSE on unseen data: {np.sqrt(mean_squared_error(y_test,pred))}')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62

在上面的代码中,‘X_train’是训练集(k-fold交叉验证),‘X_test’用于对看不见的数据进行模型评估。上面的代码是一个带有数据泄漏的模型评估示例,其中,用于估算缺失值的模式(strategy= ’ most_frequent ‘)在’ X_train ‘上计算。类似地,用于缩放数据的均值和标准偏差也使用’ X_train ‘计算。’ X_train的缺失值将被输入,’ X_train '在k-fold交叉验证之前进行缩放。

在k-fold交叉验证中,’ X_train ‘被分割成’ k ‘折叠。在每次k-fold交叉验证迭代中,其中一个折用于验证(我们称其为验证部分),其余的折用于训练(我们称其为训练部分)。每次迭代中的训练和验证部分都有已经使用’ X_train ‘计算的模式输入的缺失值。类似地,它们已经使用在’ X_train ‘上计算的平均值和标准偏差进行了缩放。这种估算和缩放操作会导致来自’ X_train '的信息泄露到k-fold交叉验证的训练和验证部分。这种信息泄漏可能导致模型在验证部分上的性能估计有偏差。下面的代码展示了一种通过使用管道来避免它的方法。

#Preprocessing and regressor pipeline
pipeline = Pipeline(steps=[['imputer',imp],['scaler',standard_scaler],['regressor',knn]])

#Running 5-fold cross-validation using pipeline as estimator
cv = cross_validate(estimator=pipeline,X=X_train,y=y_train,cv=5,scoring="neg_root_mean_squared_error",return_train_score=True)

#Calculating mean of the training scores of cross-validation
print(f'Training RMSE (without data leakage): {-1 * np.mean(cv["train_score"])}')

#Calculating mean of the validation scores of cross-validation
print(f'validation RMSE (without data leakage): {-1 * np.mean(cv["test_score"])}')

#fitting the pipeline to the training data
pipeline.fit(X_train,y_train)
      
#Predictions and model evaluation on unseen data
pred = pipeline.predict(X_test)
print(f'RMSE on unseen data: {np.sqrt(mean_squared_error(y_test,pred))}')
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

在上面的代码中,我们已经在管道中包含了输入器、标量和回归器。在本例中,’ X_train '被分割为5个折,在每次迭代中,管道使用训练部分计算用于输入训练和验证部分中缺失值的模式。同样,用于衡量训练和验证部分的平均值和标准偏差也在训练部分上计算。这一过程消除了数据泄漏,因为在每次k-fold交叉验证迭代中,都在训练部分计算归责模式和缩放的均值和标准偏差。在每次k-fold交叉验证迭代中,这些值用于计算和扩展训练和验证部分。

我们可以看到在有数据泄漏和没有数据泄漏的情况下计算的训练和验证rmse的差异。由于数据集很小,我们只能看到它们之间的微小差异。在大数据集的情况下,这个差异可能会很大。对于看不见的数据,验证RMSE(带有数据泄漏)接近RMSE只是偶然的。

因此,使用管道进行k-fold交叉验证可以防止数据泄漏,并更好地评估模型在不可见数据上的性能。

作者:KSV Muralidhar

deephub翻译组

登录后您可以享受以下权益:

×
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值

举报

选择你想要举报的内容(必选)
  • 内容涉黄
  • 政治相关
  • 内容抄袭
  • 涉嫌广告
  • 内容侵权
  • 侮辱谩骂
  • 样式问题
  • 其他
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回顶部