numpy读文档:numpy.exceptions 1.20 大全

numpy.exceptions

文章目录

  • numpy.exceptions
    • Warnings:ComplexWarning
    • Warnings:VisibleDeprecationWarning
    • Warnings:RankWarning
    • exceptions:AxisError
    • exceptions:DTypePromotionError
    • exceptions:TooHardError

一文看完所有的 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 npx = 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,可能会导致操作失败。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/web/49270.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

14 集合运算符和矩阵乘法运算符@

集合的交集、并集、对称差集等运算借助于位运算符来实现&#xff0c;而差集则使用减号运算符实现。 print({1, 2, 3} | {3, 4, 5}) # 并集&#xff0c;自动去除重复元素 print({1, 2, 3} & {3, 4, 5}) # 交集 print({1, 2, 3} - {3, 4, 5}) # 差集 print({1, 2, 4, 6, …

【Python】打印图案 .center(width)

一、题目 Mr. Vincent works in a door mat manufacturing company. One day, he designed a new door mat with the following specifications: Mat size must be N*M. (N is an odd natural number, and M is 3 times N.)The design should have WELCOME written in the ce…

Pandas Series对象的创建和基本使用(Pandas Series Object)

pandas是Python的一个第三方数据分析库&#xff0c;其集成了大量的数据模型和分析工具&#xff0c;可以方便的处理和分析各类数据。Pandas中主要对象类型有Series&#xff0c;DataFrame和Index。本文介绍Series对象的创建和基本用法。 文章目录 一、Series对象的创建1.1 通过序…

Linux|多线程(三)

线程池 线程池是一种多线程处理形式&#xff0c;处理过程中它将被提交的任务分配给预先创建好的多个线程中的一个去执行。 线程池的实现 #pragma once #include <pthread.h> #include <vector> #include <string> #include <unistd.h> #include <…

Conda pack 进行Python环境打包

大模型相关目录 大模型&#xff0c;包括部署微调prompt/Agent应用开发、知识库增强、数据库增强、知识图谱增强、自然语言处理、多模态等大模型应用开发内容 从0起步&#xff0c;扬帆起航。 基于Dify的智能分类方案&#xff1a;大模型结合KNN算法&#xff08;附代码&#xff…

第一次CCF计算机软件能力认证

AcWing 3197. 相反数 有 N 个非零且各不相同的整数。 请你编一个程序求出它们中有多少对相反数(a 和 −a 为一对相反数)。 输入格式 第一行包含一个正整数 N。 第二行为 N 个用单个空格隔开的非零整数&#xff0c;每个数的绝对值不超过 1000&#xff0c;保证这些整数各不相同。…

使用netty编写syslog日志接收服务端

使用netty编写syslog日志接收服务端 1.添加netty依赖 <dependency><groupId>io.netty</groupId><artifactId>netty-all</artifactId><version>4.1.72.Final</version> <!-- 版本号可能需要根据实际情况更新 --></dependenc…

Docker Desktop安装(通俗易懂)

1、官网 https://www.docker.com/products/docker-desktop/ 2、阿里云镜像 docker-toolbox-windows-docker-for-windows安装包下载_开源镜像站-阿里云 1. 双击安装文件勾选选项 意思就是&#xff1a; Use WSL 2 instead of Hyper-V (recommended) : 启用虚拟化&#xff0c;…

重生之“我打数据结构,真的假的?”--4.二叉树

1.对称二叉树 . - 力扣&#xff08;LeetCode&#xff09; 思路 &#xff1a; 1.设置两个队列l&#xff0c;r&#xff0c;先将root的左节点入l&#xff0c;右节点入r。 2.分别出队&#xff0c;若出队元素相同 Queuepush(&l, front->left); Queuepush(&l, front->…

调度器——DolphinScheduler讲解及安装教程

调度器——DolphinScheduler讲解及安装教程 一&#xff1a;基本讲解 Dolphin Scheduler 1、开源的分布式任务调度系统 2、支持多种任务类型&#xff0c;包括Shell、Spark、Hive等 3、灵活的任务调度功能和友好的Web界面&#xff0c;方便管理和监控任务的执行情况 架构 操作系…

idea 自动生成pojo类

