- numpy.ndarray의 속성
- ndarray.ndim
- ndarray.ndim은 "Number of array dimensions(배열 차원의 수)"이다.
import numpy as np
scalar_np = np.array(1)
vector_np = np.array([1,2,3])
matrix_np = np.array([[1,2],[3,4]])
tensor_np = np.array([[[1, 2, 3],
[4, 5, 6]],
[[11, 12, 13],
[14, 15, 16]]])
print(scalar_np.ndim) # 0
print(vector_np.ndim) # 1
print(matrix_np.ndim) # 2
print(tensor_np.ndim) # 3
위 코드의 변수명으로 쓰이고 있는- Scalar(스칼라) : 0차원, 하나의 숫자- Vector(벡터) : 1차원, Scalar가 모인 배열- matrix(매트릭스) : 2차원, Vector가 모인 배열- tensor(텐서) : 3차원이상, (배열 일반을 나타내는 표현)
정도로 이해하면 되겠다.
그러한 맥락에서 ndarray.ndim은 해당 배열의 차원을 나타내는 ndarray의 속성이다.
- ndarray.shape
- ndarray.shape는 "Tuple of array dimensions(배열 차원의 튜플)"이다.
- shape의 뜻 그대로 "배열의 모양"으로 받아들여도 무방하겠다.
scalar_np = np.array(1)
vector_np = np.array([1,2,3])
matrix_np = np.array([[1,2],[3,4]])
tensor_np = np.array([[[1,2,3],
[4,5,6]],
[[7,8,9],
[10,11,12]]])
print(scalar_np.shape) # ()
print(vector_np.shape) # (3,)
print(matrix_np.shape) # (2, 2)
print(tensor_np.shape) # (2, 2, 3)
- scalar_np의 경우에는 scalar로서 0차원이므로, 배열의 모양이랄게 없으니 패스
- vector_np의 경우에는 "1,2,3"을 요소로 갖는 1차원 배열이므로,
요소의 개수인 3칸짜리 1차원 배열이라는 의미의 (3, )
- matrix_np의 경우에는 좀 더 보기편하게 펼쳐보면
$$ \left[\begin{matrix}1 & 2 \\3 & 4 \\\end{matrix}\right] $$
이러한 모양일 것이다. matrix_np가 2개의 요소를 가지고 있는데, 그 요소가 vector인 것이다.
첫번째 요소는 "1, 2"라는 1차원 배열, 두번째 요소는 "3, 4"라는 1차원 배열
이럴 경우, 2칸짜리 배열안의 각각의 칸에 2칸짜리 배열이 들어있으니 (2, 2)
- tensor_np의 경우에는 좀 더 보기 편하게 펼쳐보면
$$ \left[\begin{matrix}1 & 2 & 3 \\ 4 & 5 & 6 \\\end{matrix}\right] \left[\begin{matrix}7 & 8 & 9 \\ 10 & 11 & 12 \\\end{matrix}\right] $$
이러한 모양일 것이다. 앞내용과 연결지어 생각해보면, 앞선 matrix_np와 같은 2차원 배열이 2개인 경우이다.
tensor_np가 2개의 요소를 가지고 있고, 그 각각의 요소가 2개의 요소를 가지고 있고, 또, 그 각각의 요소가 3개의 요소를 가지고 있다.
이럴 경우, 2칸짜리 배열안에 2칸짜리 배열안에 3칸짜리 배열이므로, (2, 2, 3)
- ndarray.shape의 활용, ndarray.reshape()
- 다른 속성들보다 모양을 나타내는 shape 속성은 활용도가 높은 편이다.
- 이때 shape 속성을 활용하는 메소드가 reshape()이다.
예를 들어
a = np.array([[1,2,3],
[4,5,6],
[7,8,9]])
print(a.shape) # (3, 3)
b = np.linspace(11, 19, 9)
print(b) # [11. 12. 13. 14. 15. 16. 17. 18. 19.] 요소의 개수:9
b = b.reshape(a.shape)
print(b) # [[11. 12. 13.]
# [14. 15. 16.]
# [17. 18. 19.]]
print("result: ", a + b)
요소의 개수가 적절할 경우, 행렬의 모양을 바꿔 연산 처리를 하는 식으로 활용할 수 있다.
- ndarray.size
- ndarray.size는 "Number of elements in the array(배열의 요소 수)"이다.
- "the product of the array’s dimensions(배열의 차원들의 곱)"과 같습니다.
scalar_np = np.array(1)
vector_np = np.array([1,2,3])
matrix_np = np.array([[1,2],[3,4]])
tensor_np = np.array([[[1,2,3],
[4,5,6]],
[[7,8,9],
[10,11,12]]])
print(scalar_np.size, ' / ', scalar_np.shape) # 1 / ()
print(vector_np.size, ' / ', vector_np.shape) # 3 / (3,)
print(matrix_np.size, ' / ', matrix_np.shape) # 4 / (2, 2)
print(tensor_np.size, ' / ', tensor_np.shape) # 12 / (2, 2, 3)
- scalar_np의 경우에는 scalar로서 0차원이자, 하나의 숫자를 뜻하므로, size는 1이다.
- vector_np의 경우에는 "1,2,3"을 요소로 가지므로, size는 3이다.
- matrix_np의 경우에는 "1,2", "3,4"를 요소로 가지므로, size는 4이다.
- tensor_np의 경우에는 "1,2,3", "4,5,6", "7,8,9", "10,11,12"를 요소로 가지므로, size는 12이다.
- 이와 관련해서 규칙을 찾아보면, size는 shape로 나타내는 배열의 모양의 곱이다.
scalar_np : 하나의 정수 = 1
vector_np : 3개의 요소 * 1차원 = 3
matrix_np : 2개의 요소 안에 * 2개의 요소 = 4
tensor_np : 2개의 요소 안에 * 2개의 요소, 그리고 그안에 * 3개의 요소 = 12
- ndarray.dtype, itemsize
- ndarray.dtype은 "Data-type of the array’s elements(배열의 요소의 데이터타입)"이다.
- numpy는 데이터의 효율적인 활용을 위해 데이터 타입 설정을 지원한다.
- 작게는 MB단위, 크게는 TB단위 이상의 데이터를 처리하다보면, 메모리 공간의 낭비를 줄임으로서 속도를 높이고, 컴퓨터의 부하를 줄이는데 큰 도움이 될 수 있다.
int8_np = np.array([1,2,3], dtype=np.int8)
int16_np = np.array([1,2,3], dtype=np.int16)
int32_np = np.array([1,2,3], dtype=np.int32)
int64_np = np.array([1,2,3], dtype=np.int64)
uint8_np = np.array([1,2,3], dtype=np.uint8)
uint16_np = np.array([1,2,3], dtype=np.uint16)
uint32_np = np.array([1,2,3], dtype=np.uint32)
uint64_np = np.array([1,2,3], dtype=np.uint64)
float32_np = np.array([1,2,3], dtype=np.float32)
float64_np = np.array([1,2,3], dtype=np.float64)
print("Integer: {}/{}/{}/{}".format(int8_np.dtype, int16_np.dtype,
int32_np.dtype, int64_np.dtype))
print("Unsigned Integer: {}/{}/{}/{}".format(uint8_np.dtype, uint16_np.dtype,
uint32_np.dtype, uint64_np.dtype))
print("Floating Point: {}/{}".format(float32_np.dtype, float64_np.dtype))
이와 같이 Integer, Unsigned Integer, Floating point + 8,16,32,64 등의 데이터 타입을 지원하고
ones = np.ones(shape=(10, 5, 3, 2)) # np.ones() 요소들의 값을 1로 채운 배열 return
print("size:", ones.size) # size: 300(= 10 * 5 * 3 * 2)
print("dtype/itemsize: {} / {}\n".format(ones.dtype, ones.itemsize)) # dtype/itemsize: float64 / 8
m_cap = ones.size * ones.itemsize # 300 * 8 (byte)
print("메모리 용량 in B: {}B".format(m_cap)) # 2400B
print("메모리 용량 in KB: {}KB".format(m_cap/1024)) # 2.34375KB
print("메모리 용량 in MB: {}MB".format(m_cap/1024**2)) # 0.002288818359375MB
- dtype을 통해 배열의 datatype을 확인 및 설정할 수 있고, 그에 따라 itemsize가 결정된다.
- 위의 코드와 같이 배열 및 현재 프로그램에 할당된 nparray 객체들의 메모리 사용 용량을 확인 및 조절할 수 있다.
* 사실 nparray.size * nparray.itemsize는 nparray.nbytes와 동일하다.
이상으로, Numpy 클래스의 기본적인 속성에 대해 알아보았다.
다음 포스트에서는 수학적 처리를 돕는 좀 더 고차원의 데이터 생성 및 처리에 대해 알아보겠다.
* 참조
- https://numpy.org/doc/stable/reference/arrays.ndarray.html
The N-dimensional array (ndarray) — NumPy v1.21 Manual
Arithmetic and comparison operations on ndarrays are defined as element-wise operations, and generally yield ndarray objects as results. Each of the arithmetic operations (+, -, *, /, //, %, divmod(), ** or pow(), <<, >>, &, ^, |, ~) and the comparisons (=
numpy.org
- ICT이노베이션 강의 신경식 강사님 강의자료
'머신러닝 > Numpy' 카테고리의 다른 글
[Numpy] #6 브로드캐스팅(Broadcasting) 심화 기초문법 공부하기 6 (0) | 2021.09.29 |
---|---|
[Numpy] #5 요소별 연산, 브로드캐스팅(Broadcasting) ndarray 가지고놀기 기초문법 공부하기 5 (0) | 2021.09.28 |
[Numpy] #4 reshape(-1), flatten(), copy(), ndarray 가지고놀기 기초문법 공부하기 4 (0) | 2021.09.28 |
[Numpy] #3 무작위, 랜덤, 표본추출 (normal, random) 기초문법 공부하기 3 (0) | 2021.09.28 |
[Numpy] #1 넘파이란, 객체생성및처리 기초문법 공부하기 1 (0) | 2021.09.27 |
댓글