Post

농어 길이로 무게 예측 실습

농어 길이로 무게 예측 실습

실습1. 농어길이로 무게 예측

230913

데이터 수집 및 확인
모델 학습 : 단순 선형 회귀
산점도

230914

평가지표 : 단순 선형 회귀
모델 학습 및 평가 지표 : 다항 회귀, 결정트리, K최근접이웃 —

  1. 데이터 수집 및 확인
    1-1. df = pd.read_csv('path')
    1-2. df.info()
    1-3. scatter 시각화 ```python import matplotlib.pyplot as plt
1
2
3
4
5
6
7
plt.scatter(fish['길이'], fish['무게'])  # 둘 간의 관계를 나타내고 2차원이다.
plt.xlabel('length')
plt.ylabel('weight')
plt.show()
```
1-4. EDA 툴 사용하여 결측치, 중복값 확인
1-5. boxplot으로 이상치 확인
  1. 모델 학습 : 단순 선형 회귀 ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error , r2_score, mean_absolute_error from sklearn.linear_model import LinearRegression

경고메세지 끄기

import warnings warnings.filterwarnings(action=’ignore’)

데이터 로드

fish_df = pd.read_csv(‘./data/fish.csv’)

데이터 분석

pass

데이터 전처리

y_data = fish_df[‘무게’] x_data = fish_df.drop(‘무게’,axis=1) # fish_df[‘길이’]로 하면 안됨.

print(y_data.shape, x_data.shape)

x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=42) # 회귀분석

모델 생성

model = LinearRegression()

모델 학습

model.fit(x_train, y_train)

모델 검증

print(model.score(x_train, y_train)) #0.9371680443381393 print(model.score(x_test, y_test)) #0.8324765337629763

모델 예측

x_test = np.array([ [50] ])

y_predict = model.predict(x_test)

print(y_predict[0]) #1245.423930742852

#model객체에 coef_와 intercept_ 속성에 저장되어 있음 print(model.coef_ , model.intercept_)

1
2
**모델 결과 값**

0.9370169868327092 0.8320172451017457 1245.6320794533735 [39.30166945] -719.4513928072395

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
**[농어 무게 예측 방정식]**  
$y = 39.27*x - 718.43$

* coef_는 기울기, intercept_를 절편이다.
* 머신러닝에서는 기울기를 계수(coefficient) 또는 가중치(weight)라고 부른다.
* 이는 머신러닝 알고리즘이 학습을 하고 찾은 값이라는 의미로 모델 파라미터라고 부른다. 
* 많은 머신러닝 알고리즘의 훈련과정은 최적의 모델 파라미터를 찾는 것과 같다. 

3. 산점도
```python
import matplotlib.pyplot as plt

# 훈련 세트의 산점도를 그립니다
plt.scatter(x_train, y_train)

# 농어의 길이 15에서 50까지 1차 방정식 직선 그래프를 그립니다
plt.plot([15, 50], [15*model.coef_+model.intercept_, 50*model.coef_+model.intercept_])

# 50cm 농어 데이터
plt.scatter(50, 1245.42, marker='^')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

산점도 결과

  • 훈련세트에 비해서 테스트 세트의 성능이 많이 떨어지는 것을 보아 과대적합이 된 것 같다.
  • 그래프 왼쪽아래가 이상 -> 무게를 음수로 예측
  • 1차 선형방정식이니 무게가 음수로 예측될 수 밖에 없으므로 좀 더 예측력을 높이기 위해 곡선인 다항 회귀로 접근필요

평가지표추가

  • 선형 회귀 ```python from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_log_error

def evaluate_reg_all(y_test, y_predict): MSE = mean_squared_error(y_test,y_predict,squared=True) RMSE = mean_squared_error(y_test,y_predicat,squared=False) MAE = mean_absolute_error(y_test,y_predict) R2 = r2_score(y_test,y_predict)

1
print(f'MSE: {MSE:.3f}, RMSE: {RMSE:.3F}, MAE: {MAE:.3F}, R^2: {R2:.3F}') ``` ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import mean_squared_error , r2_score, mean_absolute_error, mean_squared_log_error from sklearn.linear_model import LinearRegression

경고메세지 끄기

import warnings warnings.filterwarnings(action=’ignore’)

데이터 로드

fish_df = pd.read_csv(‘./data/fish.csv’)

데이터 분석

pass

데이터 전처리

y_data=fish_df[‘무게’] x_data=fish_df.drop(‘무게’,axis=1)

x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=42)

모델 생성

model = LinearRegression()

모델 학습

model.fit(x_train, y_train)

모델 검증

pint(model.score(x_train, y_train)) #0.9371680443381393 print(model.score(x_test, y_test)) #0.8324765337629763

y_predict = model.predict(x_train) #훈련 데이터 예측

evaluate_reg_all(y_train,y_predict) #훈련 데이터에 대한 평가

y_predict = model.predict(x_test) #테스트 데이터 예측 evaluate_reg_all(y_test,y_predict) #테스트 데이터에 대한 평가

모델 실제 예측

xreal = np.array([ [50] ])

y_real_predict = model.predict(x_real)

print(f’실제 예측값:{y_real_predict[0]}’) #1245.423930742852

#model객체에 coef_와 intercept_ 속성에 저장되어 있음 print(model.coef_ , model.intercept_)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- 다항 회귀
```python
from sklearn.metrics import r2_score
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_log_error

