首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >plot_partial_dependence()来自scikit-学习错误地为合适的模型(例如KerasRegressor或LGBMClassifier)提高NotFittedError

plot_partial_dependence()来自scikit-学习错误地为合适的模型(例如KerasRegressor或LGBMClassifier)提高NotFittedError
EN

Stack Overflow用户
提问于 2020-04-22 19:18:50
回答 3查看 4.5K关注 0票数 5

我试图使用sklearn.inspection.plot_partial_dependence在我成功构建的一个模型上创建部分依赖图,该模型使用keras和keras包装工具(请参阅下面的代码块)。该模型建立成功,可以采用拟合方法,拟合后可以根据预期结果使用预测方法。所有迹象表明,这是一个有效的估计。然而,当我试图从plot_partial_dependence运行sklearn.inspection时,我得到了一些错误文本,暗示它不是一个有效的估计器,尽管我可以证明它是有效的。

我已经编辑了这是更容易复制使用sklearn示例波士顿住房数据。

代码语言:javascript
运行
复制
from sklearn.datasets import load_boston
from sklearn.inspection import plot_partial_dependence, partial_dependence
from keras.wrappers.scikit_learn import KerasRegressor
import keras
import tensorflow as tf
import pandas as pd

boston = load_boston()
feature_names = boston.feature_names
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = boston.target
mean = X.describe().transpose()['mean']
std = X.describe().transpose()['std']
X_norm = (X-mean)/std

def build_model_small():
    model = keras.Sequential([
        keras.layers.Dense(64, activation='relu', input_shape=[len(X.keys())]),
        keras.layers.Dense(64, activation='relu'),
        keras.layers.Dense(1)
        ])

    optimizer = keras.optimizers.RMSprop(0.0005)

    model.compile(loss='mse',
              optimizer=optimizer,
              metrics=['mae', 'mse', 'mape'])
    return model


kr = KerasRegressor(build_fn=build_model_small,verbose=0)
kr.fit(X_norm,y, epochs=100, validation_split = 0.2)
pdp_plot = plot_partial_dependence(kr,X_norm,feature_names)

就像我说的,如果我运行kr.predict(X.head(20)),就会得到20种y值的预测,这是对X的前20行的预测,就像一个有效的估计器所期望的那样。

但是,我从plot_partial_dependence获得的错误文本如下:

代码语言:javascript
运行
复制
Traceback (most recent call last):
  File "temp_ML_tf_sklearn_postproc.py", line 79, in <module>
    pdp_plot = plot_partial_dependence(kr,X,labels[:-1])
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 678, in plot_partial_dependence
    for fxs in features)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 921, in __call__
    if self.dispatch_one_batch(iterator):
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "/home/mymachine/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 307, in partial_dependence
    "'estimator' must be a fitted regressor or classifier."
ValueError: 'estimator' must be a fitted regressor or classifier.

我查看了plot_partial_dependence的源代码,它有以下几点要说。首先,在docstring中,它说第一个输入estimator必须是.

一个拟合的估计器对象实现:术语:predict,:term:predict\_proba,或:term:decision\_function。不支持多输出-多类分类器。

我的估计器确实实现了.predict。

其次,在errr跟踪中调用的行调用一个检查器,该检查器检查它是一个回归者还是一个分类器:

代码语言:javascript
运行
复制
if not (is_classifier(estimator) or is_regressor(estimator)):
    raise ValueError(
        "'estimator' must be a fitted regressor or classifier."
    )

我查看了is_regressor()的源代码,它是一个类似于这样的一行:

代码语言:javascript
运行
复制
return getattr(estimator, "_estimator_type", None) == "regressor"

所以我尝试通过做setattr(mp,'_estimator_type','regressor')来破解它,它只是说Attribute Error: can't set attribute,所以这是一个不起作用的廉价解决方法。

我甚至尝试了更困难的修复,并临时注释掉了_partial_dependence.py源中的违规检查(我在上面复制的if语句),并得到了以下错误:

