解决:ImportError: cannot import name ‘mean_absolute_percentage_error‘ from ‘sklearn.metrics‘

Python问题:

ImportError: cannot import name ‘mean_absolute_percentage_error‘ from ‘sklearn.metrics‘

问题原因:

就是在源脚本中,metric文件夹中mean_absolute_percentage_error所归属的regression.py文件中,没有mean_absolute_percentage_error()函数

解决方法:

  • 第一步:找到电脑中Lib\site-packages\sklearn\metrics位置。
    (我的是在D:\InstallPosition\python×××\Lib\site-packages\sklearn\metrics)

  • 第二步:从sklearn的GitHub源码( 链接:https://github.com/scikit-learn/scikit-learn/blob/2beed5584/sklearn/metrics/_regression.py#L197)中,把mean_absolute_percentage_error这部分的脚本拷贝到自己电脑安装sklearn包的regression.py文件中。
    为了方便,大家也可以不用到这个网站里面找,直接复制粘贴下面的代码放到regression.py文件(有的为_regression.py)文件中就可以了(后面还有第三步,记得看,要不然修不好bug)

def mean_absolute_percentage_error(y_true, y_pred,
                                   sample_weight=None,
                                   multioutput='uniform_average'):
    """Mean absolute percentage error regression loss.
    Note here that we do not represent the output as a percentage in range
    [0, 100]. Instead, we represent it in range [0, 1/eps]. Read more in the
    :ref:`User Guide `.
    .. versionadded:: 0.24
    Parameters
    ----------
    y_true : array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    y_pred : array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    sample_weight : array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput : {'raw_values', 'uniform_average'} or array-like
        Defines aggregating of multiple output values.
        Array-like value defines weights used to average errors.
        If input is list then the shape must be (n_outputs,).
        'raw_values' :
            Returns a full set of errors in case of multioutput input.
        'uniform_average' :
            Errors of all outputs are averaged with uniform weight.
    Returns
    -------
    loss : float or ndarray of floats in the range [0, 1/eps]
        If multioutput is 'raw_values', then mean absolute percentage error
        is returned for each output separately.
        If multioutput is 'uniform_average' or an ndarray of weights, then the
        weighted average of all output errors is returned.
        MAPE output is non-negative floating point. The best value is 0.0.
        But note the fact that bad predictions can lead to arbitarily large
        MAPE values, especially if some y_true values are very close to zero.
        Note that we return a large value instead of `inf` when y_true is zero.
    Examples
    --------
    >>> from sklearn.metrics import mean_absolute_percentage_error
    >>> y_true = [3, -0.5, 2, 7]
    >>> y_pred = [2.5, 0.0, 2, 8]
    >>> mean_absolute_percentage_error(y_true, y_pred)
    0.3273...
    >>> y_true = [[0.5, 1], [-1, 1], [7, -6]]
    >>> y_pred = [[0, 2], [-1, 2], [8, -5]]
    >>> mean_absolute_percentage_error(y_true, y_pred)
    0.5515...
    >>> mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.3, 0.7])
    0.6198...
    """
    y_type, y_true, y_pred, multioutput = _check_reg_targets(
        y_true, y_pred, multioutput)
    check_consistent_length(y_true, y_pred, sample_weight)
    epsilon = np.finfo(np.float64).eps
    mape = np.abs(y_pred - y_true) / np.maximum(np.abs(y_true), epsilon)
    output_errors = np.average(mape,
                               weights=sample_weight, axis=0)
    if isinstance(multioutput, str):
        if multioutput == 'raw_values':
            return output_errors
        elif multioutput == 'uniform_average':
            # pass None as weights to np.average: uniform mean
            multioutput = None

    return np.average(output_errors, weights=multioutput)

  • 第三步:在Lib\site-packages\sklearn\metrics文件夹中,找到__init__.py文件,增加一行下面的代码:
from ._regression import mean_absolute_percentage_error

这句代码的意思就是记得去_regression.py文件中找mean_absolute_percentage_error。

  • 第四步:在__init__.py文件和_regression.py中还存在__all__()函数,可以把‘mean_absolute_percentage_error’或者“mean_absolute_percentage_error”按照函数里的几个格式照葫芦画瓢地写上去。
    为了确保能早点解决错误,笔者在这里是在__all__()函数里面也按照格式写上了mean_absolute_percentage_error,但是自身认为可能不写也可以,所以认为这点可有可无。
    如果大家看到博文这里有兴趣进行尝试,欢迎将该种方案是否可行评论区或者私信告诉笔者哦~~(**^▽^**),欢迎交流

参考文献:

  1. https://blog.csdn.net/qq_40206371/article/details/120549324
  2. https://github.com/scikit-learn/scikit-learn/blob/2beed5584/sklearn/metrics/_regression.py#L197
  3. https://blog.csdn.net/u010614781/article/details/118080544

你可能感兴趣的:(sklearn,python,机器学习)