numpy读文档:numpy.exceptions 1.20 大全

numpy.exceptions

一文看完所有的 numpy 异常与警告,文中会有 gpt 生成的部分
https://numpy.org/doc/stable/reference/routines.exceptions.html

Warnings:ComplexWarning

The warning raised when casting a complex dtype to a real dtype.

As implemented, casting a complex number to a real discards its imaginary part, but this behavior may not be what the user actually wants.

将复杂数据类型转换为真实的数据类型时出现的警告。但是用.real并不会触发警告

import numpy as np

x = np.array([1+2j, 3+4j, 5+6j])
y = np.array([7+8j, 9+10j, 11+12j])

# 没有警告
z = np.array(x + y)
print(z) # [ 8.+10.j 12.+14.j 16.+18.j]

# 有警告
z = np.array(x + y, dtype=np.float32)
print(z)
# /Users/kimshan/workplace/CVPlayground/scripts/test3.py:9: ComplexWarning: Casting complex values to real discards the imaginary part
#   z = np.array(x + y, dtype=np.float32)
# [ 8. 12. 16.]

# 没有警告
z = np.array(x + y, dtype=np.complex128)
print(z)
# [ 8.+10.j 12.+14.j 16.+18.j]

# 没有警告
print(z.real)
# [ 8. 12. 16.]

Warnings:VisibleDeprecationWarning

Visible deprecation warning.

By default, python will not show deprecation warnings, so this class can be used when a very visible warning is helpful, for example because the usage is most likely a user bug.

默认情况下,python不会显示弃用警告,所以这个类可以在非常明显的警告有帮助时使用,例如因为使用很可能是用户错误。

PS:Python 也有“VisibleDeprecationWarning”这个警告,某些代码行为即将在未来的 Python 版本中更改,或者某些代码行为在 Python 2 中是有效的,但在 Python 3 中已经不再有效。这种警告通常是为了提醒开发者某个功能或用法即将被弃用,因此最好避免使用它。当你看到这个警告时,可能意味着你的代码使用了某些已经被标记为弃用的功能,例如:

  • 使用 Python 2 风格的字符串编码和解码。
  • 使用 print 函数作为语句而不是表达式。
  • 使用 urllib2 模块(在 Python 3 中已替换为 urllib)。
  • 使用 raw_input() 函数(在 Python 3 中已替换为 input())。
import numpy as np

# 示例数据,不同长度的子数组
data = [np.array([1, 2, 3]), np.array([4, 5]), np.array([6])]

# 尝试创建一个 ndarray,它将会触发 VisibleDeprecationWarning
try:
    array = np.array(data)
except np.VisibleDeprecationWarning as e:
    print(f"触发 VisibleDeprecationWarning: {e}")
# /Users/kimshan/workplace/CVPlayground/scripts/test3.py:8: VisibleDeprecationWarning: 
# Creating an ndarray from ragged nested sequences (which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths or shapes) is deprecated. 
# If you meant to do this, you must specify 'dtype=object' when creating the ndarray.

Warnings:RankWarning

Matrix rank warning.

Issued by polynomial functions when the design matrix is rank deficient. 当设计矩阵秩亏时,由多项式函数发出。

import numpy as np
import warnings

# 忽略其他警告,仅显示 RankWarning
warnings.simplefilter('error', np.RankWarning)

# 示例数据,仅有三个点
x = np.array([0, 1, 2])
y = np.array([1, 2, 3])

# 尝试用一个 4 次多项式来拟合这三个点
try:
    coeffs = np.polyfit(x, y, 4)
    p = np.poly1d(coeffs)
    print(f"拟合的多项式系数: {coeffs}")
except np.RankWarning as e:
    print(f"触发 RankWarning: {e}")
    # 触发 RankWarning: Polyfit may be poorly conditioned

exceptions:AxisError

https://numpy.org/doc/stable/reference/generated/numpy.exceptions.AxisError.html

Axis supplied was invalid.

This is raised whenever an axis parameter is specified that is larger than the number of array dimensions. For compatibility with code written against older numpy versions, which raised a mixture of ValueError and IndexError for this situation, this exception subclasses both to ensure that except ValueError and except IndexError statements continue to catch AxisError.

只要指定的 axis 参数大于数组维数,就会引发此问题。为了与针对旧的numpy版本编写的代码兼容,在这种情况下,该代码会引发 ValueError 和 IndexError 的混合,这个异常子类都是为了确保 except ValueError 和 except IndexError 语句继续捕获 AxisError 。

import numpy as np