找到这个View>Tool Windows>Database配置数据库 配置好后刷新&#xff0c;查看是否连接上表 然后找到 点击后选择你将要生成的pojo需要保存到哪个文件&#xff0c;然后再次点击&#xff0c;就生成好了&#xff0c;然后自己稍作修改即可使用该pojo类了

nginx的配置:TLSv1 TLSv1.1 被暴露不安全

要在 Nginx 配置中禁用不安全的 SSL 协议&#xff08;如 TLSv1 和 TLSv1.1&#xff09;&#xff0c;并仅启用更安全的协议&#xff08;如 TLSv1.2 和 TLSv1.3&#xff09;&#xff0c;您可以更新您的 Nginx 配置文件。下面是一个示例配置&#xff1a; # 位于 Nginx 配置文件 (…

Vue3可媲美Element Plus Tree组件实战之移除节点

Element Plus Tree自定义节点内容示例中介绍了移除节点的用法&#xff0c;个人觉得作为提供给用户API&#xff0c;应该遵循迪米特法则&#xff0c;把功能实现的细节封装在组件内部&#xff0c;而提供给用户最简单的操作方式&#xff0c;同时在此基础上支持用户的扩展。 因此&a…

【python学习】思考-如何在PyCharm中编写一个简单的Flask应用示例以及如何用cProfile来对Python代码进行性能分析

引言 Python中有两个流行的Web框架&#xff1a;Django和Flask。Django是一个高级的Python Web框架&#xff0c;它鼓励快速开发和干净、实用的设计&#xff1b;Flask是一个轻量级的Web应用框架&#xff0c;适用于小型到大型应用。以下是使用Flask创建一个简单应用的基本步骤cPro…

从工业到航空:旋转花键跨行业的多样用途解析!

旋转花键是一种新型的高效传动元件&#xff0c;主要由内花键和外花键组成。内花键和外花键之间放置着一排排滚珠&#xff0c;当内花键和外花键相对旋转时&#xff0c;滚珠在内、外花键之间滚动&#xff0c;从而实现动力的传递。 旋转花键的基本功能主要是用于连接轴和套的旋转部…

前端位运算运用场景小知识(权限相关)

前提&#xff1a;此篇结合AI、公司实际业务产出&#xff0c;背景是公司有个业务涉及权限&#xff0c;用位运算来控制的&#xff0c;比较新奇&#xff0c;所以记录一下(可能自己比较low) 前端js位运算一般实际的应用场景在哪 ai回答&#xff1a; 整数运算与性能优化&#xff…

mmdetection训练后评估指标,验证Loss

项目场景&#xff1a; 对mmdetection框架下训练好的log.json文件进行评估。 问题描述 使用框架底下自带的评估文件&#xff0c;不能对loss进行评估。也就是文件&#xff1a;tools/analysis_tools/analyze_logs.py 解决方案&#xff1a; 自己做了评估loss的代码&#xff0c;目…

力扣94题(java语言)

题目 思路 使用一个栈来模拟递归的过程&#xff0c;以非递归的方式完成中序遍历(使用栈可以避免递归调用的空间消耗)。 遍历顺序步骤&#xff1a; 遍历左子树访问根节点遍历右子树 package algorithm_leetcode;import java.util.ArrayList; import java.util.List; import…

重磅发布:OpenAI宣布推出AI驱动的搜索引擎SearchGPT,将与Google和Perplexity展开竞争|TodayAI

OpenAI宣布推出其备受期待的AI驱动搜索引擎SearchGPT。该搜索引擎能够实时访问互联网信息&#xff0c;并将作为原型在有限范围内发布&#xff0c;计划最终将其功能整合到ChatGPT中。 SearchGPT的功能特点 SearchGPT是一个具有实时互联网信息访问能力的AI驱动搜索引擎。它的界面…

轨道式智能巡检机器人,助力综合管廊安全运维

1 引言 当前城市综合管廊建设已经成为世界范围内的发展趋势&#xff0c;2017年5月住建部、发改委联合发布《全国城市市政基础设施建设“十三五”规划》&#xff0c;截至2017年4月底国内地下综合管廊试点项目已开工建设687 km&#xff0c;建成廊体260 km&#xff0c;完成投资40…