【问题标题】:NotFittedError: This DecisionTreeClassifier instance is not fitted yetNotFittedError:此 DecisionTreeClassifier 实例尚未安装
【发布时间】:2022-01-26 23:44:09
【问题描述】:

我是 ML 新手,正在尝试运行基于决策树的模型

我尝试了以下

X = df[['Quantity']]
y = df[['label']]
params = {'max_depth':[2,3,4], 'min_samples_split':[2,3,5,10]}
clf_dt = DecisionTreeClassifier()
clf = GridSearchCV(clf_dt, param_grid=params, scoring='f1')
clf.fit(X, y)
clf_dt = DecisionTreeClassifier(clf.best_params_)

得到了这里提到的警告

FutureWarning: Pass criterion={'max_depth': 2, 'min_samples_split': 2} as keyword args. From version 1.0 (renaming of 0.25) passing these as positional arguments will result in an error
  warnings.warn(f"Pass {args_msg} as keyword args. From version "

后来,我尝试运行下面的代码并得到一个错误(但我已经使用.fit()拟合了模型)

from sklearn import tree
tree.plot_tree(clf_dt, filled=True, feature_names = list(X.columns), class_names=['Iris-setosa', 'Iris-versicolor', 'Iris-virginica'])

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

可以帮助我解决这个错误吗?

【问题讨论】:

    标签: python machine-learning scikit-learn classification decision-tree


    【解决方案1】:

    如果您选择best_params_,则必须使用这些参数重新拟合模型。请注意,这些应该在传递给模型时解包:

    clf_dt = DecisionTreeClassifier(**clf.best_params_)
    clf_dt.fit(X, y)
    

    但是,您也可以使用best_estimator_ 属性来直接访问最佳模型:

    clf_dt = clf.best_estimator_
    

    【讨论】:

    • 感谢投票。但是我得到了这个错误`AttributeError:'GridSearchCV'对象没有属性'tree_'`
    • 但我已经从 sklearn 导入了树
    • 你究竟想在哪里访问clf.tree_
    • 谢谢,现在可以了。我错误地引用了不正确的clf 而不是clf_dt
    【解决方案2】:

    所以你面临两个问题。

    首先

    参考

    FutureWarning:通过标准={'max_depth': 2, 'min_samples_split': 2} 作为关键字参数。从 1.0 版(重命名为 0.25)开始,将这些作为位置参数传递将导致错误

    您可以尝试在创建params 时使用dict 类构造函数:

    params = dict(max_depth=[2,3,4], min_samples_split=[2,3,5,10])
    

    但是这个警告看起来很奇怪,而且我没有出现。

    其次

    参考

    NotFittedError:此 DecisionTreeClassifier 实例尚未安装。在使用此估算器之前,使用适当的参数调用“fit”。

    Here你可以了解sklearn中的强制拟合步骤。但正如您所说,您只是在第一个代码示例中这样做了。你的问题是使用

    clf_dt = DecisionTreeClassifier(clf.best_params_)
    

    您创建了一个新的 DecisionTreeClassifier 类,因此在您调用时不适合

    tree.plot_tree(clf_dt ...)
    

    当你打电话时

    clf = GridSearchCV(clf_dt, param_grid=params, scoring='f1')
    

    在您的情况下,sklearn 会自动将最佳估算器分配给 clf。所以只需使用这个变量:) 以下步骤clf_dt = DecisionTreeClassifier(clf.best_params_) 不是必需的。

    【讨论】:

    • params = dict(max_depth=[2,3,4], min_samples_split=[2,3,5,10]) 正是 OP 使用的,clf = GridSearchCV(clf_dt, param_grid=**params, scoring='f1') 是无效语法。
    • 你对无效语法的事情是正确的。我的错。使用替代方法创建 param dict 只是一个建议。我真的不明白为什么会出现这个警告。
    猜你喜欢
    • 2019-12-13
    • 2021-12-19
    • 1970-01-01
    • 2020-04-14
    • 1970-01-01
    • 2022-11-07
    • 2019-03-10
    • 1970-01-01
    • 2021-08-28
    相关资源
    最近更新 更多