3-3-2-11. Arithmetic operations and Broadcasting
In this video, we will only be looking at element-wise operations.
Consider these two rank one arrays.
We can perform basic element-wise operations using arithmetic symbols or functions.
Both of these forms will do the same operation.
The only difference is that if you use this function approach,
the functions usually have options that you can tweak using keywords and methods.
Let’s also try element-wise subtraction, multiplication, and division.
Again, these also have the function approach.
In order to complete these operations,
NumPy sometimes uses something called broadcasting.
Broadcasting is a term used to describe how NumPy handles
element-wise arithmetic operations with arrays of different shapes.
An important thing to note is that,
since we are doing element-wise operations,
the arrays being operated on must have the same shape or be broadcastable.
We’ll talk more about this in a minute.
Let’s perform the same element-wise arithmetic operations on rank two arrays.
Again, remember that in order to do these operations,
the arrays being operated on must have the same shape or be broadcastable.
Here are two two-by-two matrices.
Let’s do the same arithmetic operations using the symbol notation.
We can also apply mathematical functions such
as square root to all the elements of an array at once.
Here’s that rank one array we were using before.
We can get the square root of each element like this,
and the exponential of each like this.
And also, each element to the power of two.
Another great feature of NumPy is its statistical functions.
Statistical functions such as mean,
provide us with statistical information about the elements in an array.
Let’s see some examples.
Here is that rank two array again.
We can get the average of the matrix like this,
as well as the averages of individual rows and columns like this.
We can do the same for statistics like the sum,
and others like the standard deviation,
median, maximum, and minimum.
Finally, let’s see how NumPy can add single numbers to
all the elements of a NumPy array without the use of complicated loops.
Here’s our rank two array again.
We can add three to each element like this,
and subtract three from each like this.
Multiply each by three,
and divide each by three.
In the examples above,
NumPy is working behind the scenes to broadcast
three along the X array so that they have the same shape.
This allows us to add three to each element of X in just one line of code.
Subject to certain constraints,
NumPy can do the same for two NumPy arrays of different shapes.
Consider this three-by-three array Y,
and this one-by-three array X.
If we do Y plus X, this adds zero,
to the first column in Y, one,
to the second column in Y,
and two, to the third column in Y.
As before, NumPy is able to add a one-by-three array to
a three-by-three array by broadcasting the smaller array along the big array,
so that they have compatible shapes.
In general, NumPy can do this provided that the smaller array,
such as the one-by-three array,
can be expanded to fit the shape of the larger array,
so that the resulting broadcast is unambiguous.
We can do the same with a three-by-one array.
This adds zero, the first row of Y,
one, to the second row of Y,
and two, to the third row of Y. Checkout the NumPy
documentation for more information on broadcasting and its rules.
NumPy가 배열에서 산술 연산을 수행하는 방법을 살펴보겠습니다.
NumPy는 요소별 연산을 허용합니다.
뿐만 아니라 매트릭스 연산.
이 비디오에서는 요소별 연산만 살펴보겠습니다.
이 두 개의 1순위 어레이를 고려하십시오.
산술 기호나 함수를 사용하여 기본적인 요소별 연산을 수행할 수 있습니다.
이 두 형식은 모두 동일한 작업을 수행합니다.
유일한 차이점은 이 함수 접근 방식을 사용하는 경우
함수에는 일반적으로 키워드와 방법을 사용하여 조정할 수 있는 옵션이 있습니다.
요소별 뺄셈, 곱셈 및 나눗셈도 시도해 보겠습니다.
다시 말하지만, 이것들은 또한 기능적 접근을 가지고 있습니다.
이러한 작업을 완료하려면
NumPy는 때때로 방송이라는 것을 사용합니다.
브로드캐스팅은 NumPy가 처리하는 방법을 설명하는 데 사용되는 용어입니다.
다양한 모양의 배열을 사용한 요소별 산술 연산.
주목해야 할 중요한 점은,
요소별 연산을 수행하기 때문에
작동 중인 어레이는 모양이 같거나 브로드캐스트 가능해야 합니다.
잠시 후에 이에 대해 더 이야기하겠습니다.
2순위 배열에 대해 동일한 요소별 산술 연산을 수행해 보겠습니다.
다시 말하지만, 이러한 작업을 수행하려면
작동 중인 어레이는 모양이 같거나 브로드캐스트 가능해야 합니다.
다음은 두 개의 2×2 행렬입니다.
기호 표기법을 사용하여 동일한 산술 연산을 수행해 보겠습니다.
다음과 같은 수학 함수를 적용할 수도 있습니다.
한 번에 배열의 모든 요소에 대한 제곱근으로.
여기 우리가 이전에 사용했던 1순위 배열이 있습니다.
다음과 같이 각 요소의 제곱근을 얻을 수 있습니다.
그리고 각각의 지수는 이와 같습니다.
또한, 각 요소는 2의 거듭제곱입니다.
NumPy의 또 다른 훌륭한 기능은 통계 기능입니다.
평균,
배열의 요소에 대한 통계 정보를 제공합니다.
몇 가지 예를 살펴보겠습니다.
다음은 2순위 배열입니다.
우리는 다음과 같이 행렬의 평균을 얻을 수 있습니다.
이와 같은 개별 행과 열의 평균뿐만 아니라.
합계와 같은 통계에 대해서도 동일한 작업을 수행할 수 있습니다.
표준편차와 같은 다른 것들,
중앙값, 최대값, 최소값.
마지막으로 NumPy가 단일 숫자를 추가하는 방법을 살펴보겠습니다.
복잡한 루프를 사용하지 않고 NumPy 배열의 모든 요소.
다음은 2순위 배열입니다.
다음과 같이 각 요소에 3개를 추가할 수 있습니다.
그리고 이와 같이 각각에서 3을 뺍니다.
각각에 3을 곱하고,
그리고 각각을 3으로 나눕니다.
위의 예에서,
NumPy는 방송을 위해 무대 뒤에서 일하고 있습니다.
같은 모양이 되도록 X 배열을 따라 세 개를 만듭니다.
이를 통해 단 한 줄의 코드에서 X의 각 요소에 3개를 추가할 수 있습니다.
특정 제약 조건에 따라
NumPy는 모양이 다른 두 개의 NumPy 배열에 대해 동일한 작업을 수행할 수 있습니다.
이 3×3 배열 Y를 고려하십시오.
그리고 이 1×3 배열 X.
Y에 X를 더하면 0이 추가되고
Y의 첫 번째 열에 하나,
Y의 두 번째 열로,
그리고 2, Y의 세 번째 열.
이전과 마찬가지로 NumPy는 1×3 배열을 추가할 수 있습니다.
큰 배열을 따라 작은 배열을 브로드캐스트하여 3×3 배열,
호환되는 모양을 갖도록 합니다.
일반적으로 NumPy는 더 작은 배열,
1×3 배열과 같이
더 큰 배열의 모양에 맞게 확장할 수 있습니다.
결과 브로드캐스트가 모호하지 않도록 합니다.
3×1 배열로 동일한 작업을 수행할 수 있습니다.
이것은 Y의 첫 번째 행인 0을 추가합니다.
하나, Y의 두 번째 행에,
그리고 2, Y의 세 번째 행에. NumPy 확인
방송 및 규칙에 대한 자세한 내용은 문서를 참조하십시오.
Arithmetic operations and Broadcasting
We have reached the last lesson in this Introduction to NumPy. In this last lesson we will see how NumPy does arithmetic operations on ndarrays. NumPy allows element-wise operations on ndarrays as well as matrix operations. In this lesson we will only be looking at element-wise operations on ndarrays. In order to do element-wise operations, NumPy sometimes uses something called Broadcasting. Broadcasting is the term used to describe how NumPy handles element-wise arithmetic operations with ndarrays of different shapes. For example, broadcasting is used implicitly when doing arithmetic operations between scalars and ndarrays.
Let’s start by doing element-wise addition, subtraction, multiplication, and division, between ndarrays. To do this, NumPy provides a functional approach, where we use functions such as np.add()
, or by using arithmetic symbols, such as +
, that resembles more how we write mathematical equations. Both forms will do the same operation, the only difference is that if you use the function approach, the functions usually have options that you can tweak using keywords. It is important to note that when performing element-wise operations, the shapes of the ndarrays being operated on, must have the same shape or be broadcastable. We’ll explain more about this later in this lesson. Let’s start by performing element-wise arithmetic operations on rank 1 ndarrays:
Example 1. Element-wise arithmetic operations on 1-D arrays
# We create two rank 1 ndarrays x = np.array([1,2,3,4]) y = np.array([5.5,6.5,7.5,8.5]) # We print x print() print('x = ', x) # We print y print() print('y = ', y) print() # We perfrom basic element-wise operations using arithmetic symbols and functions print('x + y = ', x + y) print('add(x,y) = ', np.add(x,y)) print() print('x - y = ', x - y) print('subtract(x,y) = ', np.subtract(x,y)) print() print('x * y = ', x * y) print('multiply(x,y) = ', np.multiply(x,y)) print() print('x / y = ', x / y) print('divide(x,y) = ', np.divide(x,y))
x = [1 2 3 4]
y = [ 5.5 6.5 7.5 8.5]
x + y = [ 6.5 8.5 10.5 12.5] add(x,y) = [ 6.5 8.5 10.5 12.5]
x – y = [-4.5 -4.5 -4.5 -4.5] subtract(x,y) = [-4.5 -4.5 -4.5 -4.5]
x * y = [ 5.5 13. 22.5 34. ] multiply(x,y) = [ 5.5 13. 22.5 34. ]
x / y = [ 0.18181818 0.30769231 0.4 0.47058824] divide(x,y) = [ 0.18181818 0.30769231 0.4 0.47058824]
We can also perform the same element-wise arithmetic operations on rank 2 ndarrays. Again, remember that in order to do these operations the shapes of the ndarrays being operated on, must have the same shape or be broadcastable.
Example 2. Element-wise arithmetic operations on a 2-D array (Same shape)
# We create two rank 2 ndarrays X = np.array([1,2,3,4]).reshape(2,2) Y = np.array([5.5,6.5,7.5,8.5]).reshape(2,2) # We print X print() print('X = \n', X) # We print Y print() print('Y = \n', Y) print() # We perform basic element-wise operations using arithmetic symbols and functions print('X + Y = \n', X + Y) print() print('add(X,Y) = \n', np.add(X,Y)) print() print('X - Y = \n', X - Y) print() print('subtract(X,Y) = \n', np.subtract(X,Y)) print() print('X * Y = \n', X * Y) print() print('multiply(X,Y) = \n', np.multiply(X,Y)) print() print('X / Y = \n', X / Y) print() print('divide(X,Y) = \n', np.divide(X,Y))
X = [[1 2] [3 4]]
Y = [[ 5.5 6.5] [ 7.5 8.5]]
X + Y = [[ 6.5 8.5] [ 10.5 12.5]]
add(X,Y) = [[ 6.5 8.5] [ 10.5 12.5]]
X – Y = [[-4.5 -4.5] [-4.5 -4.5]]
subtract(X,Y) = [[-4.5 -4.5] [-4.5 -4.5]]
X * Y = [[ 5.5 13. ] [ 22.5 34. ]]
multiply(X,Y) = [[ 5.5 13. ] [ 22.5 34. ]]
X / Y = [[ 0.18181818 0.30769231] [ 0.4 0.47058824]]
divide(X,Y) = [[ 0.18181818 0.30769231] [ 0.4 0.47058824]]
We can also apply mathematical functions, such as sqrt(x)
, to all elements of an ndarray at once.
Example 3. Additional mathematical functions
# We create a rank 1 ndarray x = np.array([1,2,3,4]) # We print x print() print('x = ', x) # We apply different mathematical functions to all elements of x print() print('EXP(x) =', np.exp(x)) print() print('SQRT(x) =',np.sqrt(x)) print() print('POW(x,2) =',np.power(x,2)) # We raise all elements to the power of 2
x = [1 2 3 4]
EXP(x) = [ 2.71828183 7.3890561 20.08553692 54.59815003]
SQRT(x) = [ 1. 1.41421356 1.73205081 2. ]
POW(x,2) = [ 1 4 9 16]
Another great feature of NumPy is that it has a wide variety of statistical functions. Statistical functions provide us with statistical information about the elements in an ndarray.
Note – Most of the statistical operations can be done using either a function or an equivalent method. For example, both numpy.mean function and Example 4. Statistical functions
# We create a 2 x 2 ndarray X = np.array([[1,2], [3,4]]) # We print x print() print('X = \n', X) print() print('Average of all elements in X:', X.mean()) print('Average of all elements in the columns of X:', X.mean(axis=0)) print('Average of all elements in the rows of X:', X.mean(axis=1)) print() print('Sum of all elements in X:', X.sum()) print('Sum of all elements in the columns of X:', X.sum(axis=0)) print('Sum of all elements in the rows of X:', X.sum(axis=1)) print() print('Standard Deviation of all elements in X:', X.std()) print('Standard Deviation of all elements in the columns of X:', X.std(axis=0)) print('Standard Deviation of all elements in the rows of X:', X.std(axis=1)) print() print('Median of all elements in X:', np.median(X)) print('Median of all elements in the columns of X:', np.median(X,axis=0)) print('Median of all elements in the rows of X:', np.median(X,axis=1)) print() print('Maximum value of all elements in X:', X.max()) print('Maximum value of all elements in the columns of X:', X.max(axis=0)) print('Maximum value of all elements in the rows of X:', X.max(axis=1)) print() print('Minimum value of all elements in X:', X.min()) print('Minimum value of all elements in the columns of X:', X.min(axis=0)) print('Minimum value of all elements in the rows of X:', X.min(axis=1))X = [[1 2] [3 4]]
Average of all elements in X: 2.5 Average of all elements in the columns of X: [ 2. 3.] Average of all elements in the rows of X: [ 1.5 3.5]
Sum of all elements in X: 10 Sum of all elements in the columns of X: [4 6] Sum of all elements in the rows of X: [3 7]
Standard Deviation of all elements in X: 1.11803398875 Standard Deviation of all elements in the columns of X: [ 1. 1.] Standard Deviation of all elements in the rows of X: [ 0.5 0.5]
Median of all elements in X: 2.5 Median of all elements in the columns of X: [ 2. 3.] Median of all elements in the rows of X: [ 1.5 3.5]
Maximum value of all elements in X: 4 Maximum value of all elements in the columns of X: [3 4] Maximum value of all elements in the rows of X: [2 4]
Minimum value of all elements in X: 1 Minimum value of all elements in the columns of X: [1 2] Minimum value of all elements in the rows of X: [1 3]
Finally, let’s see how NumPy can add single numbers to all the elements of an ndarray without the use of complicated loops.
Example 5. Change value of all elements of an array
# We create a 2 x 2 ndarray X = np.array([[1,2], [3,4]]) # We print x print() print('X = \n', X) print() print('3 * X = \n', 3 * X) print() print('3 + X = \n', 3 + X) print() print('X - 3 = \n', X - 3) print() print('X / 3 = \n', X / 3)X = [[1 2] [3 4]]
3 * X = [[ 3 6] [ 9 12]]
3 + X = [[4 5] [6 7]]
X – 3 = [[-2 -1] [ 0 1]]
X / 3 = [[ 0.33333333 0.66666667] [ 1. 1.33333333]]
In the examples above, NumPy is working behind the scenes to broadcast
3
along the ndarray so that they have the same shape. This allows us to add 3 to each element ofX
with just one line of code.Subject to certain constraints, Numpy can do the same for two ndarrays of different shapes, as we can see below.
Example 6. Arithmetic operations on 2-D arrays (Compatible shape)
# We create a rank 1 ndarray x = np.array([1,2,3]) # We create a 3 x 3 ndarray Y = np.array([[1,2,3],[4,5,6],[7,8,9]]) # We create a 3 x 1 ndarray Z = np.array([1,2,3]).reshape(3,1) # We print x print() print('x = ', x) print() # We print Y print() print('Y = \n', Y) print() # We print Z print() print('Z = \n', Z) print() print('x + Y = \n', x + Y) print() print('Z + Y = \n',Z + Y)x = [1 2 3]
Y = [[1 2 3] [4 5 6] [7 8 9]]
Z = [[1] [2] [3]]
x + Y = [[ 2 4 6] [ 5 7 9] [ 8 10 12]]
Z + Y = [[ 2 3 4] [ 6 7 8] [10 11 12]]
As before, NumPy is able to add 1 x 3 and 3 x 1 ndarrays to 3 x 3 ndarrays by broadcasting the smaller ndarrays along the big ndarray so that they have compatible shapes. In general, NumPy can do this provided that the smaller ndarray, such as the 1 x 3 ndarray in our example, can be expanded to the shape of the larger ndarray in such a way that the resulting broadcast is unambiguous.
Make sure you check out the NumPy Documentation for more information on Broadcasting and its rules: Broadcasting
Glossary of Mathematical Functions
- Refer to this list of NumPy Mathematical Functions to find the one you need.
Supporting Materials
댓글을 달려면 로그인해야 합니다.