맞춤형 플랫폼 개발 도전기 (웹개발, 딥러닝, 블록체인)

Python Numpy Basic 1 (Array, Random) 본문

딥러닝·머신러닝/Python

Python Numpy Basic 1 (Array, Random)

경이가 꿈꾸는 플랫폼 개발 2021. 10. 30. 21:53

Python에서는 대부분 함수 적용했을 때 원본이 변화되면 return 값이 없는데, 원본이 변화되지 않으면 return 값이 있음

(은근히 유욯하게 쓰인다 :) 잘 기억해 놓으면 활용도 多)

 

 

 

Array

 

1. np.arange(iterable)

일단, range(10) 이라 함은 0부터 10 전까지의 iterable한 list가 생성되는 것

그래서 np.array(range(10)) 같은 형태도 가능하지만 np.arange(10) 도 가능하다 (np.arange(1,10,2) 이런 형태도 가능하다.

 

1-2. np.arange(범위(start, end, step)).reshape(차원)

배열을 뽑은 다음에 차원 변경하는 것

x = np.arange(36)
x.reshape(6, -1)  # 앞의 차원이 정해지면 나머지는 유추할수 있다. 그게 -1 이다
x.reshape(-1, 12)  # (3, 12)

 

2. slicing

기억하면 좋을 것 : arr[::-1] → 역순으로 만들기

차원 유지하면서 slicing : (comma)로 slicing → arr[ : , : , : ] comma 기준 1차원 slicing, 2차원 slicing, 3차원 slicing 

x = np.arange(15).reshape(3, 5)
x[0:2,1:4]

# array([[1, 2, 3],
#       [6, 7, 8]])

 

3. Array와 List는 연산이 다름

List는 정수를 곱하면 list가 n개 복제 or List 자체가 붙여짐 (원소 값이 변하지 않음)

Array는 원소끼리 4칙연산 == add(), substract(), multiply(), divide() : Array 간 행렬 4칙연산.

a = [10, 20, 30, 40]
b = 2
c = [100, 200, 300, 400]
a * b
a + b

# [10, 20, 30, 40, 10, 20, 30, 40]
# [10, 20, 30, 40, 100, 200, 300, 400]

x = np.arange(15).reshape(3, 5)
y = np.arange(0, 150, 10).reshape(3, 5)
x + y

# array([[  0,  11,  22,  33,  44],
#        [ 55,  66,  77,  88,  99],
#        [110, 121, 132, 143, 154]])

# 스칼라값, 단일값 객체와 array 연산 가능
x ** 2
x + np.array([10]) # 이렇게도 사용 가능, 단일값만 있는 array는 shape와 관계 없이 scalar 연산 가능
# array([[  0,   1,   4,   9,  16],
#        [ 25,  36,  49,  64,  81],
#        [100, 121, 144, 169, 196]], dtype=int32)

 

4. 통계 함수

평균 : iterable.mean() , np.mean(iterable)

최댓값, 최소값 : np.max(iterable), np.min(iterable), iterable.max(), iterable.min()

최댓값, 최소값이 있는 원소가 몇 번째에 있는지 : np.argmax(iterable), np.argmin(iterable), iterable.argmin(), iterable.argmax() → 차원별로 추출도 가능 np.argmax(iterable, axis=축) 축별로 1개씩 max, min 뽑는 거라고 생각 

var() : 분산 (variance) 값

std() : 표준편차 (standard deviation) 값

median() : 중앙값

sum() : 합계

np.cumsum() : 누적합계 

 

 

5. 비교 연산

비교 연산을 하면 True, False로 이루어진 ndarray의 결과값이 나온다

z = np.random.randn(10)
z > 0

# array([False, False,  True, False, False,  True, False, False,  True, True])

p = np.arange(1, 13).reshape(3, 4)
p % 2 == 0

# array([[False,  True, False,  True],
#        [False,  True, False,  True],
#        [False,  True, False,  True]])

 

6. Any, All

Any: 특정 조건을 만족하는 것이 하나라도 있으면 True, 아니면 False

All: 모든 원소가 특정 조건을 만족한다면 True, 아니면 False

z = np.random.randn(10)
np.any(z > 0)
np.all(z > 0)

# True
# False

 

7. Where

np.where(조건, True일 때, False일 때)

q = np.random.randn(10)
np.where(q > 0, q, 0)

# array([0. , 1.19590068, 0.47289855, 0.83683569, 0.10575251, 1.31968865, 0.2279251 , 0. , 0.49977128, 1.64262925])

8. Array 용량

여기서 용량은 단순히 xbyte * 원소개수 가 아니라 Array 객체 + 배열 데이터 

xbyte * 원소개수 구하려면 변수.nbytes 로 구하면 된다 (배열 데이터 용량만)

from sys import getsizeof
a = np.arange(6).reshape(3, 2)
getsizeof(a)
a.__sizeof__()
a.nbytes

# 120
# 120
# 24

 

 

 

Random

 

1. np.ones(차원tuple), np,zeros(차원tuple), np.full(차원tuple, number), np.empty(차원tuple) 

어떤 특정 숫자 (1, 0, 내가 지정한 number, 초기화 안된 임의의 값으로 초기화

 

2. np.eye(number)

(number X number) 의 단위행렬 만들기

 

3. np.linspace(start, end, num)

start부터 end까지 균일한 간격이 되도록 몇 개(num)로 나눌지 정하는 함수

 

4. np.random.sub_module

기본적으로 rand 함수는 [0, 1) 사이의 균일분포(확률이 동일)로 랜덤한 array 생성 

np.random.rand(차원)  : np.arange 처럼 차원으로 넣을 수 있음

np.random.randn(차원) : 정규분포

np.random.randint(start, end, 차원) : start 부터 end 까지 정수범위 안에서 뽑음

np.random.seed(정수) : 랜덤한 값을 동일하게 다시 생성하고자 할때 사용

np.random.choice(정수, size, replace) : 첫번째 parameter 가 정수인 경우 0 ~ 정수 (replace=False : 중복 불가, size=차원)

np.random.choice([a, b, c, d ... ]) : a, b, c, d .. 중에서 뽑기 (1차원 배열 안에서 뽑기)

                                            이 말은 np.random.choice() 안에 np.arange(1, 10,2) 써도 된다는 뜻  

np.random.uniform(차원) : 0과 1 사이의 난수 균등분포 확률

np.random.normal(차원) : np.random.normal(기준, 양 옆으로 얼마나 퍼져있을건지, size = 몇개 뽑을건지) 정규분포로 뽑아냄

def func():
    arr = np.arange(1, 46)
    np.random.shuffle(arr)
    return arr[:6]
func()

# array([17,  2, 25, 29, 43,  3])

 

5. np.unique(iterable), np.bincount

고유원소, 개수 구할 때 쓰인다. 

index, count = np.unique(b, return_counts=True)
# index는 array(['a', 'b', 'c'], dtype='<U1') 로 출력
# count는 array([2, 2, 1], dtype=int64)로 출력

c = np.array([0, 1, 1, 16])
np.bincount(c)
# 0에서 16까지 각 몇개씩 나왔는지 세는 함수
# array([1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1], dtype=int64)

 

6. np.random.shuffle(iterable)

랜덤으로 뽑아서 섞음

shuffle은 리턴값이 없음 (원본 변화시키는 것 ->  이 결과는 굳이 return 안해도 반영)

Comments