代码语言:javascript
运行
复制
Traceback (most recent call last):
  File "temp_ML_tf_sklearn_postproc.py", line 79, in <module>
    pdp_plot = plot_partial_dependence(kr,X,labels[:-1])
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 678, in plot_partial_dependence
    for fxs in features)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 921, in __call__
    if self.dispatch_one_batch(iterator):
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 759, in dispatch_one_batch
    self._dispatch(tasks)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 716, in _dispatch
    job = self._backend.apply_async(batch, callback=cb)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 182, in apply_async
    result = ImmediateResult(func)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/_parallel_backends.py", line 549, in __init__
    self.results = batch()
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in __call__
    for func, args, kwargs in self.items]
  File "/home/billy/anaconda3/lib/python3.7/site-packages/joblib/parallel.py", line 225, in <listcomp>
    for func, args, kwargs in self.items]
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py", line 317, in partial_dependence
    check_is_fitted(est)
  File "/home/billy/anaconda3/lib/python3.7/site-packages/sklearn/utils/validation.py", line 967, in check_is_fitted
    raise NotFittedError(msg % {'name': type(estimator).__name__})
sklearn.exceptions.NotFittedError: This KerasRegressor instance is not fitted yet. Call 'fit' with appropriate arguments before using this estimator.

这可以追溯到滑雪板函数的问题,当它真的适合的时候,它并不认为这个模型是合适的。无论如何,在这一点上,我决定不再尝试任何更危险的、烦人的修补程序来修改源代码。

我还尝试直接传递kr.fit(X,y,etc...)作为plot_partial_dependence的第一个参数。计算机旋转了几分钟,表明fit实际上在运行,但是当它试图运行部分依赖图时,我得到了同样的错误。

另一个令人费解的线索。我试着在另一个sklearn函数中使用keras/sklearn包装的管道,看看它是否能与任何sklearn实用程序一起工作。这次,我做到了:

