如何在纽比处理一个np.RankWarning?

2024-05-20 11:12:32 发布

您现在位置:Python中文网/ 问答频道 /正文

尽管我是新手,我还是会尽我所能地说出来,请你宽大处理:

我使用下面的代码找到最适合我从物理温度传感器动态读取的数据的多项式:

coefficients = numpy.polyfit(x, y, 2)
polynomial = numpy.poly1d(self.coefficients)

#and then I using matpltlib to plot
matplotlib.pyplot.plot(self.x, self.y, 'o')

有时,我接收不到足够的数据,因此会出现错误:

RankWarning:Polyfit可能是条件不好的警告。warn(msg,RankWarning)

很公平。以下是我需要做的(但不能):如果我从polyfit得到异常,那么我不想尝试绘制。换句话说,当我得到异常时,我需要采取行动,而不仅仅是忽略异常。我在numpy文档中找到的一些代码仅仅忽略了异常

import warnings
warnings.simplefilter('ignore', np.RankWarning)

我试过使用try except,但在这种情况下不起作用(我对不同类型的异常有一个基本的理解,尽管我计划很快阅读更多内容)。

谢谢你的建议!


Tags: 数据代码selfnumpyplot物理动态温度传感器
1条回答
网友
1楼 · 发布于 2024-05-20 11:12:32
import numpy as np
import warnings
x = [1]
y = [2]

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        coefficients = np.polyfit(x, y, 2)
    except np.RankWarning:
        print "not enought data"

相关问题 更多 >