首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用K-折叠交叉验证将数据标准化

用K-折叠交叉验证将数据标准化
EN

Stack Overflow用户
提问于 2019-11-19 17:18:17
回答 2查看 4.5K关注 0票数 1

我使用的是StratifiedKFold,所以我的代码如下所示

代码语言:javascript
复制
def train_model(X,y,X_test,folds,model):
    scores=[]
    for fold_n, (train_index, valid_index) in enumerate(folds.split(X, y)):
        X_train,X_valid = X[train_index],X[valid_index]
        y_train,y_valid = y[train_index],y[valid_index]        
        model.fit(X_train,y_train)
        y_pred_valid = model.predict(X_valid).reshape(-1,)
        scores.append(roc_auc_score(y_valid, y_pred_valid))
    print('CV mean score: {0:.4f}, std: {1:.4f}.'.format(np.mean(scores), np.std(scores)))
folds = StratifiedKFold(10,shuffle=True,random_state=0)
lr = LogisticRegression(class_weight='balanced',penalty='l1',C=0.1,solver='liblinear')
train_model(X_train,y_train,X_test,repeted_folds,lr)

现在,在训练模型之前,我想对数据进行标准化,那么哪种方法是正确的?

1)

代码语言:javascript
复制
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)

在调用train_model函数之前执行此操作

2)

像这样做标准化内部功能

代码语言:javascript
复制
def train_model(X,y,X_test,folds,model):
    scores=[]
    for fold_n, (train_index, valid_index) in enumerate(folds.split(X, y)):
        X_train,X_valid = X[train_index],X[valid_index]
        y_train,y_valid = y[train_index],y[valid_index]
        scaler = StandardScaler()
        X_train = scaler.fit_transform(X_train)
        X_vaid = scaler.transform(X_valid)
        X_test = scaler.transform(X_test)
        model.fit(X_train,y_train)
        y_pred_valid = model.predict(X_valid).reshape(-1,)

        scores.append(roc_auc_score(y_valid, y_pred_valid))

    print('CV mean score: {0:.4f}, std: {1:.4f}.'.format(np.mean(scores), np.std(scores)))

根据我在第二个选项中的知识,我没有泄漏data.so,如果我不使用管道,那么哪种方式是正确的?如果我想使用交叉验证,那么如何使用管道呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-11-19 17:34:33

实际上,第二个选项更好,因为定标器没有看到X_valid的值来缩放X_train

现在,如果要使用管道,则可以:

代码语言:javascript
复制
from sklearn.pipeline import make_pipeline

def train_model(X,y,X_test,folds,model):
    pipeline = make_pipeline(StandardScaler(), model)
    ...

然后使用pipeline而不是model。在每次fitpredict调用时,它都会自动标准化手头的数据。

请注意,您还可以使用得分函数,使用参数scoring='roc_auc'

票数 1
EN

Stack Overflow用户

发布于 2019-11-19 17:27:59

何时标准化您的数据可能是一个更适合交叉验证的问题。

国际海事组织,如果你的数据很大,那么它可能并不重要太多(如果你使用k-折叠,这可能不是这样的情况),但既然你可以,最好是在交叉验证(k-折叠),或选项2。

此外,有关交叉验证中过度拟合的更多信息,请参见

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58939568

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档