Help us understand the problem. What is going on with this article?

Numpyのブロードキャストについて

ブロードキャストとは

Numpyでは、次元の異なる行列同士の演算を行う際に自動で適切な形に変換してくれる機能が備わっており、これをブロードキャストと呼びます。
見たほうが早いと思うので以下に書きます。

A = np.array([1, 2, 3, 4, 5])
print(f'{"="*20}A')
print(A)
print(f'{"="*20}A-1')
# (1, 5)行列とスカラ値の演算
print(A - 1)
====================A
[1 2 3 4 5]
====================A-1
[0 1 2 3 4]

内部の挙動

Numpyでは次元の異なる行列の演算を行う際に自動で次元を合わせてくれています。
例えば、$(m, n) + (1, n)$の演算では$(1, n)$を拡張して$(m, n)$に変換しています。

$$
\begin{bmatrix}
1 & 2 & 3 & 4 & 5\\
6 & 7 & 8 &9 & 10
\end{bmatrix}
-
\begin{bmatrix}
1 & 2 & 3 & 4 & 5
\end{bmatrix}\\
=
\begin{bmatrix}
1 & 2 & 3 & 4 & 5\\
6 & 7 & 8 &9 & 10
\end{bmatrix}
-
\begin{bmatrix}
1 & 2 & 3 & 4 & 5\\
1 & 2 & 3 & 4 & 5
\end{bmatrix}
$$

A = np.array([
    [1, 2, 3, 4, 5],
    [6, 7, 8, 9, 10]])
B = np.array([1, 2, 3, 4, 5])
print(f'{"="*20}A')
print(A)
print(f'{"="*20}B')
print(B)
print(f'{"="*20}A - B')
print(A - B)
====================A
[[ 1  2  3  4  5]
 [ 6  7  8  9 10]]
====================B
[1 2 3 4 5]
====================A - B
[[0 0 0 0 0]
 [5 5 5 5 5]]
sssssssiiiiinnn
24歳です。 某SIerで働いてます。 Deep Learningの勉強中。
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした