-- 01.numpy.ipynb --
import numpy as np

Scalar : 0차원 array (단일값)
Vector : 1차원 array
Matrix : 2차원 array
Tensor : 3차원(이상) array
x = np.array([1,2,3])
y = np.array([2,4,15])
y # repr값
print(y) # str값
np.array(10)
type(x)
numpy에서는 해당 array의 크기를 알 수 있다.
shape 을 확인함으로써 몇개의 데이터가 있는지, 몇 차원으로 존재하는지 등을 확인할 수 있다.
위에서 arr1.shape의 결과는 (5,) 으로써, 1차원의 데이터이며 총 5라는 크기를 갖고 있음을 알 수 있다.
arr4.shape의 결과는 (4,3) 으로써, 2차원의 데이터이며 4 * 3 크기를 갖고 있는 array 이다.
arr = np.array([1,2,3,4,5])
arr
arr.shape # tuple 타입이다.
arr.ndim # 몇차원 데이터입니까?
arr.size
len(arr)
arr.dtype
arr2 = np.array([10, 3.14, 2, 0.12])
arr2
arr2.dtype
x = np.array([1, 2, 3, 4])
y = np.array([[2, 3, 4],[1, 2, 4]])
x
y
x.shape
y.shape
x.ndim
y.ndim
len(x)
len(y)
x.size
y.size
z = np.array([
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12]
],
[
[101, 102, 103, 104],
[201, 202, 203, 204],
[301, 302, 303, 304]
]
])
z
z.shape
z.size
'차원 변환' 중요하다.
np.array(10) # scalar값 -- 0차원
np.array([10]) # 1차원
np.array([[10]]) # 2차원
np.array([[[10]]]) # 3차원
np.arange(10)
np.arange(1, 10)
np.arange(1, 10, 2)
np.arange(10, 0, -1)
np.arange(1, 10, dtype=np.int16)
타입변환한 array 를 리턴 (원본 변화 없슴!)
d = np.arange(3, 10)
d # int64 타입
d.astype(np.float64)
d
np.arange(12).reshape(2,6) # (12,) -> (2,6)
np.arange(12).reshape(3, 2, 2)
np.ones(5)
np.ones(6).reshape(2, 3)
np.ones((2,3), dtype=np.int16)
np.zeros((3,2,5), dtype=np.int8)
np.eye(5) # (5, 5) 단위 행렬
np.random.rand(10)
np.random.rand(2,3)

