sklearn “管道实例尚未安装。”错误,即使它是

Posted

技术标签:

【中文标题】sklearn “管道实例尚未安装。”错误,即使它是【英文标题】:sklearn "Pipeline instance is not fitted yet." error, even though it is 【发布时间】:2021-08-28 18:21:16 【问题描述】:

已经问过一个类似的问题,但答案并没有帮助我解决我的问题:Sklearn components in pipeline is not fitted even if the whole pipeline is?

我正在尝试使用多个管道通过 One Hot Encoder 对分类和数值数据进行预处理(如 this blog 中所建议的那样)。

这是我的代码,尽管我的分类器产生了 78% 的准确率,但我无法弄清楚为什么我无法绘制我正在训练的决策树以及什么可以帮助我解决问题。这是代码sn-p:

import pandas as pd
import sklearn.tree as tree
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import OneHotEncoder  
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
from sklearn.compose import ColumnTransformer


X = pd.DataFrame(data=data)  
Y = pd.DataFrame(data=prediction)

categoricalFeatures = ["race", "gender"]
numericalFeatures = ["age", "number_of_actions"]

categoricalTransformer = Pipeline(steps=[
    ('onehot', OneHotEncoder(handle_unknown='ignore')),
])

numericTransformer = Pipeline(steps=[
    ('imputer', SimpleImputer(strategy='median')),
    ('scaler', StandardScaler()),
])

preprocessor = ColumnTransformer(transformers=[
    ('num', numericTransformer, numericalFeatures),
    ('cat', categoricalTransformer, categoricalFeatures)
])

classifier = Pipeline(steps=[
    ('preprocessor', preprocessor),
    ('classifier', tree.DecisionTreeClassifier(max_depth=3))
])

X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=12, stratify=Y)

classifier.fit(X_train, y_train)
print("model score: %.3f" % classifier.score(X_test, y_test))  # Prints accuracy of 0.78

text_representation = tree.export_text(classifier)

最后一个命令产生了这个错误,尽管模型被拟合了(我假设这是一个同步情况,但不知道如何解决它):

sklearn.exceptions.NotFittedError: This Pipeline instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

【问题讨论】:

【参考方案1】:

您不能在整个管道上使用export_text 函数,因为它只接受决策树对象,即DecisionTreeClassifierDecisionTreeRegressor。仅通过管道的拟合估计器,它将起作用:

text_representation = tree.export_text(classifier['classifier'])

指出Pipeline 对象未拟合的错误消息是由于scikit-learncheck_is_fitted 函数引起的。它通过检查估计器上是否存在拟合属性(以尾随下划线结尾)来工作。由于Pipeline 对象不公开此类属性,因此检查失败并引发错误,尽管它确实适合。但这不是问题,因为无论如何Pipeline 对象不应该以这种方式使用。

【讨论】:

这太棒了!非常感谢您快速而完整的回复,@afsharov!后续问题:有没有办法使用此管道实际获取新的功能名称列表? (基于管道中的一个热门编码器?) 没关系!找到了一个解决方案here,在我的情况下,它的工作原理如下:classifier['preprocessor'].transformers_[1][1]['onehot']\ .get_feature_names(categoricalFeatures)

以上是关于sklearn “管道实例尚未安装。”错误,即使它是的主要内容,如果未能解决你的问题,请参考以下文章

使用 sklearn 找出错误率

python sklearn中的导入错误。无法加载引用的库

Python 导入错误:无法从“sklearn.externals”导入名称“六”

Python SKLearn 拟合值错误输入

sklearn:应用相同的缩放来训练和预测管道

导入 sklearn 时出现不可排序的类型错误