【问题标题】:'DecisionTreeClassifier' object is not subscriptable\'DecisionTreeClassifier\' 对象不可订阅
【发布时间】:2022-12-11 04:52:57
【问题描述】:

我尝试在管道之后可视化决策树。

这是我的代码:

num_pipeline = Pipeline(steps=[
    ('impute', SimpleImputer(strategy='mean')),
    ('scale', MinMaxScaler())
])
cat_pipeline = Pipeline(steps=[
    ('impute', SimpleImputer(strategy='most_frequent')),
    ('one-hot',OneHotEncoder(handle_unknown='ignore', sparse=False))
])


from sklearn.compose import ColumnTransformer
preprocessor = ColumnTransformer(transformers=[
    ('num_pipeline',num_pipeline,num_cols),
    ('cat_pipeline',cat_pipeline,cat_cols)
    ],
    remainder='drop',
    n_jobs=-1)

from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn import tree

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

from sklearn import metrics

clf.fit(X_train, y_train)
# preds = clf_pipeline.predict(X_test)
model = clf.score(X_test, y_test)
print(f"Model score: {model}") # accuracy

tree.plot_tree(clf['classifier'])

但是,我收到一个错误:TypeError: 'DecisionTreeClassifier' object is not subscriptable。

我该如何解决?

我认为一切都已正确完成,但我仍然遇到错误,而且我不知道如何解决。

【问题讨论】:

  • 请包括具有所有必需导入的代码和其他人可以轻松运行的数据示例。如果不提供它们,您就很难让其他人帮助您。

标签: python pipeline


【解决方案1】:

你试过了吗

tree.plot_tree(clf)

该错误表明无法使用 ['something'] 表示法访问 clf 对象。

【讨论】:

    猜你喜欢
    • 2018-04-29
    • 2020-09-07
    • 2023-01-15
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    • 2023-02-03
    • 2022-01-23
    相关资源
    最近更新 更多