지도 학습(supervised learning) 알고리즘 : 분류 + 회귀(regression)
k-최근접 이웃 알고리즘
데이터 준비
# 훈련 세트와 테스트 세트로 나누기
from sklearn.model_selection import train_test_split
train_input, test_input, train_target, test_target = train_test_split(perch_length,perch_weight,random_state=42)
### random_state는 책과 결과를 동일하게 유지하기 위함
# 사이킷런에 사용할 훈련 세트는 2차원 배열이어야 함!
print(train_input.shape, test_input.shape) # shape : 배열의 크기 출력
train_input=train_input.reshape(-1,1) # reshape : 배열의 크기 원하는 형태로 바꾸기
test_input=test_input.reshape(-1,1) # 크기에 -1 : 나머지 원소 개수로 모두 채움
print(train_input.shape, test_input.shape)
※ reshape() : 바꾸려는 배열의 크기를 지정
결정계수($R^2$)
KNeighborsRegressor : 사이킷런에서 k-최근접 이웃 회귀 알고리즘을 구현한 클래스
※ KNeighborsClassifier : k-최근접 이웃 분류 알고리즘을 구현한 클래스
KNeighborsClassifier & KNeighborsRegressor 사용법 : 객체를 생성 → fit() 메서드로 모델 훈련 → score() 메서드로 Test set의 점수 확인
Test set의 점수(score)
분류(KNeighborsClassifier)의 경우 : 정확도(= Test set에 있는 샘플을 정확하게 분류한 개수의 비율)
회귀(KNeighborsRegressor)의 경우 : 결정계수($R^2$, coefficient of determination)
$R^2 = 1 - ((타깃 - 예측)^2 의 합) / ((타깃 - 평균)^2의 합)$
⇒ 타깃의 평균 정도를 예측하는 수준인 경우 : $R^2$ → 0
타깃에 아주 가까워지는 경우 : $R^2$ → 1
타깃과 예측한 값 사이의 차이 ⇒ 어느 정도 예측이 벗어났는지 알 수 있음