# 创建一个二维数组
array = np.array([[1, 2, 3], [4, 5, 6]])

# 尝试沿着不存在的轴进行求和操作(二维数组只有轴 0 和 1)
try:
    result = np.sum(array, axis=2)
except np.AxisError as e:
    print(f"触发 AxisError: {e}")
# 触发 AxisError: axis 2 is out of bounds for array of dimension 2

另外可以通过传入参数来指定有关错误的信息,如 axis, ndim, 和 msg_prefix。

  • axis: 引发错误的轴。
  • ndim: 数组的维度。
  • msg_prefix: 错误消息的前缀,提供额外的上下文信息。

当你编写的函数需要处理多维数组,并且必须确保某些操作仅在有效的轴上执行时,指定这些参数有助于调试和处理错误。

import numpy as np

# 自定义函数,确保操作在有效轴上进行
def safe_sum(arr, axis):
    if axis >= arr.ndim or axis < -arr.ndim:
        raise np.AxisError(axis, arr.ndim, msg_prefix="Sum operation")
    return np.sum(arr, axis=axis)

# 创建二维数组
array = np.array([[1, 2, 3], [4, 5, 6]])

# 尝试沿不存在的轴进行求和操作(二维数组只有轴 0 和 1)
try:
    result = safe_sum(array, axis=2)
except np.AxisError as e:
    print(f"触发 AxisError: {e}")
触发 AxisError: Sum operation: axis 2 is out of bounds for array of dimension 2

exceptions:DTypePromotionError

Multiple DTypes could not be converted to a common one.

This exception derives from TypeError and is raised whenever dtypes cannot be converted to a single common one. This can be because they are of a different category/class or incompatible instances of the same one (see Examples).
这个异常来自 TypeError ,当dtypes不能转换为一个公共类型时就会引发。这可能是因为它们属于不同的类别/类或同一类别/类的不兼容实例(参见示例)。

Many functions will use promotion to find the correct result and implementation. For these functions the error will typically be chained with a more specific error indicating that no implementation was found for the input dtypes.
许多函数将使用提升来找到正确的结果和实现。对于这些函数,错误通常会与一个更具体的错误链接在一起,该错误指示没有找到输入数据类型的实现。

Typically promotion should be considered “invalid” between the dtypes of two arrays when arr1 == arr2 can safely return all False because the dtypes are fundamentally different. 通常,当arr 1 == arr 2可以安全地返回所有 False 时,两个数组的数据类型之间的提升应该被认为是“无效的”,因为数据类型是根本不同的。

import numpy as np

# 创建两个数组,一个是整型,一个是字符串型
array_int = np.array([1, 2, 3])
array_str = np.array(["a", "b", "c"])

# 尝试将整型数组和字符串型数组进行元素级加法操作
try:
    result = np.add(array_int, array_str)
except TypeError as e:
    print(f"触发 DTypePromotionError(作为 TypeError 显示): {e}")
# 触发 DTypePromotionError(作为 TypeError 显示): ufunc 'add' did not contain a loop with signature matching types (dtype('int64'), dtype('<U1')) -> None

再如,日期时间和复数是不兼容的类

>>>np.result_type(np.dtype("M8[s]"), np.complex128)
DTypePromotionError: The DType <class 'numpy.dtype[datetime64]'> could not
be promoted by <class 'numpy.dtype[complex128]'>. This means that no common
DType exists for the given inputs. For example they cannot be stored in a
single array unless the dtype is `object`. The full list of DTypes is:
(<class 'numpy.dtype[datetime64]'>, <class 'numpy.dtype[complex128]'>)

在 NumPy 中,np.promote_types 函数用于尝试将两种数据类型(dtype)进行推广(promotion),即找到一个通用的数据类型来容纳这两种类型的数据。下面用np.promote_types来合并两个不兼容的类:

>>>dtype1 = np.dtype([("field1", np.float64), ("field2", np.int64)])
>>>dtype2 = np.dtype([("field1", np.float64)])
>>>np.promote_types(dtype1, dtype2)
DTypePromotionError: field names ('field1', 'field2') and ('field1',)
mismatch.

exceptions:TooHardError

max_work was exceeded. MAX_WORK

This is raised whenever the maximum number of candidate solutions to consider specified by the max_work parameter is exceeded. Assigning a finite number to max_work may have caused the operation to fail.

每当超过由 max_work 参数指定的要考虑的候选解决方案的最大数量时,就会引发此问题。如果将有限的数值设置为max_work,可能会导致操作失败。

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值