np.random.randn(3,4,2)
np.random.randint(5) # 0 ~ 4 사이의 정수 난수
np.random.randint(1, 10) # 1 ~ 9 [1, 10)
np.random.randint(1, 100, (3, 5, 2))
np.unique([11, 11, 2, 2, 34, 34]) # unique 한 값으로 이루어진 array 리턴
x = np.arange(10)
x
x[0]
x[3] = 100
x
x = np.arange(10).reshape(2,5)
x
x[0] # (5,)
x[0][2]
x[0, 2] # <- 콤마로 인덱싱 가능! numpy 에선 후자의 방법을 추천!!!!
x
x[1, 4], x[1, -1], x[-1, -1]
x.shape
x[0]
x[[0]]
x[[1,0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0]]
x = np.arange(10)
x
x[1:7]
x[1:]
x[:]
x[::2]
x[1::3]
x[::-1]
y = [[0, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]]
y
y[0:1]
y[1:3]
x = np.arange(15).reshape(3, 5)
x
x[:2][1:4]
x[:2, 1:4] # array는 차원별로 slicing 가능!!!!
차원변환은 데이터분석 과 인공지능에서 매우 빈번하게 발생되는 작업이니만큼 자유자재로 변환할수 있어야 하고, 머리속으로 내가 변환하는 데이터의 구조가 그려지도록 익숙해져야 합니다
사용 예) 이미지 데이터 벡터화 - 이미지는 기본적으로 2차원 혹은 3차원(RGB)이나 트레이닝을 위해 1차원으로 변경하여 사용 됨
x
x.ravel()
np.ravel(x)
np.ravel(x, order = 'C') # row(행) 방향으로 펼쳐짐 차원축(axis) : (axis 0 부터 펼처짐)
np.ravel(x, order = 'F') # column(열) 방향으로 펼쳐짐 (axis -1 부터 펼처짐)
y = np.arange(15).reshape(3,5)
y
y.flatten()
temp = x.ravel()
temp
temp[0] = 100
temp
x
temp2 = y.flatten() # 데이터의 '복사본'을 생성함
temp2
temp2[0] = 100
temp2
y # y는 바뀌지 않는다. (원본 데이터는 변화 없다!!!!)
x2 = np.arange(36)
x2
x2.reshape(6,6)
x2.reshape(6, -1)
x2.reshape(6, -1, 2) # (6, 3, 2) 이런게 차원을 유추한다는 말이다.
x3 = np.arange(6)
x3
x3.shape
x3 = x3.reshape(6, 1) # (6,) => (6,1) 로 차원 확장
x3
x3 = x3.reshape(6, 1, 1)
x3
x3 = x3.reshape((6,)) # 1차원으로 축소 (차원 제거)
x3
x3 = x3.reshape(1, 1, 1, 6)
x3
x3.squeeze()
x4 = np.arange(4).reshape((2, 1, 2))
x4
x4.squeeze()
x5 = np.arange(3)
x5
y5 = np.expand_dims(x5, 0) # 0번째 axis에 새로운 차원을 추가(삽입)한다.
y5
y5.shape
x6 = np.arange(4).reshape(2,2)
x6
y7 = np.expand_dims(x6, -1)
y7
a = np.array([2, 0, 1, 8])
a
a1 = a[np.newaxis, :] # (4,) => (1, 4)
a1
a1.shape
a2 = a[:, np.newaxis] # (4,) => (4,1)
a2
전치행렬 (transpose matrix) , 차원 축 바꾸기
![]()
a = np.arange(15).reshape(3, 5)
a
np.transpose(a) # (3, 5) => (5, 3)
a.T
np.swapaxes(a, 0, 1) # axis 0 과 axis 1을 바꾸기
x = np.arange(15).reshape(3, 5)
y = np.arange(0, 150, 10).reshape(3, 5)
y2 = np.random.rand(15).reshape(3, 5)
y3 = np.arange(15).reshape(5, 3)
x
y
y2
y3
a = [10, 20, 30, 40]
b = 2
c = [100, 200, 300, 400]
a *2
a + c
x + y
x - y
x + 10
x + [10]
x + [[10]]
x + np.array(10)
x + np.array([10])
"""
numpy 의 많은 함수들은 axis= 파라미터를 갖고 있습니다.
axis (축) 은 각 '차원' 을 의미합니다.
1차원 array 라면 각 차원에 대한 axis 값은 0 <- 1개 입니다.
2차원 array 라면 각 차원에 대한 axis 값은 0, 1 <- 2개 입니다.
3차원 array 라면 각 차원에 대한 axis 값은 0, 1, 2 <- 3개 입니다.
axis= 값을 명시하면 그 함수의 연산 은 해당 axis(축) 에 '따라서' 연산을 수행함
과연 '따라서' 의 의미가 무엇인지 실습을 통해 이해해봅시다
"""
None
x1 = np.arange(15)
x1
np.sum(x1)
np.sum(x1, axis=None)
x2 = x1.reshape(3,5)
x2
x2.shape
np.sum(x2)
np.sum(x2, axis=0)
np.sum(x2, axis=1)
np.sum(x2, axis=-1)
np.sum(x2, axis=-2)
y = np.random.rand(15).reshape(3,5)
y
np.max(y)
np.argmax(y) # 최대값의 index
np.max(y, axis=0)
np.argmax(y, axis=0)
np.max(y, axis=1)

x = np.arange(15).reshape(3,5)
x
y = np.random.rand(15).reshape(3,5)
y
x+y
a = np.arange(12).reshape(4, 3)
b = np.arange(100, 103)
a
b # b.shape => (3,)
a + b

- 출처: https://www.tutorialspoint.com/numpy/images/array.jpg
''' 브로드캐스팅 가용한 경우
A : 256 x 256 x 3
B : 3
Result: 256 x 256 x 3 <-- 결과 차원은 둘중 큰 size의 차원으로 확장
A : 8 x 1 x 6 x 1
B : 7 x 1 x 5
Result: 8 x 7 x 6 x 5
'''
''' 브로드캐스팅 불가능한 경우
A : 3
B : 4
A : 2 x 1
B : 8 x 4 x 3
'''
None
c = np.arange(1000,1004)
c
a.shape, c.shape
x = np.random.randint(1, 100, size = 10)
x
x % 2
x % 2 == 0
even_mask = x % 2 == 0
even_mask
x
x[even_mask]
x[[True, True, True, True, True, True, True, True, True, False]]
x[x % 2 == 0]
x[x > 30]
x[(x % 2 == 0) & (x < 50)]
True, int(True), False, int(False)
(x > 50).astype(int)
(x > 50).astype(int).sum()
np.sum(x > 50)
temp = np.array(
[23.9, 24.4, 24.1, 25.4, 27.6, 29.7,
26.7, 25.1, 25.0, 22.7, 21.9, 23.6,
24.9, 25.9, 23.8, 24.7, 25.6, 26.9,
28.6, 28.0, 25.1, 26.7, 28.1, 26.5,
26.3, 25.9, 28.4, 26.1, 27.5, 28.1, 25.8])
"""
평균기온이 25도를 넘는 날수는 총 21일
평균기온이 25를 넘는 날의 평균 기온은 약 26.8도
"""
None
np.sum(temp > 25.0)
temp[temp > 25]
print("%0.2f", sum(temp[temp > 25]) / len(temp[temp > 25]))
np.mean(temp[temp > 25])
np.average(temp[temp > 25])