numpy의 배열끼리 연산을 수행하는 방법들을 알아보자.
배열 간 사칙연산
- numpy는 shape이 같은 array간의 기본적인 사칙 연산을 지원한다.
- 같은 위치에 있는 element 값들끼리 연산한다. (element-wise operation)
test_a = np.array([[1,2,3], [4,5,6]], float)
print(test_a + test_a)
# 출력:
# [[ 2. 4. 6.]
# [ 8. 10. 12.]]
print(test_a * test_a)
# 출력:
# [[ 1. 4. 9.]
# [16. 25. 36.]]
배열 간 비교연산
배열의 shape이 동일할 때 같은 위치에 있는 element간 비교 결과를 boolean type으로 반환한다.
test_a = np.array([1, 3, 0], float)
test_b = np.array([5, 2, 1], float)
print(test_a > test_b) # 출력: [False True False]
dot 함수
행렬 곱을 수행하는 함수이다.
test_a = np.arange(1, 7).reshape(2,3)
test_b = np.arange(7, 13).reshape(3,2)
print(test_a.dot(test_b))
# 출력:
# [[ 58 64]
# [139 154]]
broadcasting
크기가 다른 numpy 배열끼리 연산을 할 경우, 작은쪽의 배열이 자신의 원소를 복사해서 크기를 맞추어 연산을 진행한다.
1. matrix - scalar 간의 연산
test_matrix = np.array([[1,2,3], [4,5,6]], float)
scalar = 3
print(test_matrix + scalar) # test_matrix의 모든 원소에 3을 더한다.
# 출력:
# [[4. 5. 6.]
# [7. 8. 9.]]
print(test_matrix < 3) # test_matrix의 각 원소들이 3 미만인지 boolean type을 반환한다.
# 출력:
# [[ True True False]
# [False False False]]
2. matrix - vector 간의 연산
test_matrix = np.arange(1,13).reshape(4,3)
test_vector = np.arange(10,40,10)
print(test_matrix + test_vector)
# 출력:
# [[11 22 33]
# [14 25 36]
# [17 28 39]
# [20 31 42]]
test_matrix = np.array([[0],[10],[20],[30]])
test_vector = np.array([0, 1, 2])
print(test_matrix + test_vector)
# 출력:
# [[ 0 1 2]
# [10 11 12]
# [20 21 22]
# [30 31 32]]
transpose 함수 / T attribute
행렬의 전치행렬을 반환한다.
test_a = np.arange(1, 7).reshape(2, 3)
# 아래 두 코드는 같은 역할을 한다.
print(test_a.transpose())
print(test_a.T)
# 출력:
# [[1 4]
# [2 5]
# [3 6]]
'AI > Numpy' 카테고리의 다른 글
[Numpy] numpy 배열 원소 추출하기 (0) | 2023.03.08 |
---|---|
[Numpy] where 함수 사용법 (0) | 2023.03.08 |
[Numpy] numpy 배열 합치기 (0) | 2023.03.08 |
[Numpy] axis란 무엇일까? (0) | 2023.03.08 |
[Numpy] numpy 배열 생성하기 (0) | 2023.03.08 |