' GridSearchCV'对象没有属性'估算值_'使用dtreeviz

发布于 2025-02-11 06:56:30 字数 1042 浏览 1 评论 0原文

Randomforest分类器上执行GridSearchCV之后,我正在尝试显示树图。我尝试了下面的代码,但是我得到了此错误:

AttributeError: 'GridSearchCV' object has no attribute 'estimators_'

您能告诉我如何修复此错误并获取树的视图吗?

这是我的分类器代码:

model = RandomForestClassifier()

parameter_space = {
    'n_estimators': [10,50,100],
    'criterion': ['gini', 'entropy'],
    'max_depth': np.linspace(10,50,11),
}

clf = GridSearchCV(model, parameter_space, cv = 5, scoring = "accuracy", verbose = True) # model

clf.fit(X_train,y_train)

train_pred = clf.predict(X_train)   # Train predict
test_pred = clf.predict(X_test)     # Test predict

# Load packages
import pandas as pd
from sklearn import tree
from dtreeviz.trees import dtreeviz # will be used for tree visualization
from matplotlib import pyplot as plt
plt.rcParams.update({'figure.figsize': (12.0, 8.0)})
plt.rcParams.update({'font.size': 14})
 
plt.figure(figsize=(20,20))
_ = tree.plot_tree(clf.n_estimators_[0], feature_names=X_train.columns, filled=True)

After carrying out a GridSearchCV on a Randomforest classifer, I am attempting to display a tree plot. I tried the code below, but I get this error:

AttributeError: 'GridSearchCV' object has no attribute 'estimators_'

Can you tell me how to fix this error and get a view of a tree?

Here is my code from the classifier:

model = RandomForestClassifier()

parameter_space = {
    'n_estimators': [10,50,100],
    'criterion': ['gini', 'entropy'],
    'max_depth': np.linspace(10,50,11),
}

clf = GridSearchCV(model, parameter_space, cv = 5, scoring = "accuracy", verbose = True) # model

clf.fit(X_train,y_train)

train_pred = clf.predict(X_train)   # Train predict
test_pred = clf.predict(X_test)     # Test predict

# Load packages
import pandas as pd
from sklearn import tree
from dtreeviz.trees import dtreeviz # will be used for tree visualization
from matplotlib import pyplot as plt
plt.rcParams.update({'figure.figsize': (12.0, 8.0)})
plt.rcParams.update({'font.size': 14})
 
plt.figure(figsize=(20,20))
_ = tree.plot_tree(clf.n_estimators_[0], feature_names=X_train.columns, filled=True)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

少女七分熟 2025-02-18 06:56:30

您需要从网格搜索中选择最佳的随机森林模型。您需要更改最后一行的代码:

_ = tree.plot_tree(clf.best_estimator_.estimators_[0], feature_names=X_train.columns, filled=True)

You need to select the best Random Forest model from the grid search. You need to change your last line of code :

_ = tree.plot_tree(clf.best_estimator_.estimators_[0], feature_names=X_train.columns, filled=True)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文