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

人工智能 深度学习
本文讨论了评估模型性能时的数据泄漏问题以及避免数据泄漏的方法。

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

 

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

 

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

 

  1. import numpy as np  
  2. import pandas as pd  
  3. from sklearn.datasets import load_boston  
  4. from sklearn.preprocessing import StandardScaler  
  5. from sklearn.pipeline import Pipeline  
  6. from sklearn.impute import SimpleImputer  
  7. from sklearn.neighbors import KNeighborsRegressor  
  8. from sklearn.model_selection import cross_validate, train_test_split  
  9. from sklearn.metrics import mean_squared_error  
  10.  
  11. #Importing the dataset  
  12. data = pd.DataFrame(load_boston()['data'],columns=load_boston()['feature_names'])  
  13. data['target'] = load_boston()['target']  
  14.  
  15.  
  16. #Split the input and target features  
  17. X = data.iloc[:,:-1].copy()  
  18. y = data.iloc[:,-1].copy()  
  19.  
  20.  
  21. # Adding 100 random missing values  
  22. np.random.seed(11)  
  23. rand_cols = np.random.randint(0,X.shape[1],100)  
  24. rand_rows = np.random.randint(0,X.shape[0],100)  
  25. for i,j in zip(rand_rows,rand_cols):  
  26. X.iloc[i,j] = np.nan  
  27.  
  28. #Splitting the data into training and test sets  
  29. X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=11)  
  30.  
  31. #Initislizing KNN Regressor  
  32. knn = KNeighborsRegressor()  
  33.  
  34. #Initializing mode imputer  
  35. imp = SimpleImputer(strategy='most_frequent')  
  36.  
  37. #Initializing StandardScaler  
  38. standard_scaler = StandardScaler()  
  39.  
  40. #Imputing and scaling X_train  
  41. X_train_impute = imp.fit_transform(X_train).copy()  
  42. X_train_scaled = standard_scaler.fit_transform(X_train_impute).copy()  
  43.  
  44. #Running 5-fold cross-validation  
  45. cv = cross_validate(estimator=knn,X=X_train_scaled,y=y_train,cv=5,scoring="neg_root_mean_squared_error",return_train_score=True)  
  46.  
  47. #Calculating mean of the training scores of cross-validation  
  48. print(f'Training RMSE (with data leakage): {-1 * np.mean(cv["train_score"])}')  
  49.  
  50. #Calculating mean of the validation scores of cross-validation  
  51. print(f'validation RMSE (with data leakage): {-1 * np.mean(cv["test_score"])}')  
  52.  
  53. #fitting the model to the training data  
  54. lr.fit(X_train_scaled,y_train)  
  55.  
  56. #preprocessing the test data  
  57. X_test_impute = imp.transform(X_test).copy()  
  58. X_test_scaled = standard_scaler.transform(X_test_impute).copy()  
  59.  
  60. #Predictions and model evaluation on unseen data  
  61. pred = lr.predict(X_test_scaled)  
  62. print(f'RMSE on unseen data: {np.sqrt(mean_squared_error(y_test,pred))}'

 

 

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

 

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

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

 

  1. #Preprocessing and regressor pipeline  
  2. pipeline = Pipeline(steps=[['imputer',imp],['scaler',standard_scaler],['regressor',knn]])  
  3.  
  4. #Running 5-fold cross-validation using pipeline as estimator  
  5. cv = cross_validate(estimator=pipeline,X=X_train,y=y_train,cv=5,scoring="neg_root_mean_squared_error",return_train_score=True)  
  6.  
  7. #Calculating mean of the training scores of cross-validation  
  8. print(f'Training RMSE (without data leakage): {-1 * np.mean(cv["train_score"])}')  
  9.  
  10. #Calculating mean of the validation scores of cross-validation  
  11. print(f'validation RMSE (without data leakage): {-1 * np.mean(cv["test_score"])}')  
  12.  
  13. #fitting the pipeline to the training data  
  14. pipeline.fit(X_train,y_train)  
  15.  
  16. #Predictions and model evaluation on unseen data  
  17. pred = pipeline.predict(X_test)  
  18. print(f'RMSE on unseen data: {np.sqrt(mean_squared_error(y_test,pred))}'

 

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

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

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

责任编辑:华轩 来源: 今日头条
相关推荐

2020-09-22 14:59:52

机器学习人工智能计算机

2022-10-08 11:11:25

机器学习人工智能

2020-09-25 09:59:52

人工智能

2022-08-10 15:56:40

机器学习算法深度学习

2021-12-09 19:13:10

远程办公时数据泄露网络攻击

2010-05-17 22:53:19

2010-05-07 15:22:41

数据安全数据泄漏DLP

2020-06-24 07:53:03

机器学习技术人工智能

2010-09-03 16:44:22

2020-07-01 08:48:01

Python机器学习工具

2023-12-18 10:45:23

内存泄漏计算机服务器

2010-09-06 10:26:30

2017-10-13 15:59:24

iPhone机器学习iOS

2017-07-07 14:41:13

机器学习神经网络JavaScript

2021-11-02 09:40:50

TensorFlow机器学习人工智能

2022-06-02 15:42:05

Python机器学习

2023-07-21 12:48:37

2022-05-10 08:17:03

goroutine泄漏

2017-03-24 15:58:46

互联网

2017-07-13 10:12:58

机器学习
点赞
收藏

51CTO技术栈公众号