혼자 공부하는 머신러닝 + 딥러닝

[혼공머신] 4. K-NN 회귀

Seon_ 2021. 12. 17. 17:17
4.fish_regression
In [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])
In [2]:
import matplotlib.pyplot as plt
plt.scatter(perch_length, perch_weight)
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
In [3]:
from sklearn.model_selection import train_test_split
In [4]:
train_input, test_input, train_target, test_target = train_test_split(perch_length, perch_weight, random_state=42)
In [5]:
train_input = train_input.reshape(-1,1)
test_input = test_input.reshape(-1,1)
print(train_input.shape, test_input.shape)
(42, 1) (14, 1)
In [6]:
from sklearn.neighbors import KNeighborsRegressor

knr = KNeighborsRegressor()

knr.fit(train_input, train_target)
Out[6]:
KNeighborsRegressor(algorithm='auto', leaf_size=30, metric='minkowski',
                    metric_params=None, n_jobs=None, n_neighbors=5, p=2,
                    weights='uniform')
In [7]:
print(knr.score(test_input, test_target))
0.9928094061010639
  • Regression에서 Accuarcy는 R2 score를 뜻한다.
    • R2 score는 타깃의 평균 정도를 예측하는 수준이면 0, 타깃에 아주 가까워지면 1에 가까운 값이 된다.
In [8]:
from sklearn.metrics import mean_absolute_error

test_prediction = knr.predict(test_input)

mae = mean_absolute_error(test_target, test_prediction)
print(mae)
19.157142857142862
  • 실제값과 예측값이 평균적으로 19g 정도의 무게 차이를 보임을 알 수 있다.
In [9]:
print(knr.score(train_input, train_target))
0.9698823289099255
  • 테스트 세트에서 훈련 세트보다 높은 정확도를 보이는 것을 보아 과소적합의 특징을 띔을 알 수 있다.
    • 해결법: 모델을 복잡하게 만든다 : k-nn에서는 k의 수를 낮추면 국지적 패턴에 민감해지므로 복잡해진다.
In [10]:
knr.n_neighbors = 3

knr.fit(train_input, train_target)
print(knr.score(train_input, train_target))
0.9804899950518966
In [11]:
print(knr.score(test_input, test_target))
0.974645996398761
  • 과소적합 문제가 해결되었음을 알 수 있다.
  • 또한 두 점수 차이가 크지 않으므로 일반화가 잘 되었다고 할 수 있다.
In [12]:
# 5부터 45까지 x 좌표 만들기
x = np.arange(5, 45).reshape(-1,1)

for n in [1, 5, 10] :
  knr.n_neighbors = n
  knr.fit(train_input, train_target)
  prediction = knr.predict(x) # 주어진 x 좌표에 대한 y 값을 predict함
  plt.scatter(train_input, train_target)
  plt.plot(x, prediction)
  plt.title('n_neighbors = {}'.format(n))
  plt.xlabel('length')
  plt.ylabel('weight')
  plt.show()
In [1]:
from IPython.core.display import display, HTML

display(HTML("<style>.container { width:90% !important; }</style>"))