【问题标题】:TypeError: estimator should be an estimator implementing 'fit' method [closed]TypeError:估计器应该是实现“适合”方法的估计器[关闭]
【发布时间】:2022-01-11 05:27:39
【问题描述】:

我从 Stepik 解决问题:

一棵树是好的,但哪里能保证它是最好的,或者 至少接近它?找到或多或少最优的方法之一 一组树参数是迭代一组树 不同的参数并选择合适的参数。以此目的, 有一个 GridSearchCV 类迭代每个 为模型、火车指定的参数组合 它在数据上并执行交叉验证。之后,模型 具有最佳参数的存储在 .best_estimator_ 属性中。 现在的任务是遍历 iris 数据上的所有树 根据以下参数: 最大深度 - 从 1 到 10 用于分离的最小样本数量为 2 到 10 每张纸的最小样本数量 - 从 1 到 10 并存储最好的 变量 best_tree 中的树。使用 GridSearchCV 命名变量 搜索。 这是我的解决方案:

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_iris


iris = load_iris()
X = iris.data
y = iris.target

parameters = {'max_depth': range(1, 10), 'min_samples_split': range(2, 10), 'min_samples_leaf': range(1, 10)}
search = GridSearchCV(iris, parameters)

search.fit(X, y)

best_tree = search.estimator

为什么会出现这个错误?:

Traceback (most recent call last):
  File "jailed_code", line 22, in <module>
    search.fit(X, y)
  File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/sklearn/model_selection/_search.py", line 595, in fit
    self.estimator, scoring=self.scoring)
  File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/sklearn/metrics/scorer.py", line 342, in _check_multimetric_scoring
    scorers = {"score": check_scoring(estimator, scoring=scoring)}
  File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/sklearn/metrics/scorer.py", line 274, in check_scoring
    "'fit' method, %r was passed" % estimator)
TypeError: estimator should be an estimator implementing 'fit' method, {'data': array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
       [4.7, 3.2, 1.3, 0.2],
       [4.6, 3.1, 1.5, 0.2],
       [5. , 3.6, 1.4, 0.2],
       [5.4, 3.9, 1.7, 0.4],
       [4.6, 3.4, 1.4, 0.3],
       [5. , 3.4, 1.5, 0.2],
       ...

【问题讨论】:

  • GridSearchCV(iris, ...) 处的错字。您需要放置一个估算器(即DecisionTreeClassifier)而不是数据本身(iris

标签: python pandas scikit-learn


【解决方案1】:

您传递了数据集而不是估算器。如果你还没有,看看这个 https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.GridSearchCV.html

这应该可以工作

import pandas as pd
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import GridSearchCV
from sklearn.datasets import load_iris

iris = load_iris()
X = iris.data
y = iris.target

parameters = {'max_depth': range(1, 10), 'min_samples_split': range(2, 10), 'min_samples_leaf': range(1, 10)}
search = GridSearchCV(estimator=DecisionTreeClassifier(),
                      param_grid=parameters)

search.fit(X, y)

search.cv_results_

【讨论】:

    【解决方案2】:

    您已将任何估算器传递给您的 GridSearchCV 函数。您必须将要适合 GridSearCV 的估计器的实例传递给 GridSearCV,但是您只是传递了不是估计器的 iris

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 2022-01-01
      • 2021-11-03
      • 2020-02-03
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 2015-12-09
      • 2023-01-29
      相关资源
      最近更新 更多