代码语言:javascript
运行
复制
from sklearn.model_selection import cross_validate
cv_scores = cross_validate(kr,X_norm,y, cv=4, return_train_score=True, n_jobs=-1)`

而且起作用了!因此,我认为我使用keras.wrappers.scikit_learn.KerasRegressor并没有本质上的问题。

这可能只是一种情况,我试图做的是在plot_partial_dependence源代码中没有具体规划的边缘情况,我运气不好,但我想知道是否有其他人看到这样的问题,并有一个解决方案或解决方案。

顺便说一下,我正在使用sklearn 0.22.1和Python3.7.3 (Anaconda)。而且要明确的是,我已经在滑雪板建造的模型甚至管道上使用了plot_partial_dependence。这个问题只发生在基于核的模型上。非常感谢人们的任何投入。

编辑:

这个问题的前一个版本涉及使用StandardScaler()构建管道,然后使用KerasRegressor包装对象。从那时起,我发现即使只使用KerasRegressor对象也会发生这种情况,也就是说,我已经将问题隔离到了该对象上,而不是管道。因此,正如一位评论者所建议的,我把管道部分排除在外,以使它更简单,更有意义。

EN

回答 3

Stack Overflow用户

发布于 2020-05-30 12:48:20

之所以会出现这个问题,是因为非scikit学习模型对象(如LightGBMRegressorLGBMClassifier)不包含以下划线结尾的属性,如果模型合适,check_is_fitted()将使用该属性作为测试(参见文档)。

因此,一个简单的解决方法是在经过训练的模型对象中添加一个虚拟属性,其名称以下划线结尾:

代码语言:javascript
运行
复制
test_model.dummy_ = "dummy"

您还可以通过自己调用check_if_fitted()来验证它是否工作:

代码语言:javascript
运行
复制
from sklearn.utils import validation

validation.check_is_fitted(estimator=test_model)
票数 4
EN

Stack Overflow用户

发布于 2020-04-28 16:47:06

最后,我找到了一个廉价的工作环境,它成功地适用于这个特定的案例。然而,这并不是一个非常令人满意的答案,也不能保证它将适用于所有情况,所以我希望看到一个更好的答案,如果有人有一个更一般的。但我会在这里发这篇文章,以防其他人需要解决这个问题。

我只是简单地将源代码(在我的anaconda安装中,它在~/anaconda3/lib/python3.7/site-packages/sklearn/inspection/_partial_dependence.py中)复制到我的项目目录中的一个名为custom_pdp.py的文件中,在该文件中,我将违规的部分注释掉(并且在必要时,硬编码我自己的暂存值)。

在我的代码中,我使用了导入行import custom_pdp as cpdp,而不是从sklearn导入它,然后将plot_partial_dependence称为cpdp.plot_partial_dependence(...)

下面是我必须从该源文件中更改的行。请注意,您需要复制整个源文件,因为其中还定义了需要的其他函数,但我只做了如下更改。而且,这是在sklearn 0.22.1中完成的--它可能不适用于其他版本。

首先,您必须更改顶部的相对导入行,如下所示:

代码语言:javascript
运行
复制
from sklearn.utils.extmath import cartesian
from sklearn.utils import check_array
from sklearn.utils import check_matplotlib_support  # noqa
from sklearn.utils import _safe_indexing
from sklearn.utils import _determine_key_type
from sklearn.utils import _get_column_indices
from sklearn.utils.validation import check_is_fitted
from sklearn.tree._tree import DTYPE
from sklearn.exceptions import NotFittedError
from sklearn.ensemble._gb import BaseGradientBoosting
from sklearn.ensemble._hist_gradient_boosting.gradient_boosting import (
    BaseHistGradientBoosting)

(它们以前是相对路径,如from ..utils.extmath import cartesian等)

然后,唯一被更改的函数是:

来自_partial_dependence_brute

代码语言:javascript
运行
复制
def _partial_dependence_brute(est, grid, features, X, response_method):

    ... (skipping docstring)

    averaged_predictions = []

    # define the prediction_method (predict, predict_proba, decision_function).
    # if is_regressor(est):
    #     prediction_method = est.predict
    # else:
    #     predict_proba = getattr(est, 'predict_proba', None)
    #     decision_function = getattr(est, 'decision_function', None)
    #     if response_method == 'auto':
    #         # try predict_proba, then decision_function if it doesn't exist
    #         prediction_method = predict_proba or decision_function
    #     else:
    #         prediction_method = (predict_proba if response_method ==
    #                              'predict_proba' else decision_function)
    #     if prediction_method is None:
    #         if response_method == 'auto':
    #             raise ValueError(
    #                 'The estimator has no predict_proba and no '
    #                 'decision_function method.'
    #             )
    #         elif response_method == 'predict_proba':
    #             raise ValueError('The estimator has no predict_proba method.')
    #         else:
    #             raise ValueError(
    #                 'The estimator has no decision_function method.')
    prediction_method = est.predict

    #the rest in this function are as they were before, beginning with:
    for new_values in grid:
        X_eval = X.copy()

        ....

然后注释掉partial_dependence定义的前20行

代码语言:javascript
运行
复制
def partial_dependence(estimator, X, features, response_method='auto',
                   percentiles=(0.05, 0.95), grid_resolution=100,
                   method='auto'):
    ... (skipping docstring)
    # if not (is_classifier(estimator) or is_regressor(estimator)):
    #     raise ValueError(
    #         "'estimator' must be a fitted regressor or classifier."
    #     )
    # 
    # if isinstance(estimator, Pipeline):
    #     # TODO: to be removed if/when pipeline get a `steps_` attributes
    #     # assuming Pipeline is the only estimator that does not store a new
    #     # attribute
    #     for est in estimator:
    #         # FIXME: remove the None option when it will be deprecated
    #         if est not in (None, 'drop'):
    #             check_is_fitted(est)
    # else:
    #     check_is_fitted(estimator)
    # 
    # if (is_classifier(estimator) and
    #         isinstance(estimator.classes_[0], np.ndarray)):
    #     raise ValueError(
    #         'Multiclass-multioutput estimators are not supported'
    #     )

    #The rest of the function continues as it was:
    # Use check_array only on lists and other non-array-likes / sparse. Do not
    # convert DataFrame into a NumPy array.
    if not(hasattr(X, '__array__') or sparse.issparse(X)):
        X = check_array(X, force_all_finite='allow-nan', dtype=np.object)

        ....

如果您的模型是不同类型的,或者您正在使用不同的参数,则可能需要进行其他更改。

在我的模型上,它的工作与我所希望的完全一样。但就像我说的,这是一个解决方案,并不是最令人满意的解决方案。而且,您的成功可能会因您试图使用的模型类型或参数类型而有很大差异。

票数 1
EN

Stack Overflow用户

发布于 2022-07-28 11:46:28

DrSandwich提出的"hack“就像一种魅力--我正在努力解决与我使用的ARIMA模型不同的问题--这个模型不遵循传统的sklearn语法--我编写了一个包装器,并对.py文件进行了DrSandwich建议的调整.非常感谢!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61373393

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档