03-1. k-최근접 이웃 회귀


<aside> 📌 회귀 : 클래스 중 하나로 분류하는 것이 아니라 임의의 어떤 숫자를 예측

</aside>

1. 데이터 준비

농어 데이터 준비

import numpy as np

perch_length = np.array(
    [8.4, 13.7, 15.0, 16.2, 17.4, 18.0, 18.7, 19.0, 19.6, 20.0, 
     21.0, 21.0, 21.0, 21.3, 22.0, 22.0, 22.0, 22.0, 22.0, 22.5, 
     22.5, 22.7, 23.0, 23.5, 24.0, 24.0, 24.6, 25.0, 25.6, 26.5, 
     27.3, 27.5, 27.5, 27.5, 28.0, 28.7, 30.0, 32.8, 34.5, 35.0, 
     36.5, 36.0, 37.0, 37.0, 39.0, 39.0, 39.0, 40.0, 40.0, 40.0, 
     40.0, 42.0, 43.0, 43.0, 43.5, 44.0]
     )
perch_weight = np.array(
    [5.9, 32.0, 40.0, 51.5, 70.0, 100.0, 78.0, 80.0, 85.0, 85.0, 
     110.0, 115.0, 125.0, 130.0, 120.0, 120.0, 130.0, 135.0, 110.0, 
     130.0, 150.0, 145.0, 150.0, 170.0, 225.0, 145.0, 188.0, 180.0, 
     197.0, 218.0, 300.0, 260.0, 265.0, 250.0, 250.0, 300.0, 320.0, 
     514.0, 556.0, 840.0, 685.0, 700.0, 700.0, 690.0, 900.0, 650.0, 
     820.0, 850.0, 900.0, 1015.0, 820.0, 1100.0, 1000.0, 1100.0, 
     1000.0, 1000.0]
     )

산점도

import matplotlib.pyplot as plt

plt.scatter(perch_length, perch_weight)
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

Untitled

훈련 세트 준비

<aside> 📌 reshape() : 배열의 크기를 바꿀 수 있음

</aside>

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)

train_input = train_input.reshape(-1, 1)     # (42, 1)
test_input = test_input.reshape(-1, 1)       # (14, 1)
# 크기 -1 : 나머지 원소 개수로 모두 채우기

2. 결정계수 (R^2)

<aside> 📌 KNeighborsRegressor : k-최근접 이웃 회귀 알고리즘을 구현한 클래스

</aside>

<aside> 📌 결정계수 (R^2) = 1 - (타깃 - 예측)^2의 합 / (타깃 - 평균)^2의 합

</aside>

3. 과대 적합과 과소 적합

03-2. 선형 회귀