【发布时间】: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.
【问题讨论】:
标签: python scikit-learn pipeline