def evaluate_reg_all(y_test, y_predict):
    MSE = mean_squared_error(y_test,y_predict,squared=True)
    RMSE = mean_squared_error(y_test,y_predict,squared=False)
    MAE = mean_absolute_error(y_test,y_predict)
    R2 = r2_score(y_test,y_predict)
    
    print(f'MSE: {MSE:.3f}, RMSE: {RMSE:.3F}, MAE: {MAE:.3F}, R^2: {R2:.3F}')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from sklearn.preprocessing import PolynomialFeatures
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error , r2_score, mean_absolute_error
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np

fish_df = pd.read_csv('./data/fish.csv')

y_target = fish_df['무게']
X_data = fish_df.drop(['무게'],axis=1,inplace=False)

x_train , x_test , y_train , y_test = train_test_split(X_data , y_target ,test_size=0.3, random_state=777)


# degree = 2 인 2차 다항식으로 변환하기 위해 PolynomialFeatures를 이용하여 변환
poly = PolynomialFeatures(degree=2, include_bias=False)

poly.fit(x_train)
poly_train = poly.transform(x_train)
poly_test = poly.transform(x_test)

print('변환된 2차 다항식 계수 feature:\n', poly_train)
1
2
#특성이 어떻게 만들어 졌는지 이름 출력
poly.get_feature_names_out()
1
2
3
4
5
6
7
lr = LinearRegression()
lr.fit(poly_train, y_train) #학습

y_preds = lr.predict(poly_test) #예측

#50cm 농어도 훈련때와 같은 형태로 변환해야 함
print(lr.predict([[50, 50**2]]))

print(lr.coef_, lr.intercept_)

  • 농어 무게 예측 방정식 $ y = 1.01 * x^2 -21.6 * x + 111.35$
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import matplotlib.pyplot as plt
# 구간별 직선을 그리기 위해 15에서 49까지 정수 배열을 만듭니다
point = np.arange(15, 50)

# 훈련 세트의 산점도를 그립니다
plt.scatter(x_train, y_train)

# 15에서 49까지 2차 방정식 그래프를 그립니다
plt.plot(point, 1.01*point**2 - 21.6*point + 111.35)

# 50cm 농어 데이터
plt.scatter([50], [1573], marker='^')
plt.xlabel('length')
plt.ylabel('weight')
plt.show()

=> scatter 시각화를 확인해보면 훈련세트의 경향을 잘 따르고 있고 무게가 음수로 나오는 일도 없다.

1
2
3
4
5
6
7
8
9
10
from sklearn.metrics import mean_squared_error , r2_score

#MSE : 에러들의 평균
mse = mean_squared_error(y_test, y_preds)

#R^2 : 실제와 예측의 분산비교
r2 = r2_score(y_test, y_preds)

print('MSE : {0:.3f}'.format(mse))
print('R^2 : {0:.3f}'.format(r2))
1
2
print(lr.score(poly_train, y_train))
print(lr.score(poly_test, y_test))

=> 훈련 세트와 테스트 세트에 대한 점수가 크게 높아졌다. => 하지만 여전히 테스트 세트의 점수가 조금 더 놓고, 과소적합이 아직 남아 있는 것 같다. => 조금 더 복잡한 모델이 필요할 것 같다.

  • 결정트리회귀모델 ```python from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_log_error

def evaluate_reg_all(y_test, y_predict): MSE = mean_squared_error(y_test,y_predict,squared=True) RMSE = mean_squared_error(y_test,y_predict,squared=False) MAE = mean_absolute_error(y_test,y_predict) R2 = r2_score(y_test,y_predict)

1
print(f'MSE: {MSE:.3f}, RMSE: {RMSE:.3F}, MAE: {MAE:.3F}, R^2: {R2:.3F}') ``` ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.metrics import r2_score from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_log_error from sklearn.tree import DecisionTreeRegressor

경고메세지 끄기

import warnings warnings.filterwarnings(action=’ignore’)

fish_df = pd.read_csv(‘./data/fish.csv’)

데이터 분석

pass

데이터 전처리

y_data = fish_df[‘무게’] x_data = fish_df.drop(‘무게’,axis=1) # fish_df[‘길이’]로 하면 안됨.

x_train, x_test, y_train, y_test = train_test_split(x_data, y_data, test_size=0.3, random_state=42)

모델 생성

model = DecisionTreeRegressor(random_state=43,max_depth=5) # (random_state=111,min_samples_leaf=2,max_depth=4)

모델 학습

model.fit(x_train, y_train)

모델 검증

모델 검증1. 함수로 출력

print(f’훈련_R2: {model.score(x_train, y_train)}’) print(f’테스트_R2: {model.score(x_test, y_test)}’)

y_predict = model.predict(x_test) ## 주의: 테스트 데이터에 대해 평가해야함! evaluate_reg_all(y_test,y_predict)

모델 예측

x_real = np.array([ [50] ]) y_real_predict = model.predict(x_real)

print(f’예측값:{y_real_predict[0]}’)

```

This post is licensed under CC BY 4.0 by the author.