gpt4 book ai didi

Scikit-Learn:在交叉验证期间避免数据泄漏

转载 作者:行者123 更新时间:2023-12-04 04:33:09 25 4
gpt4 key购买 nike

我刚刚阅读了 k 折交叉验证,并意识到我在使用当前的预处理设置时无意中泄露了数据。

通常,我有一个训练和测试数据集。我对整个训练数据集进行了大量数据插补和单热编码,然后运行 ​​k 折交叉验证。

泄漏的原因是,如果我进行 5 折交叉验证,我将在 80% 的训练数据上进行训练,并在其余 20% 的训练数据上进行测试。

我真的应该根据 80% 的火车来估算 20%(而我之前使用的是 100% 的数据)。

1)这是考虑交叉验证的正确方法吗?

2) 我一直在看 Pipeline类(class) sklearn.pipeline它似乎对进行一堆转换然后最终将模型拟合到结果数据中很有用。但是,我正在做很多事情,例如“用平均值估算 float64 列中的缺失数据”、“用模式估算所有其他数据”等。

这种插补没有明显的更改器(mutator)。我将如何将此步骤添加到 Pipeline ?我会创建我自己的 BaseEstimator 子类吗? ?

这里的任何指导都会很棒!

最佳答案

1) 是的,您应该使用 80% 的训练数据来估算 20% 的测试数据。

2) 我写了 a blog post这回答了你的第二个问题,但我会在这里包括核心部分。

sklearn.pipeline ,您可以将单独的预处理规则应用于不同的特征类型(例如,数字、分类)。在下面的示例代码中,我在缩放数字特征之前估算了它们的中位数。分类和 bool 特征用模式进行估算——分类特征是单热编码的。

您可以在管道的末尾包含一个用于回归、分类等的估算器。

import numpy as np
from sklearn.pipeline import make_pipeline, FeatureUnion
from sklearn.preprocessing import OneHotEncoder, Imputer, StandardScaler

preprocess_pipeline = make_pipeline(
FeatureUnion(transformer_list=[
("numeric_features", make_pipeline(
TypeSelector(np.number),
Imputer(strategy="median"),
StandardScaler()
)),
("categorical_features", make_pipeline(
TypeSelector("category"),
Imputer(strategy="most_frequent"),
OneHotEncoder()
)),
("boolean_features", make_pipeline(
TypeSelector("bool"),
Imputer(strategy="most_frequent")
))
])
)
TypeSelector管道的一部分假定对象 X是 Pandas DataFrame .使用 TypeSelector.transform 选择具有给定数据类型的列子集.
from sklearn.base import BaseEstimator, TransformerMixin
import pandas as pd

class TypeSelector(BaseEstimator, TransformerMixin):
def __init__(self, dtype):
self.dtype = dtype

def fit(self, X, y=None):
return self

def transform(self, X):
assert isinstance(X, pd.DataFrame)
return X.select_dtypes(include=[self.dtype])

关于Scikit-Learn:在交叉验证期间避免数据泄漏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48482440/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com