NumPy Test Support で `testing.assert_equal()` を使いこなす:サンプルコードで理解を深める


testing.assert_equal() は、NumPy のテストサポートモジュール (numpy.testing) に含まれるアサーション関数の一つです。2つのオブジェクトが等しいかどうかを比較し、等しくない場合は AssertionError を発生させます。

この関数は、配列だけでなく、スカラー値、リスト、タプルなどの他の種類のオブジェクトにも使用できます。比較は逐次的に行われ、最初の不一致が見つかった時点で停止します。

構文

numpy.testing.assert_equal(actual, desired, **kwargs)

引数

  • kwargs: オプション引数。詳細は後述
  • desired: 期待される値
  • actual: 検証対象の実際の値

オプション引数

  • verbose: True の場合、詳細なエラーメッセージが出力されます。デフォルトは False です。
  • atol: 絶対許容誤差。デフォルトは 0 です。
  • rtol: 相対許容誤差。デフォルトは 1e-9 です。
  • check_dtype: True の場合、データ型も比較されます。デフォルトは False です。
  • equal_nan: True の場合、NaN は等しいとみなされます。デフォルトは False です。

import numpy as np

np.testing.assert_equal(1, 1)  # 成功
np.testing.assert_equal([1, 2, 3], [1, 2, 3])  # 成功
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3]))  # 成功

np.testing.assert_equal(1, 2)  # 失敗
np.testing.assert_equal([1, 2, 3], [1, 3, 2])  # 失敗
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 4]))  # 失敗

np.testing.assert_equal(1, 1.00000001, rtol=1e-9)  # 成功
np.testing.assert_equal(1, 1.000000011, rtol=1e-9)  # 失敗

testing.assert_equal()testing.assert_allclose() の違い

testing.assert_equal()testing.assert_allclose() は、どちらも2つのオブジェクトを比較するアサーション関数ですが、精度において違いがあります。

  • testing.assert_allclose(): 相対誤差と絶対誤差に基づいて近似等価性を比較します。つまり、2つのオブジェクトが許容範囲内であれば等しいとみなされます。
  • testing.assert_equal(): 厳密な等価性を比較します。つまり、2つのオブジェクトが完全に一致している必要があります。

一般的に、数値計算の結果を検証する場合は testing.assert_allclose() を使用する方が適切です。これは、浮動小数点演算の誤差の影響を考慮できるためです。



基本的な例

この例では、2つのスカラー値、2つの配列、2つのリストがそれぞれ等しいことを検証します。

import numpy as np
import numpy.testing as npt

np.testing.assert_equal(1, 1)
np.testing.assert_equal([1, 2, 3], [1, 2, 3])
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3]))
np.testing.assert_equal((1, 2, 3), (1, 2, 3))

オプション引数の使用

この例では、オプション引数を使用して、比較の精度を調整する方法を示します。

import numpy as np
import numpy.testing as npt

np.testing.assert_equal(1.00000001, 1, rtol=1e-9)  # 成功
np.testing.assert_equal(1.00000011, 1, rtol=1e-9)  # 失敗
np.testing.assert_equal(np.array([1.00000001, 2, 3]), np.array([1, 2, 3]), atol=1e-9)  # 成功
np.testing.assert_equal(np.array([1.0001, 2, 3]), np.array([1, 2, 3]), atol=1e-9)  # 失敗

カスタムメッセージの設定

この例では、err_msg オプション引数を使用して、カスタムエラーメッセージを設定する方法を示します。

import numpy as np
import numpy.testing as npt

try:
  np.testing.assert_equal(1, 2)
except AssertionError as err:
  print(err)  # カスタムエラーメッセージが出力される

異なるデータ型の比較

この例では、check_dtype オプション引数を使用して、データ型を比較する方法を示します。

import numpy as np
import numpy.testing as npt

np.testing.assert_equal(1, 1.0, check_dtype=False)  # 成功
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3]), check_dtype=False)  # 成功
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3.0]), check_dtype=False)  # 成功

np.testing.assert_equal(1, 1.0, check_dtype=True)  # 失敗
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3]), check_dtype=True)  # 成功
np.testing.assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3.0]), check_dtype=True)  # 失敗

NaN の比較

この例では、equal_nan オプション引数を使用して、NaN を比較する方法を示します。

import numpy as np
import numpy.testing as npt

np.testing.assert_equal(np.nan, np.nan, equal_nan=True)  # 成功
np.testing.assert_equal(np.nan, np.inf, equal_nan=True)  # 成功
np.testing.assert_equal(np.nan, np.nan, equal_nan=False)  # 失敗


np.allclose()

np.allclose()は、testing.assert_equal()と同様に2つのオブジェクトを比較しますが、許容誤差に基づいて近似等価性を検証します。これは、浮動小数点演算の結果を検証する場合などに役立ちます。

利点

  • 柔軟な許容誤差を設定できる
  • 浮動小数点演算の誤差を考慮できる

欠点

  • 厳密な等価性を検証できない
import numpy as np
import numpy.testing as npt

np.testing.assert_allclose(1.00000001, 1, rtol=1e-9)  # 成功
np.testing.assert_allclose(1.00000011, 1, rtol=1e-9)  # 失敗

カスタムアサーション関数

より複雑な比較ロジックが必要な場合は、カスタムアサーション関数を作成することができます。これは、assertステートメントと比較演算子を使用して行うことができます。

利点

  • 独自のエラーメッセージを出力できる
  • 柔軟な比較ロジックを実装できる

欠点

  • テストコードの読みやすさが低下する可能性がある
  • コードが冗長になる可能性がある
def my_assert_equal(actual, desired):
  if actual != desired:
    raise AssertionError(f"Actual: {actual}, Desired: {desired}")

my_assert_equal(1, 1)  # 成功
my_assert_equal([1, 2, 3], [1, 2, 3])  # 成功
my_assert_equal(np.array([1, 2, 3]), np.array([1, 2, 3]))  # 成功

サードパーティ製ライブラリ

pytestのようなサードパーティ製ライブラリを使用することもできます。これらのライブラリは、assert_equal()と同様の機能に加えて、より多くの機能を提供している場合があります。

利点

  • 使いやすい
  • 豊富な機能

欠点

  • 導入コストがかかる
  • NumPyに特化したものではない
import pytest

def test_my_function():
  actual = 1
  desired = 1
  assert actual == desired

手動による比較

シンプルな比較の場合は、手動で比較を行うこともできます。これは、デバッ グや簡単なテストを行う場合に役立ちます。

利点

  • コード量が少ない
  • シンプル
  • ミスが発生しやすい
  • 時間のかかる場合がある
actual = 1
desired = 1

if actual == desired:
  print("成功")
else:
  print("失敗")