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

k-최근접 이웃 회귀

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import numpy as np

# 농어의 데이터 (perch)
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]
)

K-최근접이웃 회귀(Regression)

  • 중요도 : 하 ( 그냥 넘아가)
  • 1967년에 만들어짐. 굉장히 옛날 모델.
  • 알고리즘은 예측정확성이 가장 중요한데, 최근접이웃은 가장 낮게 나옴. 따라서, 현업에서 쓸 일이 없다.

시각화

1
2
3
4
5
# 시각화의 안좋은 예(교재)
import matplotlib.pyplot as plt

plt.scatter(perch_length, perch_weight)
plt.show()

png

1
2
3
4
5
6
7
8
# 시각화의 좋은 예(객체 지향)
fig, ax = plt.subplots()
ax.scatter(perch_length, perch_weight)

# xlabel, ylabel은 구글링을 찾아라
ax.set_xlabel("length")
ax.set_ylabel("weight")
plt.show()

png

  • 앞으로 시각화는 객체 지향으로

분석

  • 30을 기준으로 자르면
    • 30 이전은 완만하고, 30 이상은 급격하다.
    • 30 이전은 편차가 작고, 30 이상은 편차가 크다.

훈련데이터와 테스트데이터셋으로 분리

  • 가급적 코드 외우기
1
2
3
4
5
6
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 = 42 는 랜덤시드 고정을 자동으로 해준다
# ndim을 찍으면 모두 1차원배열로 나온다.
print(train_input.shape, test_input.shape)
(42,) (14,)
1
2
test_array = np.array([1,2,3,4])
print(test_array.shape)
(4,)
1
2
test_array = test_array.reshape(2, 2)
print(test_array.shape)
(2, 2)
  • reshape() 사용하여 2차원 배열 바꿈
  • 머신러닝은 2차원 배열로 넣어야 한다.
1
2
3
4
5
train_input = train_input.reshape(-1, 1) # -1은 매직

test_input = test_input.reshape(-1, 1)

print(train_input.shape, test_input.shape)
(42, 1) (14, 1)

결정계수

  • 모델이 얼마만큼 정확하냐?
  • 절댓값은 아님/ 상대적인 값
1
2
3
4
5
6
7
8
9
10
11
12
from sklearn.neighbors import KNeighborsRegressor

# knn 클래스 불러오기
knr = KNeighborsRegressor()

# 모형학습
knr.fit(train_input, train_target)

# 테스트 점수 확인하자. -> 얼마나 정확하냐? -> 실무에서는 잘 나와야 70%
knr.score(test_input, test_target)


0.992809406101064
  • 오차가 작으면 작을수록 좋은 모델.
  • 100%을 예측하는 것은 있을 수 없다.

MAE

  • 타깃과 예측의 절댓값 오차를 평균하여 반환
  • mean_absolute_error는 타깃과 예측의 절댓값 오차를 평균하여 반환한다.
1
2
3
4
5
from sklearn.metrics import mean_absolute_error

# 예측 데이터 만들기
test_prediction = knr.predict(test_input)
test_prediction
array([  60. ,   79.6,  248. ,  122. ,  136. ,  847. ,  311.4,  183.4,
        847. ,  113. , 1010. ,   60. ,  248. ,  248. ])
  • mae를 구한다.
1
2
mae = mean_absolute_error(test_target, test_prediction)
print(mae)
19.157142857142862
  • 이게 무슨 뜻이냐면, 평균적으로 19g정도 다르다.
  • 분산 구할때는 제곱을 해준것이고, 지금은 절댓값을 씌운것이다.
  • 절대적인 게 아니라 상대적인 것이다.

과대적합 vs 과소적합

  • 공통점은 머신러닝 모형이 실제 테스트 시 잘 예측을 못한다는 것.
  • 과대적합 : 훈련데이터에는 예측 잘함 / 테스트 데이터에서는 예측을 잘못함.
    • 처리하기 곤란
    • 비일비재 하다
  • 과소적합 : 훈련데이터에서는 예측 못함 / 테스트데이터에서는 예측을 잘함. or 둘다 예측을 잘못함.
  • 보통 과소적합은 신경 안써도 된다. 데이터 양이 적거나, 모델을 너무 간단하게 만들어서 비롯된 문제이기 때문.
1
2
# 훈련 데이터 점수 확인하자.
knr.score(train_input, train_target)
0.9698823289099254
  • 0.97 정도 나옴
    • 상사왈: 0.98로 올려봐
    • k-최근접 기본값이 5인데, 3으로 줄여봄
1
2
3
4
5
6
7
8
9
# Default = 5를 3으로 변경
# 머신러닝 모형을 살짝 변경
# 옷으로 비유하면, 꽉끼는 옷에 단추가 5개였는데, 2개를 풀었다는 소리
knr.n_neighbors = 3

# 모데을 다시 훈련
knr.fit(train_input, train_target)
print(knr.score(train_input, train_target))

0.9804899950518966
  • 훈련데이터로 검증했더니 0.98
1
print(knr.score(test_input, test_target))
0.9746459963987609
  • MAE 구하기
1
2
3
test_prediction = knr.predict(test_input)
mae = mean_absolute_error(test_target, test_prediction)
print(mae)
35.42380952380951
  • 뭔가 이상하다.. 오차 값이 19 -> 35

결론

  • k 그룹을 5로 했을 때, R2(결정계수) 점수는 0.98, MAE는 19였음.
  • k 그룹을 3으로 했을 때, R2 점수는 0.97, MAE는 35였음.
  • k 그룹 = n으로 반복될 것이다. 사용자 정의 함수를 사용한다.
  • 최적의 k를 찾는 것이 머신러닝!!!
  • 5장에서 배울 것.

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

http://griotold.github.io/2022/03/30/ch_3_1/

Author

HS

Posted on

2022-03-30

Updated on

2022-03-30

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Comments

You forgot to set the shortname for Disqus. Please set it in _config.yml.
You need to set client_id and slot_id to show this AD unit. Please set it in _config.yml.