Coding Diary.

(파이썬) NumPy 넘파이 내장 함수 총정리 본문

Coding/Python

(파이썬) NumPy 넘파이 내장 함수 총정리

life-of-nomad 2024. 6. 12. 11:39
728x90
반응형
NumPy 내장 함수를 이용하면 ndarray를 만드는 시간이 절약됩니다. 내장 함수를 이용하면 단 한줄의 코드로 특정한 종류의 ndarray를 만들 수 있습니다. 이번 글에서는 가장 유용한 ndarray 생성용 내장 함수에 대해 알아보겠습니다.

 

1. np.zeros()

  • np.zeros(shape) : 지정된 shape(행, 열) 으로 된 0으로만 채워진 ndarray를 만드는 함수 
  • np.zeros() 함수는 기본적으로 dtype float64인 배열을 만듭니다. 
  • 원한다면 dtype 키워드를 써서 데이터 유형을 변경할 수도 있습니다.
X = np.zeros((3,4))

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)

>>> X =
    [[ 0. 0. 0. 0.]
    [ 0. 0. 0. 0.]
    [ 0. 0. 0. 0.]]
    X has dimensions: (3, 4)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: float64

 

2. np.ones()

  • np.ones(shape) : 지정된 shape(행, 열) 으로 된 1으로만 채워진 ndarray를 만드는 함수 
  • np.ones() 함수도 기본적으로 dtype float64인 배열을 만듭니다. 
  • 원한다면 dtype 키워드를 써서 데이터 유형을 변경할 수도 있습니다.
X = np.ones((3, 2))

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype) 

>>> X =
    [[ 1. 1.]
    [ 1. 1.]
    [ 1. 1.]]
    X has dimensions: (3, 2)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: float64

 

3. np.full()

  • np.full(shape, constant value) : 원하는 숫자가 채워진 지정된 모양의 ndarray를 만드는 함수
  • 첫번째 인수인 shape 은 행렬 모양이고, 두번째 인수인 constant value는 원하는 상수 값입니다.
  • np.full 함수는 기본적으로 배열을 채운 상수 값과 데이터 유형이 동일한 배열을 만듭니다.
  • 원한다면 키워드 dtype 을 써서 데이터 유형을 변경할 수도 있습니다. 
X = np.full((2, 3), 5)

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)  

>>> X =
    [[5 5 5]
    [5 5 5]]
    X has dimensions: (2, 3)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: int64

 

4. np.eye()

  • 단위행렬(Identity Matrix)는 선형대수에서 가장 기초적인 배열입니다.
  • 단위행렬은 주 대각선에 1만 있고 나머지 자리에는 모두 0이 채워진 정사각형 행렬입니다.
  • 단위행렬은 모두 정사각형이기 때문에 np.eye() 함수는 정수 하나만을 인수로 받습니다.
  • np.eye() 함수도 기본적으로 dtype float64인 배열을 만듭니다. dtype으로 데이터 유형을 변경할 수 있습니다.
X = np.eye(5)

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)  

>>> X =
    [[ 1. 0. 0. 0. 0.]
    [ 0. 1. 0. 0. 0.]
    [ 0. 0. 1. 0. 0.]
    [ 0. 0. 0. 1. 0.]
    [ 0. 0. 0. 0. 1.]]
    X has dimensions: (5, 5)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: float64

 

5. np.diag()

  • np.diag()를 이용해서 대각행렬을 만들 수 있습니다.
  • 대각행렬이란 주 대각선에만 값이 있는 정사각형 행렬을 의미합니다.
X = np.diag([10, 20, 30, 50])

print('X = \n', X)

>>> X =
    [[10 0 0 0]
    [ 0 20 0 0]
    [ 0 0 30 0]
    [ 0 0 0 50]]

 

6. np.arange()

  • np.arange(start_val, stop_val, step_size) : 주어진 구간 안에서 일정한 간격으로 된 값들로 된 array를 만듭니다.
  • 인수를 1개, 2개, 3개 쓸 수 있습니다.

1) np.arange(stop_val)

  • np.arange(N) : 0와 N-1 사이의 연속된 정수로 된 1차원 ndarray 를 만듭니다.
x = np.arange(10)

print('x = ', x)
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype) 

>>> x = [0 1 2 3 4 5 6 7 8 9]
    x has dimensions: (10,)
    x is an object of type: class 'numpy.ndarray'
    The elements in x are of type: int64

