Web制作、Web開発の歩き方

初心者のためのDjango入門

■第13話:Numpyでの算術演算

(最終更新日:2023.06.07)

Djangoフレームワークのイメージ
この記事は4分で読めます!
(絵が小さい場合はスマホを横に)

「NumPyで計算しよう!」

前回、初期化や等間隔な値の作成、 インデックスやスライス、配列の変形などNumPy配列の基本的な操作について学んだ。 今回は数学的な操作である、四則演算からブロードキャスティング、内積、行列積の計算方法について学ぼう。


1.NumPy配列の四則演算

NumPyは、標準的な算術演算子(+、-、*、/など)を使用して配列に対する要素単位の演算を簡単に行うことができる。 下記に最も基本的な四則演算の例を示す。 見て分かるように、同じ要素の位置にある数値同士で計算を行っている。 ちなみに、四則演算以外にも、べき乗(**)、切り捨て除算(//)、剰余演算(%)なども使える。

NumPy配列の四則演算

NumPy配列の四則演算

さらに、NumPyは様々な数学的な関数(sin、cos、exp、logなど)を提供しており、これらの関数はすべて配列に対する要素単位の操作を可能にする。 例えば、np.sin(np.radians([0, 90]))とすれば、各要素はsin0°とsin90°に相当し、[0, 1]となる。

また、NumPyは比較演算子(<、>、<=、>=、==、!=)もサポートしており、これを使用して配列の要素を比較することができる。 これは配列のマスキング(指定した条件に合致する要素を抽出する)という強力な機能を可能にする。 例えば下記では、>=を用いることで、4以上の要素を抽出して1つの配列に格納している。

NumPy配列のマスキング

NumPy配列のマスキング

以上のような算術演算や数学的な関数を使用することで、NumPyは柔軟で効率的な数値計算を提供する。

2.NumPy配列のブロードキャスティング

NumPyにはブロードキャスティングという機能がある。 これは、形状の異なる配列間で算術演算を行うための強力なメカニズムである。 NumPyのブロードキャスティングルールにより、一部の条件下で小さな配列と大きな配列の間で演算を可能にする。 例えば下記では、aは1×3のnp配列、bは数値の2で、これらの積を計算することで、1×3の全ての要素に対して2を掛けることができている。 これは、要素数の等しいnp配列を用意しなくても、np配列全ての要素に同一の計算を行うことができることを意味し、 非常に効率的に計算できる。強力な計算機能である。

NumPy配列のブロードキャスティング

NumPy配列のブロードキャスティング

3.NumPy配列によるドット積(内積)、行列積の計算

NumPyは、線形代数で良く使われる内積や行列積の計算にも対応している。 以下がそれらに相当する。内積とはある成分方向に貢献した力の積で、 行列積はあるベクトルに対して線形変換したものである。線形変換では90°角度を回転させたりすることができる。 数学的手法について、この場で細かく説明する気はないが、そのような計算が簡単に行える。

NumPy配列のドット積

NumPy配列のドット積

NumPy配列の行列積

NumPy配列の行列積


4.まとめ

今回、NumPy配列の応用となる四則演算、三角関数を含めた数学的な演算、 ブロードキャスティング、内積、ドット積について説明した。 中でもブロードキャスティングは専門領域でなくても、計算の効率化として非常に威力を発揮する。 是非、覚えておいておこう。


▼参考図書、サイト

Numpy の dot() 関数は引数によって「ドット積(内積)」や「行列積」の計算になる  kakakakakku blog
Numpyのブロードキャストの挙動  Qiita
行列のかけ算のやり方まとめ。例題から分かる行列の積の考え方  アタリマエ!
マスキング  スキルアップTips


Intro to Django for Beginners ■Episode 13: Arithmetic Operations with NumPy (Last updated: 2023.06.07) Image of Django framework You can read this article in 4 minutes! (If the image looks small, try turning your phone sideways) “Let’s do calculations with NumPy!” In the previous article, we learned about basic operations with NumPy arrays, such as initialization, creating equally spaced values, indexing and slicing, and reshaping arrays. In this article, we’ll learn how to perform arithmetic operations, broadcasting, dot products, and matrix multiplication. [Table of Contents] Arithmetic Operations with NumPy Arrays Broadcasting in NumPy Dot Product and Matrix Multiplication with NumPy Arrays Summary 1. Arithmetic Operations with NumPy Arrays NumPy makes it easy to perform element-wise operations using standard arithmetic operators like +, -, *, and /. Below is a basic example of such operations. As you can see, the calculation is done between elements in the same position. In addition to these, you can also use exponentiation (**), floor division (//), and modulo (%). Arithmetic operations with NumPy Arithmetic Operations with NumPy Arrays Furthermore, NumPy offers various mathematical functions such as sin, cos, exp, log, etc., all of which operate element-wise on arrays. For example, `np.sin(np.radians([0, 90]))` will compute [0, 1], corresponding to sin(0°) and sin(90°). NumPy also supports comparison operators (<, >, <=, >=, ==, !=), which allow you to compare array elements. This enables a powerful feature called masking, where elements matching a condition can be extracted. In the example below, elements greater than or equal to 4 are extracted into a new array. Masking in NumPy Masking with NumPy Arrays With these arithmetic and mathematical operations, NumPy provides flexible and efficient numerical computation. 2. Broadcasting in NumPy NumPy has a feature called broadcasting, which allows arithmetic operations between arrays of different shapes. Thanks to NumPy’s broadcasting rules, operations can be performed between smaller and larger arrays under certain conditions. In the example below, `a` is a 1×3 NumPy array and `b` is the scalar value 2. When multiplied, each element in `a` is multiplied by 2. This means you can apply operations to all elements of an array without explicitly creating another array of the same size—an efficient and powerful capability. Broadcasting in NumPy Broadcasting with NumPy Arrays 3. Dot Product and Matrix Multiplication with NumPy Arrays NumPy also supports dot products and matrix multiplications, which are often used in linear algebra. The dot product represents the sum of products along a specific direction, while matrix multiplication can represent linear transformations such as rotation. We won’t go into the math in detail here, but NumPy makes these operations easy to perform. Dot Product in NumPy Dot Product with NumPy Arrays Matrix Multiplication in NumPy Matrix Multiplication with NumPy Arrays 4. Summary In this article, we covered advanced NumPy features including arithmetic operations, mathematical functions like trigonometry, broadcasting, dot product, and matrix multiplication. Broadcasting in particular is highly useful, even outside of specialized fields, for optimizing computation. Be sure to remember this powerful tool. ▼References   Numpy’s dot() function performs “dot product” or “matrix multiplication” depending on the input - kakakakakku blog   Behavior of Broadcasting in NumPy - Qiita   How to Multiply Matrices: Examples and Intuition - Atarimae!   Masking in NumPy - Skill-up Tips