【问题标题】:Does the pipeline object in sklearn transform the test data when using the .predict() method?使用 .predict() 方法时,sklearn 中的管道对象是否会转换测试数据?
【发布时间】:2021-09-17 21:29:14
【问题描述】:

当我使用管道对象时,

  1. 当我使用.fit() 方法时,管道对象是否适合和转换训练数据?还是应该使用.fit_transform() 方法?两者有什么区别?

  2. 当我对测试数据使用.predict()方法时,管道对象是否转换测试数据然后才预测它?也就是说,我应该使用@987654324转换测试数据吗? @方法之前我使用.predict()方法?

这是我的代码:

import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.decomposition import PCA
from sklearn.tree import DecisionTreeClassifier



#creating some data
X, y = np.ones((50, 1)), np.hstack(([0] * 45, [1] * 5))

#creating the pipeline
steps = [('scaler', StandardScaler()), ('SelectKBest', SelectKBest(f_classif, k=3)), ('pca', PCA(n_components=2)), ('DT', DecisionTreeClassifier(random_state=0))]
model = Pipeline(steps=steps)

#splitting the data
X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.33, random_state=42)

model.fit(X_train,y_train)

model.predict(X_test)

【问题讨论】:

    标签: python machine-learning scikit-learn


    【解决方案1】:

    Pipeline 对象正在公开其最后一步的方法。由于您的最后一步是 DecisionTreeClassifier(一个 Estimator),因此管道不会有 fit_transform() 而是估计函数,例如 fit()predict()score() 等。

    当使用fit() 时,管道将在所有转换器上调用fit_transform(),最后在估算器上调用fit()

    当使用predict() 时,管道将transform() 所有数据,然后在估算器上调用predict()

    如图所示:(图片来自 Raschka, Sebastian。Python 机器学习。英国伯明翰:Packt Publishing,2015 年。印刷)

    【讨论】:

    • (漂亮)图像的任何来源?
    • 对不起,我用源更新了我的答案。
    猜你喜欢
    • 2021-10-14
    • 2015-09-07
    • 2017-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2021-01-04
    • 2023-03-07
    相关资源
    最近更新 更多