2) np.arange(start_val, stop_val)

  • np.arange(start, stop)은 인수를 2개 넣으면 반열린구간 [start, stop)안의 일정한 간격의 값들로 된 1차원 array를 만듭니다.
  • 즉, 간격의 숫자들에 start는 포함되지만 stop 은 제외됩니다.
x = np.arange(4, 10)

print('x = ', x)
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype) 

>>> x = [4 5 6 7 8 9]
    x has dimensions: (6,)
    x is an object of type: class 'numpy.ndarray'
    The elements in x are of type: int64

3) np.arange(start_val, stop_val, step_size)

  • np.arange(start, stop, step)은 반열린구간 [start, stop) 안에서 step만큼 증가하는 1차원 ndarray를 만듭니다.
x = np.arange(1, 14, 3)

print('x = ', x)
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype) 

>>> x = [ 1 4 7 10 13]
    x has dimensions: (5,)
    x is an object of type: class 'numpy.ndarray'
    The elements in x are of type: int64

 

7. np.linspace

  • np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
  • 이 구문은 [start, stop]에 걸쳐 계산된 일정한 간격의 값 num을 리턴합니다.
  • np.arange() 함수를 사용할 때 0.3 같은 step도 되지만 소수점의 정밀도에 한계가 있기 때문에 정수가 아닌 step 을 써야 하는 경우 np.linspace() 함수를 쓰는게 더 좋습니다.
  • np.linspace(start, stop, N) 함수는 닫힌구간 [start, stop]에 걸쳐 일정한 간격으로 된 숫자 N개를 리턴합니다. 즉, start, stop 값이 모두 포함됩니다. 
  • 또한, np.linspace(start, stop) 형태로 적어도 2개의 인수를 써야 합니다. 이 경우 디폴트 간격 값은 N=50이 됩니다. 
x = np.linspace(0, 25, 10)

print('x = \n', x)
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype) 

>>> x = [ 0. 2.77777778 5.55555556 8.33333333 11.11111111 13.88888889 16.66666667 19.44444444 22.22222222 25. ]
    x has dimensions: (10,)
    x is an object of type: class 'numpy.ndarray'
    The elements in x are of type: float64
  • endpoint = False를 설정하면 구간의 종료점을 제외할 수 있습니다. 
x = np.linspace(0,25,10, endpoint = False)

print('x = ', x)
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype) 

>>> x = [ 0. 2.5 5. 7.5 10. 12.5 15. 17.5 20. 22.5]
    x has dimensions: (10,)
    x is an object of type: class 'numpy.ndarray'
    The elements in x are of type: float64

 

8. np.reshape

1) np.reshape 함수

  • 지금까지 np.arange()와 np.linspace()를 사용하여 1차원 ndarray를 만들었습니다. 
  • 이 함수들을 np.reshape() 함수와 결합하면 2차원 ndarray를 만들 수 있습니다. 
  • np.reshape(ndarray, new_shape)는 주어진 ndarray에 지정된 new_shape으로 변환합니다.
  • 이때 new_shape는 주어진 ndarray 안에 있는 요소의 개수와 일치해야 합니다.
x = np.arange(20)
print('Original x = ', x)

x = np.reshape(x, (4, 5))
print('Reshaped x = \n', x)
print('x has dimensions:', x.shape)
print('x is an object of type:', type(x))
print('The elements in x are of type:', x.dtype) 

>>> Original x = [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
    Reshaped x =
    [[ 0 1 2 3 4]
    [ 5 6 7 8 9]
    [10 11 12 13 14]
    [15 16 17 18 19]]

    x has dimensions: (4, 5)
    x is an object of type: class 'numpy.ndarray'
    The elements in x are of type: int64

 

2) np.ndarray.reshape 메소드로 이용하여 np.arange()와 결합

  • np.reshape(shpae, order='C') 이 메소드를 쓰면 동일한 데이터가 담긴 새로운 모양의 배열이 됩니다.
  • NumPy의 특징 중 하나는 일부 함수를 메소드로서 적용할 수 있다는 것입니다. 
  • 그렇게 하면 단 한줄의 코드 안에서 다양한 함수를 순차적으로 적용할 수 있습니다.
Y = np.arange(20).reshape(4, 5)

print('Y = \n', Y)
print('Y has dimensions:', Y.shape)
print('Y is an object of type:', type(Y))
print('The elements in Y are of type:', Y.dtype) 

