完美解决cannot import name ‘_validate_lengths‘ from ‘numpy.lib.arraypad‘错误

79 篇文章 1 订阅
51 篇文章 6 订阅

运行以下语句:from skimage import transform
出现如题所示错误,出现错误是因为
C:\Users\Anaconda3\Lib\site-packages\skimage\util
这个文件中的第八行代码要从arraypad.py中导入一个名为_validate_lengths的函数,而系统在该文件中找不到该函数,出现这个错误可能是因为numpy版本升级导致的,但不建议降低numpy版本。解决办法如下:

第一步:

在C:\Users\Anaconda3\Lib\site-packages\skimage\util目录中找到arraycrop.py,并打开,该文件中已经给出了因为numpy版本变化导致arraycrop不可用的方法,即将以注释方式给出的两个函数复制到
C:\Users\Anaconda3\Lib\site-packages\numpy\lib目录中找到arraypad.py文件中。相关注释如下所示:

# The below functions are retained in comments in case the NumPy architecture
# changes and we need copies of these helper functions for `crop`.
# These are identical to functions in numpy.lib.arraypad.py as of NumPy v1.11

# def _normalize_shape(ndarray, shape, cast_to_int=True):
#     """
#     Private function which does some checks and normalizes the possibly
#     much simpler representations of 'pad_width', 'stat_length',
#     'constant_values', 'end_values'.
#
#     Parameters
#     ----------
#     narray : ndarray
#         Input ndarray
#     shape : {sequence, array_like, float, int}, optional
#         The width of padding (pad_width), the number of elements on the
#         edge of the narray used for statistics (stat_length), the constant
#         value(s) to use when filling padded regions (constant_values), or the
#         endpoint target(s) for linear ramps (end_values).
#         ((before_1, after_1), ... (before_N, after_N)) unique number of
#         elements for each axis where `N` is rank of `narray`.
#         ((before, after),) yields same before and after constants for each
#         axis.
#         (constant,) or val is a shortcut for before = after = constant for
#         all axes.
#     cast_to_int : bool, optional
#         Controls if values in ``shape`` will be rounded and cast to int
#         before being returned.
#
#     Returns
#     -------
#     normalized_shape : tuple of tuples
#         val                               => ((val, val), (val, val), ...)
#         [[val1, val2], [val3, val4], ...] => ((val1, val2), (val3, val4), ...)
#         ((val1, val2), (val3, val4), ...) => no change
#         [[val1, val2], ]                  => ((val1, val2), (val1, val2), ...)
#         ((val1, val2), )                  => ((val1, val2), (val1, val2), ...)
#         [[val ,     ], ]                  => ((val, val), (val, val), ...)
#         ((val ,     ), )                  => ((val, val), (val, val), ...)
#
#     """
#     ndims = ndarray.ndim
#
#     # Shortcut shape=None
#     if shape is None:
#         return ((None, None), ) * ndims
#
#     # Convert any input `info` to a NumPy array
#     arr = np.asarray(shape)
#
#     # Switch based on what input looks like
#     if arr.ndim <= 1:
#         if arr.shape == () or arr.shape == (1,):
#             # Single scalar input
#             #   Create new array of ones, multiply by the scalar
#             arr = np.ones((ndims, 2), dtype=ndarray.dtype) * arr
#         elif arr.shape == (2,):
#             # Apply padding (before, after) each axis
#             #   Create new axis 0, repeat along it for every axis
#             arr = arr[np.newaxis, :].repeat(ndims, axis=0)
#         else:
#             fmt = "Unable to create correctly shaped tuple from %s"
#             raise ValueError(fmt % (shape,))
#
#     elif arr.ndim == 2:
#         if arr.shape[1] == 1 and arr.shape[0] == ndims:
#             # Padded before and after by the same amount
#             arr = arr.repeat(2, axis=1)
#         elif arr.shape[0] == ndims:
#             # Input correctly formatted, pass it on as `arr`
#             arr = shape
#         else:
#             fmt = "Unable to create correctly shaped tuple from %s"
#             raise ValueError(fmt % (shape,))
#
#     else:
#         fmt = "Unable to create correctly shaped tuple from %s"
#         raise ValueError(fmt % (shape,))
#
#     # Cast if necessary
#     if cast_to_int is True:
#         arr = np.round(arr).astype(int)
#
#     # Convert list of lists to tuple of tuples
#     return tuple(tuple(axis) for axis in arr.tolist())


