Numpy part I¶
In [1]:
coefficient_matrix=[[2,2,1],[2,-1,2],[1,-1,2]]
constant_vector=[9,6,5]
- 코드로 방정식 표현하면 위와 같이 표현 할 수 있다.
- 하지만 큰 Matrix에 대해서는 python은 처리 속도 문제가 존재
- 따라서 적절한 패키지를 활용해야 한다.
Numpy¶
- Numerical Python
- 파이썬의 고성능 과학 계산용 패키지
- Matrix와 Vector와 같은 Array연산의 사실상의 표준
- 일반 List에 비해 빠르고, 메모리 효율적
- C,C++,포트란 등의 언어와 통합 가능
array¶
In [2]:
import numpy as np
In [3]:
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
a = np.array(a, int)
a
Out[3]:
- int형으로 넣겠다고 선언해 줄 수 있다
In [4]:
test_array = np.array(['1', '4', 5, 8], float)
print(test_array)
type(test_array[1])
Out[4]:
shift
+tab
하면 docstring을 볼 수 있다- numpy는 np.array함수를 활용 배열을 생성함 → ndarray
- numpy는 하나의 데이터 type만 배열에 넣을 수 있다
- List와 가장 큰 차이점 → dynamic typing not supported
- C의 Array를 사용하여 배열을 생성한다
- 메모리 공간이 일정하다
In [5]:
a = [1, 2, 3, 4, 5]
b = [5, 4, 3, 2, 1]
print(a is b)
print(a[0] is b[-1])
is
는 주소 값을 비교하는 명령어이다- 파이썬에서는 -5 ~ 256까지는 static 메모리에 저장이되어서 같은 주소 값을 가진다.
In [6]:
a = np.array(a)
b = np.array(b)
a[0] is b[-1]
Out[6]:
- numpy는 static메모리를 가지고 가는게 아니다
- numpy는 메모리가 순차적으로 할당되어 있다
In [7]:
test_array = np.array([1, 4, 5, "8"], float) # String Type의 데이터를 입력해도
test_array
Out[7]:
In [8]:
type(test_array[3]) # Float Type으로 자동 형변환을 실시
Out[8]:
In [9]:
print(test_array.dtype)
print(test_array.shape)
- shape: numpy array의 dimaension 구성을 반환함
- dtype: numpy array의 데이터 type을 반환함
array shape¶
1) vector
In [10]:
vector = [1, 4, 5, 8]
np.array(vector, int).shape
Out[10]:
- shape: array의 크기, 형태 등에 대한 정보
2) matrix
In [11]:
matrix = [[1, 2, 5, 8], [1, 2, 5, 8], [1, 2, 5, 8]]
np.array(matrix, int).shape
Out[11]:
3) 3rd order tensor
In [12]:
tensor = [
[[1, 2, 5, 8], [1, 2, 5, 8], [1, 2, 5, 8]],
[[1, 2, 5, 8], [1, 2, 5, 8], [1, 2, 5, 8]],
[[1, 2, 5, 8], [1, 2, 5, 8], [1, 2, 5, 8]],
[[1, 2, 5, 8], [1, 2, 5, 8], [1, 2, 5, 8]],
]
np.array(tensor, int).shape
Out[12]:
Array dtype¶
In [13]:
print(np.array(tensor, int).ndim)
print(np.array(tensor, int).size)
- ndim: number of dimensions
- size: data의 개수
nbytes-ndarray object의 메모리 크기를 반환함
In [14]:
np.array([[1, 2, 3], [4.5, "5", "6"]], dtype=np.float32).nbytes
Out[14]:
In [15]:
np.array([[1, 2, 3], [4.5, "5", "6"]], dtype=np.int32).nbytes
Out[15]:
In [16]:
np.array([[1, 2, 3], [4.5, "5", "6"]], dtype=np.int8).nbytes
Out[16]:
In [17]:
np.array([[1, 2, 3], [4.5, "5", "6"]], dtype=np.float64).nbytes
Out[17]:
'AI > 이론' 카테고리의 다른 글
행렬 (0) | 2021.01.25 |
---|---|
벡터 (0) | 2021.01.25 |
Numpy part III (0) | 2021.01.25 |
Numpy part II (0) | 2021.01.25 |
Python data handling (0) | 2021.01.22 |
File & Exception & Log Handling (0) | 2021.01.22 |
Module and Project (0) | 2021.01.21 |
Python Object Oriented Programming (0) | 2021.01.21 |