0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

numpyで`inf - inf`が計算されると、"invalid value encountered in AAA"というメッセージを持つ`RuntimeWarning`が発生する

Last updated at Posted at 2024-05-17

環境

  • Python 3.12.1
  • numpy 1.26.4
  • pandas 2.2.2

背景

inf - infの結果はnanです。

In [30]: np.inf - np.inf
Out[30]: nan

numpyの関数内でinf-infが計算されると、RuntimeWarningが発生します。RuntimeWarningのメッセージはinvalid value encountered in reduceのようなメッセージです。どの関数(このメッセージではreduce関数)で"invalid value"に遭遇したかが記載されます。しかし、記載されている関数はnumpyの内部の関数です。警告メッセージには、実際にどのAPIで発生したかが記載されていません。

そこで、numpyで私がよく利用するAPIにおいて、inf - infが計算されたときにRuntimeWarningはどのようなメッセージになるかを、実際に試して確認しました。

また、pandasはnumpyのAPIを利用しているため、pandasを利用したときにも、invalid value encountered in reduceというRuntimeWarningは発生します。pandasでも、どのようなメッセージになるかを確認しました。

結果

numpy

np.sum

In [32]: np.sum([np.inf, -np.inf])
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/core/fromnumeric.py:88: RuntimeWarning: invalid value encountered in reduce
  return ufunc.reduce(obj, axis, dtype, out, **passkwargs)
Out[32]: nan

np.mean

In [33]: np.mean([np.inf, -np.inf])
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/core/_methods.py:118: RuntimeWarning: invalid value encountered in reduce
  ret = umr_sum(arr, axis, dtype, out, keepdims, where=where)
Out[33]: nan

np.std

In [80]: np.std([np.inf])
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/core/_methods.py:173: RuntimeWarning: invalid value encountered in subtract
  x = asanyarray(arr - arrmean)
Out[80]: nan

np.quantile

In [48]: np.quantile([np.inf], 0.5)
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/lib/function_base.py:4655: RuntimeWarning: invalid value encountered in subtract
  diff_b_a = subtract(b, a)
Out[48]: nan

In [49]: np.quantile([np.inf,1], 0.5)
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/lib/function_base.py:4658: RuntimeWarning: invalid value encountered in subtract
  subtract(b, diff_b_a * (1 - t), out=lerp_interpolation, where=t >= 0.5,
Out[49]: nan

In [50]: np.quantile([np.inf,1,2], 0.5)
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/lib/function_base.py:4657: RuntimeWarning: invalid value encountered in multiply
  lerp_interpolation = asanyarray(add(a, diff_b_a * t, out=out))
Out[50]: nan

In [51]: np.quantile([np.inf,1,2,3], 0.5)
Out[51]: 2.5

np.arrayによる引き算

In [44]: np.array(np.inf) - np.array(np.inf)
<ipython-input-44-c7e173d9e363>:1: RuntimeWarning: invalid value encountered in subtract
  np.array(np.inf) - np.array(np.inf)
Out[44]: nan
In [46]: a = np.array([1, np.inf])

In [47]: a - a
<ipython-input-47-65de83fc0c8b>:1: RuntimeWarning: invalid value encountered in subtract
  a - a
Out[47]: array([ 0., nan])

問題となるコードを具体的に教えてくれました。

np.add

In [79]: np.add(np.inf, -np.inf)
<ipython-input-79-e503359c7179>:1: RuntimeWarning: invalid value encountered in add
  np.add(np.inf, -np.inf)
Out[79]: nan

pandas

pd.Series.sum

In [34]: pd.Series([np.inf, -np.inf]).sum()
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/core/_methods.py:49: RuntimeWarning: invalid value encountered in reduce
  return umr_sum(a, axis, dtype, out, keepdims, initial, where)
Out[34]: nan

pd.Series.mean

In [87]: pd.Series([np.inf, -np.inf]).mean()
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/core/_methods.py:49: RuntimeWarning: invalid value encountered in reduce
  return umr_sum(a, axis, dtype, out, keepdims, initial, where)
Out[87]: nan

pd.Series.std

In [88]: pd.Series([np.inf]).std(ddof=0)
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/pandas/core/nanops.py:1016: RuntimeWarning: invalid value encountered in subtract
  sqr = _ensure_numeric((avg - values) ** 2)
Out[88]: nan

pd.Series.quantile


In [52]: pd.Series([np.inf]).quantile()
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/lib/function_base.py:4655: RuntimeWarning: invalid value encountered in subtract
  diff_b_a = subtract(b, a)
Out[52]: nan

In [54]: pd.Series([np.inf,1]).quantile()
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/lib/function_base.py:4658: RuntimeWarning: invalid value encountered in subtract
  subtract(b, diff_b_a * (1 - t), out=lerp_interpolation, where=t >= 0.5,
Out[54]: nan

In [55]: pd.Series([np.inf,1,2]).quantile()
/home/yuji/.pyenv/versions/3.12.1/lib/python3.12/site-packages/numpy/lib/function_base.py:4657: RuntimeWarning: invalid value encountered in multiply
  lerp_interpolation = asanyarray(add(a, diff_b_a * t, out=out))
Out[55]: nan

In [56]: pd.Series([np.inf,1,2,3]).quantile()
Out[56]: 2.5

pd.core.groupby.DataFrameGroupBy.sum

In [93]: df = pd.DataFrame({"key":["A","A"], "value":[np.inf, -np.inf]})

In [94]: df.groupby("key").sum()
Out[94]:
     value
key
A      NaN

RuntimeWarningは発生しませんでした。

pd.Series.sub

In [97]: pd.Series([np.inf]) - pd.Series([np.inf])
Out[97]:
0   NaN
dtype: float64

RuntimeWarningは発生しませんでした。

分かったこと

  • np.sum, np.meanでは、reduce関数でRuntimeWarningが発生する
  • np.stdでは、subtract関数でRuntimeWarningが発生する
  • pd.Series.sum, pd.Series.mean, pd.Series.stdでは、RuntimeWarningが発生する
    • pd.core.groupby.DataFrameGroupBy.sumでは、RuntimeWarningが発生しない
    • pd.Series.subではRuntimeWarningが発生しない

pandasでnumpyのRuntimeWarningが発生するかどうかは、pandasの実装次第なので、あまり気にしなくてよいと思います。ただ、このRuntimeWarningでバグに気づけたこともあるので、pandasでもRuntimeWarningが発生するケースと発生しないケースをまとめました。

参考サイト

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?