# def _validate_lengths(narray, number_elements):
#     """
#     Private function which does some checks and reformats pad_width and
#     stat_length using _normalize_shape.
#
#     Parameters
#     ----------
#     narray : ndarray
#         Input ndarray
#     number_elements : {sequence, int}, optional
#         The width of padding (pad_width) or the number of elements on the edge
#         of the narray used for statistics (stat_length).
#         ((before_1, after_1), ... (before_N, after_N)) unique number of
#         elements for each axis.
#         ((before, after),) yields same before and after constants for each
#         axis.
#         (constant,) or int is a shortcut for before = after = constant for all
#         axes.
#
#     Returns
#     -------
#     _validate_lengths : tuple of tuples
#         int                               => ((int, int), (int, int), ...)
#         [[int1, int2], [int3, int4], ...] => ((int1, int2), (int3, int4), ...)
#         ((int1, int2), (int3, int4), ...) => no change
#         [[int1, int2], ]                  => ((int1, int2), (int1, int2), ...)
#         ((int1, int2), )                  => ((int1, int2), (int1, int2), ...)
#         [[int ,     ], ]                  => ((int, int), (int, int), ...)
#         ((int ,     ), )                  => ((int, int), (int, int), ...)
#
#     """
#     normshp = _normalize_shape(narray, number_elements)
#     for i in normshp:
#         chk = [1 if x is None else x for x in i]
#         chk = [1 if x >= 0 else -1 for x in chk]
#         if (chk[0] < 0) or (chk[1] < 0):
#             fmt = "%s cannot contain negative values."
#             raise ValueError(fmt % (number_elements,))
#     return normshp

第二步:

在C:\Users\Anaconda3\Lib\site-packages\numpy\lib目录中找到arraypad.py并打开,在954行之后,插入去掉注释的两个函数:

def _normalize_shape(ndarray, shape, cast_to_int=True):
    """
    Private function which does some checks and normalizes the possibly
    much simpler representations of 'pad_width', 'stat_length',
    'constant_values', 'end_values'.

    Parameters
    ----------
    narray : ndarray
        Input ndarray
    shape : {sequence, array_like, float, int}, optional
        The width of padding (pad_width), the number of elements on the
        edge of the narray used for statistics (stat_length), the constant
        value(s) to use when filling padded regions (constant_values), or the
        endpoint target(s) for linear ramps (end_values).
        ((before_1, after_1), ... (before_N, after_N)) unique number of
        elements for each axis where `N` is rank of `narray`.
        ((before, after),) yields same before and after constants for each
        axis.
        (constant,) or val is a shortcut for before = after = constant for
        all axes.
    cast_to_int : bool, optional
        Controls if values in ``shape`` will be rounded and cast to int
        before being returned.

    Returns
    -------
    normalized_shape : tuple of tuples
        val                               => ((val, val), (val, val), ...)
        [[val1, val2], [val3, val4], ...] => ((val1, val2), (val3, val4), ...)
        ((val1, val2), (val3, val4), ...) => no change
        [[val1, val2], ]                  => ((val1, val2), (val1, val2), ...)
        ((val1, val2), )                  => ((val1, val2), (val1, val2), ...)
        [[val ,     ], ]                  => ((val, val), (val, val), ...)
        ((val ,     ), )                  => ((val, val), (val, val), ...)

    """
    ndims = ndarray.ndim

    # Shortcut shape=None
    if shape is None:
        return ((None, None), ) * ndims

    # Convert any input `info` to a NumPy array
    shape_arr = np.asarray(shape)

    try:
        shape_arr = np.broadcast_to(shape_arr, (ndims, 2))
    except ValueError:
        fmt = "Unable to create correctly shaped tuple from %s"
        raise ValueError(fmt % (shape,))

    # Cast if necessary
    if cast_to_int is True:
        shape_arr = np.round(shape_arr).astype(int)

    # Convert list of lists to tuple of tuples
    return tuple(tuple(axis) for axis in shape_arr.tolist())


def _validate_lengths(narray, number_elements):
    """
    Private function which does some checks and reformats pad_width and
    stat_length using _normalize_shape.

    Parameters
    ----------
    narray : ndarray
        Input ndarray
    number_elements : {sequence, int}, optional
        The width of padding (pad_width) or the number of elements on the edge
        of the narray used for statistics (stat_length).
        ((before_1, after_1), ... (before_N, after_N)) unique number of
        elements for each axis.
        ((before, after),) yields same before and after constants for each
        axis.
        (constant,) or int is a shortcut for before = after = constant for all
        axes.

    Returns
    -------
    _validate_lengths : tuple of tuples
        int                               => ((int, int), (int, int), ...)
        [[int1, int2], [int3, int4], ...] => ((int1, int2), (int3, int4), ...)
        ((int1, int2), (int3, int4), ...) => no change
        [[int1, int2], ]                  => ((int1, int2), (int1, int2), ...)
        ((int1, int2), )                  => ((int1, int2), (int1, int2), ...)
        [[int ,     ], ]                  => ((int, int), (int, int), ...)
        ((int ,     ), )                  => ((int, int), (int, int), ...)

    """
    normshp = _normalize_shape(narray, number_elements)
    for i in normshp:
        chk = [1 if x is None else x for x in i]
        chk = [1 if x >= 0 else -1 for x in chk]
        if (chk[0] < 0) or (chk[1] < 0):
            fmt = "%s cannot contain negative values."
            raise ValueError(fmt % (number_elements,))
    return normshp

保存后,重启该环境对应的kernel,注意一定不要忘了重启!!!

  • 8
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值