티스토리 뷰

MachineLearning

[ML] numpy 함수들

SweetDev 2022. 1. 27. 11:04

1. array 생성

np.array([1,4,5,6], float) # ndarray 타입으로 생긴다.

이미 pyTorch의 Tensor로 정의되어 있다면 바로 바꿀 수도 있다. 

embeddings_t = torch.Tensor(np.ones((2, 2)))
embeddings_numpy = embeddings_t.numpy()

numpy는 하나의 데이터 타입만 넣을 수 있는거 기억하자!

 

2. array 모양 받아오기, 타입 확인하기, 크기 확인하기

array.shape
array.dtype
array.nbytes

3. shape 바꾸기

array.reshape(8,)
array.reshape(-1,2) # -1은 안쓰는것처럼 size를 기반으로 자동 설정 해준다.
array.flatten()

 

4. indexing

파이썬의 list와는 다르게 이차원 배열에서 [0,0]표기법을 지원한다. 

a[0,0] 과 a[0][0]은 같은 의미이다!!!!

 

5. slicing

list와 다르게 행과 열 부분을 나눠서 slicing이 가능하다. 

a[:, 2:]

 

step을 두개씩 뛰어서도 가능하다. 

a[:, ::2] # 0, 2, 4...번째 column의 데이터만 들어간다. 
a[::2, ::3]

 

6. arange
array의 범위를 지정하여 값의 리스트를 생성한다. 

np.arange(30)
np.arange(시작, 끝, step)

정수가 아니여도 가능하다. 

 

7. ones, zeros, empty

np.zeros(shape, dtype, order)
np.zeros(shape=(10,), dtype=np.int8)
np.ones(shape, dtype, order)
np.ones(shape=(10,), dtype=np.int8)

empty는 shape만 주어지고 안에는 쓰레기값이 들어있는 ndarray가 생성된다. 

np.empty(shape=(10,), dtype=np.int8)

8. ones_like, zeros_like, empty_like

주어진 ndarray의 shape와 같은 사이즈로 1, 0, 또는 empty ndarray 만들어준다. 

 

9. identity

identity matrix를 생성한다. ( 대각선만 1이고, 나머지는 0인 정방행렬)

np.identity(n=3, dtype=np.int8)

 

10. eye

대각선이 1인데 꼭 정방행렬이 아니어도 된다면? 시작값의 index를 인자로 받는다. 

np.eye(3) # 정방행렬
np.eye(3, 5, k=2)

 

11. diag

대각행렬의 값을 추출함. index를 받아서 대각선의 위치를 지정할 수도 있다. 

 

12. sum에서 axis

axis가 라이브러리마다 기준이 다를때도 있지만

numpy에서는 shape의 0번째 원소는 axis=0, 1번째 원소는 axis=1...처럼 생각해야 한다. 

 

test_array = np.arange(1,13).reshape(3,4)
test_array.sum(axis=1) # (3,)
test_array.sum(axis=0) # (4,)

 

차원이 커지면 이렇게 된다. 

13. mean(평균), std(표준편차)

axis가 중요하다!

axis가 제공되지 않으면 다차원 배열을 평면화 된 목록으로 취급한다. 

 

14. concatenate

array끼리 붙이는 함수!

vstack, hstack, concatenate가 있다. 

 

vstack과 concatenate(axis=0)이 같다고 보면 된다. 

 

15. array간의 연산

원소끼리 곱하기

* (shape이 같아야 한다!)

내적

A.dot(B)

transpose

a.T나 a.transpose()

 

16. All, Any

인자로 들어온 array의 데이터 전부, 혹은 일부가 조건에 만족하는지 bool값을 리턴한다. 

a = np.arange(10)
np.any(a>5) # True
np.any(a<0) # False
np.all(a>5) # False
np.all(a<10) # True

 

17. where(조건, True일때 리턴값, False일때 리턴값)

리턴값들을 쓰지 않으면 index값들이 리턴된다. 

 

18. argmax, argmin

최대값 혹은 최소값의 index를 리턴한다. 

axis도 인자로 사용 가능하다.

 

19. fancy index

??

 

20. astype

배열의 type 바꾸기

array.astype(int)

 

21. historgram

histogram, bin_edges = np.histogram(img, bins=256, range=(0, 255))
sns.lineplot(data=histogram)

도수, 구분 = np.histogram(data, 도수분포구간 (bin))

 

>>> bins = np.arange(20,55,5)  # 도수분포구간
>>> hist, bins = np.histogram(weight, bins)
>>> print (hist)
>>> print (bins)
[3 5 5 7 2 2]
[20 25 30 35 40 45 50]

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함