Numpy функция ошибок

class numpy.errstate(**kwargs)[source]#

Context manager for floating-point error handling.

Using an instance of errstate as a context manager allows statements in
that context to execute with a known error handling behavior. Upon entering
the context the error handling is set with seterr and seterrcall, and
upon exiting it is reset to what it was before.

Changed in version 1.17.0: errstate is also usable as a function decorator, saving
a level of indentation if an entire function is wrapped.
See contextlib.ContextDecorator for more information.

Parameters:
kwargs{divide, over, under, invalid}

Keyword arguments. The valid keywords are the possible floating-point
exceptions. Each keyword should have a string value that defines the
treatment for the particular error. Possible values are
{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}.

Notes

For complete documentation of the types of floating-point exceptions and
treatment options, see seterr.

Examples

>>> olderr = np.seterr(all='ignore')  # Set error handling to known state.
>>> np.arange(3) / 0.
array([nan, inf, inf])
>>> with np.errstate(divide='warn'):
...     np.arange(3) / 0.
array([nan, inf, inf])
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
...     np.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt

Outside the context the error handling behavior has not changed:

>>> np.geterr()
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}

Methods

Контекстный менеджер для обработки ошибок с плавающей точкой.

Использование экземпляра errstate в качестве диспетчера контекста позволяет операторам в этом контексте выполняться с известным поведением обработки ошибок. При входе в контекст обработка ошибок устанавливается с помощью seterr и seterrcall , а после выхода она сбрасывается до того, что было раньше.

Изменено в версии 1.17.0: errstate также можно использовать в качестве декоратора функции, сохраняя уровень отступа, если вся функция обернута. См. contextlib.ContextDecorator для получения дополнительной информации.

Parameters
kwargs {разделить, больше, меньше, недействительно}

Аргументы ключевых слов.Допустимые ключевые слова-это возможные исключения с плавающей точкой.Каждое ключевое слово должно иметь строковое значение,определяющее лечение конкретной ошибки.Возможные значения:{‘ignore’,’warn’,’raise’,’call’,’print’,’log’}.

Notes

Полную документацию о типах исключений с плавающей запятой и вариантах обработки см. В seterr .

Examples

>>> olderr = np.seterr(all='ignore')  
>>> np.arange(3) / 0.
array([nan, inf, inf])
>>> with np.errstate(divide='warn'):
...     np.arange(3) / 0.
array([nan, inf, inf])
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
...     np.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt

Вне контекста поведение при обработке ошибок не изменилось:

>>> np.geterr()
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}

Methods

Context manager for floating-point error handling.

Using an instance of errstate as a context manager allows statements in that context to execute with a known error handling behavior. Upon entering the context the error handling is set with seterr and seterrcall, and upon exiting it is reset to what it was before.

Changed in version 1.17.0: errstate is also usable as a function decorator, saving a level of indentation if an entire function is wrapped. See contextlib.ContextDecorator for more information.

Parameters
kwargs{divide, over, under, invalid}

Keyword arguments. The valid keywords are the possible floating-point exceptions. Each keyword should have a string value that defines the treatment for the particular error. Possible values are {‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}.

Notes

For complete documentation of the types of floating-point exceptions and treatment options, see seterr.

Examples

>>> olderr = np.seterr(all='ignore')  # Set error handling to known state.
>>> np.arange(3) / 0.
array([nan, inf, inf])
>>> with np.errstate(divide='warn'):
...     np.arange(3) / 0.
array([nan, inf, inf])
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
...     np.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt

Outside the context the error handling behavior has not changed:

>>> np.geterr()
{'divide': 'ignore', 'over': 'ignore', 'under': 'ignore', 'invalid': 'ignore'}

Methods

class numpy.errstate(**kwargs)[source]

Context manager for floating-point error handling.

Using an instance of errstate as a context manager allows statements in
that context to execute with a known error handling behavior. Upon entering
the context the error handling is set with seterr and seterrcall, and
upon exiting it is reset to what it was before.

Parameters:

kwargs : {divide, over, under, invalid}

Keyword arguments. The valid keywords are the possible floating-point
exceptions. Each keyword should have a string value that defines the
treatment for the particular error. Possible values are
{‘ignore’, ‘warn’, ‘raise’, ‘call’, ‘print’, ‘log’}.