>>> Y =
    [[ 0 1 2 3 4]
    [ 5 6 7 8 9]
    [10 11 12 13 14]
    [15 16 17 18 19]]
    Y has dimensions: (4, 5)
    Y is an object of type: class 'numpy.ndarray'
    The elements in Y are of type: int64

 

3) np.ndarray.reshape 메소드로 이용하여 np.linspace()와 결합

  • 마찬가지로, np.linspace()와 함께 이용할 수도 있습니다.
X = np.linspace(0, 50, 10, endpoint=False).reshape(5, 2)

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)

>>> X =
    [[ 0. 5.]
    [ 10. 15.]
    [ 20. 25.]
    [ 30. 35.]
    [ 40. 45.]]

    X has dimensions: (5, 2)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: float64

 

9. np.random.random() 

  • 랜덤 ndarray는 무작위 숫자가 담긴 배열입니다. 종종 머신러닝에서 무작위 행렬을 만들어야 할 때 유용합니다.
  • 예를 들어, 신경망의 가중치를 초기화할 때 다양한 모양의 랜덤 ndarray가 도움이 됩니다.
  • 반열린구간 [0.0, 1.0) 안에 있는 무작위 소수로 이루어진 모양의 ndarray를 만들어 보겠습니다.
X = np.random.random((3, 3))

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in x are of type:', X.dtype)

>>> X =
    [[ 0.12379926 0.52943854 0.3443525 ]
    [ 0.11169547 0.82123909 0.52864397]
    [ 0.58244133 0.21980803 0.69026858]]

    X has dimensions: (3, 3)
    X is an object of type: class 'numpy.ndarray'
    The elements in x are of type: float64

 

10. np.random.randint()

  • 위와 마찬가지로 특정한 구간 안의 무작위 정수들로 이루어진 ndarray를 만들 수도 있습니다.
  • np.random.randint(start, stop, size = shape)) 함수는 반열린구간 [start, stop) 안에 있는 무작위 정수로 된 주어진 모양의 ndarray를 만듭니다.
X = np.random.randint(4, 15, size=(3, 2))

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)

>>> X =
    [[ 7 11]
    [ 9 11]
    [ 6 7]]

    X has dimensions: (3, 2)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: int64

 

11. np.random.normal()

  • 또한, 특정한 통계적 속성을 충족하는 무작위 숫자들로 된 ndarray를 만들수도 있습니다. 
  • np.random.normal(mean, standard deviation, size=shape) 는 주어진 평균(mean)과 표준편차(standard deviation)로 된 정규(normal) (가우시안)분포에서 뽑은 무작위 숫자들이 담긴 주어진 모양의 ndarray를 만듭니다. 
  • 예를 들어, 평균이 0이고 표준편차가 0.1인 정규 분포에서 1,000 x 1,000 ndarray를 만들어 보겠습니다.
X = np.random.normal(0, 0.1, size = (1000, 1000))

print('X = \n', X)
print('X has dimensions:', X.shape)
print('X is an object of type:', type(X))
print('The elements in X are of type:', X.dtype)
print('The elements in X have a mean of:', X.mean())
print('The maximum value in X is:', X.max())
print('The minimum value in X is:', X.min())
print('X has', (X < 0).sum(), 'negative numbers')
print('X has', (X > 0).sum(), 'positive numbers')

>>> X =
    [[ 0.04218614 0.03247225 -0.02936003 ..., 0.01586796 -0.05599115 -0.03630946]
    [ 0.13879995 -0.01583122 -0.16599967 ..., 0.01859617 -0.08241612 0.09684025]
    [ 0.14422252 -0.11635985 -0.04550231 ..., -0.09748604 -0.09350044 0.02514799]
    ...,
    [-0.10472516 -0.04643974 0.08856722 ..., -0.02096011 -0.02946155 0.12930844]
    [-0.26596955 0.0829783 0.11032549 ..., -0.14492074 -0.00113646 -0.03566034]
    [-0.12044482 0.20355356 0.13637195 ..., 0.06047196 -0.04170031 -0.04957684]]
    
    X has dimensions: (1000, 1000)
    X is an object of type: class 'numpy.ndarray'
    The elements in X are of type: float64
    The elements in X have a mean of: -0.000121576684405
    The maximum value in X is: 0.476673923106
    The minimum value in X is: -0.499114224706
    X has 500562 negative numbers
    X has 499438 positive numbers
  • 위의 결과를 보면 평균이 0에 가깝고 최댓값과 최솟값이 평균 0을 중심으로 대칭이며 양수와 음수의 개수가 거의 같습니다.
728x90
반응형