민듀키티

한 번에 끝내는 딥러닝/인공지능 (Numpy Tutorial) 본문

Data Science/한번에 끝내는 딥러닝&인공지능

한 번에 끝내는 딥러닝/인공지능 (Numpy Tutorial)

민듀키티 2022. 2. 21. 21:20

1. List 와 비교

 

(1) list와 numpy 만들기

L = [1, 2, 3]
A = np.array([1, 2, 3])
print(L)
print(A)

>>> [1, 2, 3]
    [1 2 3]

 

(2) 더하기

# 리스트
L = L + [5]
print(L)
>>> [1, 2, 3, 5]


# 넘파이
A = A + np.array([5])
print(A)
>>> [6 7 8]

 

(3) 곱하기

# list의 모든 원소를 2배로 만들기
L = [1, 2, 3]
L2 = []
for item in L:
  L2.append(item*2)
print(L2)

>>> [2, 4, 6]

# ndarray의 모든 원소 2배로 만들기
A = np.array(L)
A2 = A*2
print(A2)
>>> [1, 2, 3, 1, 2, 3]

 


2. 배열 생성하기

d = np.empty((3,3))
print(d)

3*3의 배열의 랜덤 numpy가 생성됨

 

k = np.arange(10)
print(k)

>>> [0 1 2 3 4 5 6 7 8 9]

 

random -> 표준 정규분포로 생성

# uniform distribution
l = np.random.rand(2,2)
print(l)

 


3. 배열의 dtype

 a = np.array([1, 2, 3])
 b = np.array([1, 2, 3], dtype=np.float64)
 c = np.array([1, 2, 3], dtype=np.int32)

 print(a.dtype, b.dtype, c.dtype)
 
 >>> int64 float64 int32

 

비트수

d = np.array([1, 2, 3], dtype='i1')
e = np.array([1, 2, 3], dtype='i2')
f = np.array([1, 2, 3], dtype='i4')
g = np.array([1, 2, 3], dtype='i8')

print(d.dtype, e.dtype, f.dtype, g.dtype)


>>> int8 int16 int32 int64

 


4. 배열의 인덱싱과 슬라이싱

 

(1) 인덱싱

a = np.arange(10)
print(a)

>>> [0 1 2 3 4 5 6 7 8 9]


print(a[5])
>>> 5

 

(2) 슬라이싱

print(a[5:8])

>>> [5 6 7]

 

인덱싱은 슬라이싱과 다르게, 차원이 감소한다는 특징을 가지고 있음

= indexing을 사용하면 항상 랭크가 감소합니다. 반면에 slicing을 사용하면 차원이 유지가 됨

 

 

(3) 슬라이싱 예제

c = np.arange(24).reshape(2,3,4)
print(c)
print(c.shape)


>>> 
[[[ 0  1  2  3]
  [ 4  5  6  7]
  [ 8  9 10 11]]

 [[12 13 14 15]
  [16 17 18 19]
  [20 21 22 23]]]
(2, 3, 4)

 

print(c[:,:,:1])
print(c[...,:1])

[[[ 0]
  [ 4]
  [ 8]]

 [[12]
  [16]
  [20]]]
[[[ 0]
  [ 4]
  [ 8]]

 [[12]
  [16]
  [20]]]

 

(4) fancy 인덱싱

d = np.arange(8).reshape(8,-1)
print(d, d.shape)


>>> [[0]
 [1]
 [2]
 [3]
 [4]
 [5]
 [6]
 [7]] (8, 1)
d = np.hstack((d, d, d, d))
print(d, d.shape)

>>> [[0 0 0 0]
 [1 1 1 1]
 [2 2 2 2]
 [3 3 3 3]
 [4 4 4 4]
 [5 5 5 5]
 [6 6 6 6]
 [7 7 7 7]] (8, 4)

5. Transpose

f = np.arange(16).reshape(2,2,4)
print(f, f.shape)


>>> [[[ 0  1  2  3]
  [ 4  5  6  7]]

 [[ 8  9 10 11]
  [12 13 14 15]]] (2, 2, 4)
print(f.transpose(1, 0, 2))


>>> [[[ 0  1  2  3]
  [ 8  9 10 11]]

 [[ 4  5  6  7]
  [12 13 14 15]]]

 


6. Numpy 연산

import numpy as np
x = np.array([[1,2], [3,4]], dtype=np.float64)
y = np.array([[5,6], [7,8]], dtype=np.float64)

print(np.add(x, y))
print(np.subtract(x, y))
print(np.multiply(x, y))
print(np.divide(x, y))
print(np.matmul(x, y))