Notes

The with statement was introduced in Python 2.5, and can only be used
there by importing it: from __future__ import with_statement. In
earlier Python versions the with statement is not available.

For complete documentation of the types of floating-point exceptions and
treatment options, see seterr.

Examples

>>> from __future__ import with_statement  # use 'with' in Python 2.5
>>> olderr = np.seterr(all='ignore')  # Set error handling to known state.
>>> np.arange(3) / 0.
array([ NaN,  Inf,  Inf])
>>> with np.errstate(divide='warn'):
...     np.arange(3) / 0.
...
__main__:2: RuntimeWarning: divide by zero encountered in divide
array([ NaN,  Inf,  Inf])
>>> np.sqrt(-1)
nan
>>> with np.errstate(invalid='raise'):
...     np.sqrt(-1)
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
FloatingPointError: invalid value encountered in sqrt

Outside the context the error handling behavior has not changed:

>>> np.geterr()
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn',
'under': 'ignore'}

For any scientific measurement, accurate accounting for errors is nearly as important, if not more important, than accurate reporting of the number itself.
For example, imagine that I am using some astrophysical observations to estimate the Hubble Constant, the local measurement of the expansion rate of the Universe.
I know that the current literature suggests a value of around 71 (km/s)/Mpc, and I measure a value of 74 (km/s)/Mpc with my method. Are the values consistent? The only correct answer, given this information, is this: there is no way to know.

Suppose I augment this information with reported uncertainties: the current literature suggests a value of around 71 $\pm$ 2.5 (km/s)/Mpc, and my method has measured a value of 74 $\pm$ 5 (km/s)/Mpc. Now are the values consistent? That is a question that can be quantitatively answered.

In visualization of data and results, showing these errors effectively can make a plot convey much more complete information.

Basic Errorbars¶

A basic errorbar can be created with a single Matplotlib function call:

Here the fmt is a format code controlling the appearance of lines and points, and has the same syntax as the shorthand used in plt.plot, outlined in Simple Line Plots and Simple Scatter Plots.

In addition to these basic options, the errorbar function has many options to fine-tune the outputs.
Using these additional options you can easily customize the aesthetics of your errorbar plot.
I often find it helpful, especially in crowded plots, to make the errorbars lighter than the points themselves:

In addition to these options, you can also specify horizontal errorbars (xerr), one-sided errorbars, and many other variants.
For more information on the options available, refer to the docstring of plt.errorbar.

Continuous Errors¶

In some situations it is desirable to show errorbars on continuous quantities.
Though Matplotlib does not have a built-in convenience routine for this type of application, it’s relatively easy to combine primitives like plt.plot and plt.fill_between for a useful result.

Here we’ll perform a simple Gaussian process regression, using the Scikit-Learn API (see Introducing Scikit-Learn for details).
This is a method of fitting a very flexible non-parametric function to data with a continuous measure of the uncertainty.
We won’t delve into the details of Gaussian process regression at this point, but will focus instead on how you might visualize such a continuous error measurement:

We now have xfit, yfit, and dyfit, which sample the continuous fit to our data.
We could pass these to the plt.errorbar function as above, but we don’t really want to plot 1,000 points with 1,000 errorbars.
Instead, we can use the plt.fill_between function with a light color to visualize this continuous error:

Note what we’ve done here with the fill_between function: we pass an x value, then the lower y-bound, then the upper y-bound, and the result is that the area between these regions is filled.

The resulting figure gives a very intuitive view into what the Gaussian process regression algorithm is doing: in regions near a measured data point, the model is strongly constrained and this is reflected in the small model errors.
In regions far from a measured data point, the model is not strongly constrained, and the model errors increase.

For more information on the options available in plt.fill_between() (and the closely related plt.fill() function), see the function docstring or the Matplotlib documentation.

Finally, if this seems a bit too low level for your taste, refer to Visualization With Seaborn, where we discuss the Seaborn package, which has a more streamlined API for visualizing this type of continuous errorbar.

Понравилась статья? Поделить с друзьями:
  • Numpy среднеквадратичная ошибка
  • Numpy ndarray object is not callable ошибка
  • Ntdsutil ошибка при синтаксическом разборе ввода неправильный синтаксис
  • Numplate light ошибка bmw
  • Ntdll dll ошибка windows 7 x64