이 포스트는 Udacity - DLFND를 강의 내용을 필기 형식으로 작성 했습니다.
Numpy
이번 주제는 Numpy 입니다.
파이썬은 사용하기 편리하지만 느린게 단점입니다. 그래서, C 같은 동작이 빠른 언어로 작성된 라이브러리를 호출해서 사용 할 수 있도록 했습니다.
Numpy가 같은 원리로 작성된 라이브러리입니다. Numpy는 파이썬이 기본적으로 제공하는 계산보다 더 빠르고 효율적으로 동작합니다.
자세한 설명은 여기 Numpy Reference를 참고 하시기 바랍니다.
이 포스트에는 Numpy에서 자주 사용하는 코드 조각을 모아 두려고 합니다.
# Importing NumPy
import numpy as np
# Scalars (uint8, int8, uint16, int16)
s = np.array(5)
s.shape # ()
# Vector
v = np.array([1,2,3])
v.shape # (3,)
# Numpy Indexing
v[1:]
# Matrices
m = np.array([[1,2,3], [4,5,6], [7,8,9]])
m.shape # (3, 3)
# Tensors
t = np.array([[[[1],[2]],[[3],[4]],[[5],[6]]],[[[7],[8]],\
[[9],[10]],[[11],[12]]],[[[13],[14]],[[15],[16]],[[17],[17]]]])
t.shape # (3, 3, 2, 1)
# Changing Shapes
v = np.array([1,2,3,4])
x = v[:, None] # 같음 x = v.reshape(1,4)
x = v[:, None] # 같음 x = v.reshape(4,1)
# Numpy 스타일의 메트릭스 데이터 변경
values = [1,2,3,4,5]
values = np.array(values) + 5
# values 타입이 ndarray 라면
values += 5
x = np.multiply(some_array, 5)
# some_array 타입이 ndarray 라면
x = some_array * 5
m *= 0 # Element 모두 0 만들기
Important Reminders About Matrix Multiplication
- Order matters. Multiplying A•B is not the same as multiplying B•A.
= 행렬 곱의 순서가 변경되면 결과값은 바뀐다. - Data in the left matrix should be arranged as rows., while data in the right matrix should be arranged as columns.
= 왼쪽의 메트릭스 데이터 배열을 로우로, 오른쪽의 메트릭스 배열은 컬럼으로 되어야 한다.
Ex) = * ||
NumPy Matrix Multiplication
m = np.array([[1,2,3],[4,5,6]])
m
# displays the following result:
# array([[1, 2, 3],
# [4, 5, 6]])
n = m * 0.25
n
# displays the following result:
# array([[ 0.25, 0.5 , 0.75],
# [ 1. , 1.25, 1.5 ]])
m * n
# displays the following result:
# array([[ 0.25, 1. , 2.25],
# [ 4. , 6.25, 9. ]])
np.multiply(m, n) # 같음 to m * n
# displays the following result:
# array([[ 0.25, 1. , 2.25],
# [ 4. , 6.25, 9. ]])
a = np.array([[1,2,3,4],[5,6,7,8]])
a
# displays the following result:
# array([[1, 2, 3, 4],
# [5, 6, 7, 8]])
a.shape
# displays the following result:
# (2, 4)
b = np.array([[1,2,3],[4,5,6],[7,8,9],[10,11,12]])
b
# displays the following result:
# array([[ 1, 2, 3],
# [ 4, 5, 6],
# [ 7, 8, 9],
# [10, 11, 12]])
b.shape
# displays the following result:
# (4, 3)
c = np.matmul(a, b) # np.multiply(a, b) 와 동작이 다름
c
# displays the following result:
# array([[ 70, 80, 90],
# [158, 184, 210]])
c.shape
# displays the following result:
# (2, 3)
# Shape가 맞지 않으면 오류 발생
np.matmul(b, a)
# displays the following error:
# ValueError: shapes (4,3) and (2,4) not aligned: 3 (dim 1) != 2 (dim 0)
NumPy’s dot function
- matmul differs from dot in two important ways.
- matmul 은 dot과 2가지가 다르다.
-
- Multiplication by scalars is not allowed.
- scalars 값과 Multiplication이 허용되지 않는다.
-
- Stacks of matrices are broadcast together as if the matrices were elements.
- 요소가 메트릭스라면 메트릭스 스택이 브로드 케스팅 된다. (…어렵다.. 브로드캐스팅 개념 링크 추가)
-
Transpose
메트릭스에서 행과 열을 바꾸기
m = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
m
# displays the following result:
# array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
m.T
# displays the following result:
# array([[ 1, 5, 9],
# [ 2, 6, 10],
# [ 3, 7, 11],
# [ 4, 8, 12]])
MAX & MIN
메트릭스의 최대, 최소, 평균 값 구하기
m = np.array([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
m
# displays the following result:
# array([[ 1, 2, 3, 4],
# [ 5, 6, 7, 8],
# [ 9, 10, 11, 12]])
np.min(m) # 최소값
1
type(np.min(m))
<class 'numpy.int64'>
np.max(m) # 최대값
12
type(np.max(m))
<class 'numpy.int64'>
np.mean(m) # 평균값
6.5
type(np.mean(m))
<class 'numpy.float64'>