Kim MyeongOk 2022. 12. 5. 16:56

Numpy

Numpy는 파이썬 대표적 배열 라이브러리
사이킷러닝, 매플러릿도 넘파이에 의존하고 있으며, 입력도 넘파이 배열로 전달될것을 가정함.
predict 메소드에 array([1])
리스트에 리스트를 넣었었는데, 이를 넘파이를 거쳐 넘파이 배열로 변환해야함
    - 1차원 = 벡터
    - 2차원 = 행렬
    - 3차원 = ...

다른종류의 타입을 넣을 수 없다

import numpy as np

배열 = tensor

> 텐서플로우, 파이토치에서는 배열을 텐서라고 부름

> 사이킷런에서는 대부분 배열이라고 부름

# 데이터 수집
fish_length = [25.4, 26.3, 26.5, 29.0, 29.0, 29.7, 29.7, 30.0, 30.0, 30.7, 31.0, 31.0,
                      31.5, 32.0, 32.0, 32.0, 33.0, 33.0, 33.5, 33.5, 34.0, 34.0, 34.5, 35.0,
                      35.0, 35.0, 35.0, 36.0, 36.0, 37.0, 38.5, 38.5, 39.5, 41.0, 41.0, 9.8,
                      10.5, 10.6, 11.0, 11.2, 11.3, 11.8, 11.8, 12.0, 12.2, 12.4, 13.0, 14.3,
                      15.0]
fish_weight = [242.0, 290.0, 340.0, 363.0, 430.0, 450.0, 500.0, 390.0, 450.0, 500.0, 475.0, 500.0,
                      500.0, 340.0, 600.0, 600.0, 700.0, 700.0, 610.0, 650.0, 575.0, 685.0, 620.0, 680.0,
                      700.0, 725.0, 720.0, 714.0, 850.0, 1000.0, 920.0, 955.0, 925.0, 975.0, 950.0, 6.7,
                      7.5, 7.0, 9.7, 9.8, 8.7, 10.0, 9.9, 9.8, 12.2, 13.4, 12.2, 19.7, 19.9]

# 전처리
fish_data = [[l, w] for l, w in zip(fish_length, fish_weight)]
fish_target = [1]*35 + [0]*14
from sklearn.neighbors import KNeighborsClassifier

kn = KNeighborsClassifier()

train_input = fish_data[:35]
train_target = fish_target[:35]

test_input = fish_data[35:]
test_target = fish_target[35:]
# 모델 훈련
kn.fit(train_input, train_target)
# 모델 정확도
kn.score(test_input, test_target)
# [Result]
# 0.0

데이터 섞기

※ 주의점: 입력데이터와 타깃데이터가 쌍으로 섞여야한다.

(주의사항을 지키지 않을 시, 학습이 엉터리로 됨.)

1. 인덱스를 섞어서 데이터를 섞는 방법

np = 배열 슬라이싱 제공

- 배열 슬라이싱

: a = np.array([5, 6, 7, 8])

( np.array( 파이배열 혹은 리스트 사용 가능 ) )

: a[[1, 3]]

...⇑ 다른 인덱스 배열을 넣어서 a배열에 있는 원소를 선택하는 방법...

result = 6, 7

import numpy as np

input_arr = np.array(fish_data)
target_arr = np.array(fish_target)
# print(input_arr)
print(input_arr.shape)
# [Result]
# (49, 2)

np.random.seed()

머신러닝 라이브러리에서 무작위로 섞어야함. 랜덤한 행동들이 동일하게 유지됨.

랜덤시드를 사용하는 이유는 재현성을 위함.

교육용으로 학습자가 바르게 하고 있는지에 대한 여부를 확인하기 위함.

np.random.seed(42)
index = np.arange(49)
np.random.shuffle(index)
print(index)
# [Result]
# [13 45 47 44 17 27 26 25 31 19 12  4 34  8  3  6 40 41 46 15  9 16 24 33
#  30  0 43 32  5 29 11 36  1 21  2 37 35 23 39 10 22 18 48 20  7 42 14 28
#  38]
print(input_arr[[1,3]])
# [Result]
# [[ 26.3 290. ] [ 29.  363. ]]
train_input = input_arr[index[:35]]
train_target = target_arr[index[:35]]

print(input_arr[13], train_input[0])
# [Result]
# [ 32. 340.] [ 32. 340.]

데이터 나누고 확인하기

  • 2차원 배열을 선택할 때, ,(콤마)로 나눠서 행고 열을 지정할 수 있음.특정
  • 데이터를 나타낼 때는 배열 슬라이싱을 활용
  • 전체를 나타낼때는, 배열의 이름만 불러와주면 됨
  • ex) plt.scatter(행, 열)
import matplotlib.pyplot as plt

plt.scatter(train_input[:, 0], train_input[:, 1])
plt.scatter(test_input[:, 0], test_input[:, 1])
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

두번째 머신러닝 프로그램

from sklearn.neighbors import KNeighborsClassifier

kn = KNeighborsClassifier()
kn.fit(train_input, train_target)
kn.score(test_input, test_target)
# [Result]
# 1.0
kn.predict(test_input)
# [Result]
# array([0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0])
test_target
# [Result]
# array([0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0])

[결론]

  • 가능하면 편중되지 않도록 해야함
  • "샘플링 편향"이 되지 않도록 해야함.
  • 쌍을 이뤄서 섞어야하고, 섞인 인덱스를 활용함.

  • 검증데이터는 모델을 평가하는 용도

[공부할만한 도서 추천]

  • 머신러닝: 책을 여러번 사서 봐야함.
  • 커버하는 부분이 다 다르기 때문

  • x좌표에는 첫번째와 두번째 특성을 사용함.