Python NumPy ブロードキャスティング #1

株式会社リュディアです。今回から NumPy のブロードキャスティングについてまとめてみます。

まずブロードキャストという言葉自身の意味から見てみましょう。いわゆる英語のブロードキャストと IT系で使うブロードキャストの意味にもニュアンスの違いがあると思います。ここでは IT系で使うブロードキャストという言葉の意味を見てみましょう。

どうでしょうか?1か所から多数の場所にばらまくようなイメージを私は持っていますが皆さんそれぞれイメージしやすい理解をされるとよいと思います。

では NumPy でのブロードキャストについてです。NumPy におけるブロードキャスト、ブロードキャスティングとは何か?以下の NumPy のページを参考に見ていきましょう。

最初に以下のように書かれています。

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations. Subject to certain constraints, the smaller array is “broadcast” across the larger array so that they have compatible shapes. Broadcasting provides a means of vectorizing array operations so that looping occurs in C instead of Python. It does this without making needless copies of data and usually leads to efficient algorithm implementations. There are, however, cases where broadcasting is a bad idea because it leads to inefficient use of memory that slows computation.

(訳)Broadcasting という言葉は、numpyが算術演算時に形状の異なる配列をどのように扱うかを表します。一定の制約のもとで,小さい方の配列が大きい方の配列に"Broadcast"され両配列の形状が一致するようになります。Broadcasting は,配列操作をベクトル化する手段を提供し,Pythonの代わりにC言語でループ処理が行われるようになります。それ(= Boradcasting)は、データの不要なコピーを作ることなく、かつ通常は効率的なアルゴリズムの実装につながります。しかしながら Boradcasting が非効率なメモリ利用により演算速度が遅くなり悪い考え方になる場合もあります。

簡単に書くと 異なる形状の ndarray の演算を行う際に、プログラマがわざわざ形状を揃える必要はなく NumPy が特定の規則に従って演算しますということですね。もちろん何でも揃えることができるわけではなくて特定の規則があります。

次に General Boradcasting Rules に書かれている内容を見てみます。

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing (i.e. rightmost) dimensions and works its way left. Two dimensions are compatible when

1. they are equal, or
2. one of them is 1

If these conditions are not met, a ValueError: operands could not be broadcast together exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the size that is not 1 along each axis of the inputs.

(訳)2つの配列を操作するとき、それぞれの形状を要素ごとに比較します。後続の(つまり右端の)次元から始めて、左に向かって比較していきます。2つの次元が一致するとは

1. 2つの配列のサイズが等しい、または
2. 2つの配列のうちのいずれかのサイズが 1 の場合

これらの条件に合致しない場合は、ValueError: operands could not be broadcast together 例外が投げられ、配列の形状に互換性が無いと言われます。演算結果の配列のサイズは、入力の各軸に沿って 1 ではないサイズとなります。

今回は基本となるドキュメントから NumPy のブロードキャストについての説明の重要事項についてまとめました。今回はわかりづらかったかもしれません。具体的なコードによるまとめは次回から進めていきます。

Python NumPy ブロードキャスティング に関するまとめの続きは以下からどうぞ。

では、ごきげんよう。

この記事が気に入ったらサポートをしてみませんか?