Life and Tech Talk

머신러닝 회귀 모델 성능 비교
#!/usr/bin/env python3
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import mean_absolute_error # MAE(평균 절대값 오차) 
from sklearn.metrics import mean_squared_error  # MSE(평균 제곱 오차)
from sklearn.preprocessing import StandardScaler


# 문제 정의: 보스턴 집값 예측 문제
df=pd.read_csv('boston.csv')
print(df)
print(df.var())  # 컬럼에 있는 값이 모두 같은지 확인하기 위해 분산 함수 사용

# 데이터 전처리
X = StandardScaler().fit_transform(df.loc[:, df.columns!='PRICE'])
from sklearn.model_selection import train_test_split
x_tr, x_te, y_tr, y_te = train_test_split(X, df['PRICE'], test_size=0.2, random_state=1234)
x_tr.shape


# 모델별 성능 비교
from sklearn.neighbors import KNeighborsRegressor
model = KNeighborsRegressor().fit(x_tr, y_tr)
score1 = model.score(x_tr, y_tr), model.score(x_te, y_te) # 모델 평가 
error1_mae = mean_absolute_error(y_te, model.predict(x_te)) # x_test에 대한 예측값과 실제 값을 비교
error1_mse = mean_squared_error(y_te, model.predict(x_te))

from sklearn.linear_model import LinearRegression
model = LinearRegression().fit(x_tr, y_tr)
score2 = model.score(x_tr, y_tr), model.score(x_te, y_te)
error2_mae = mean_absolute_error(y_te, model.predict(x_te))
error2_mse = mean_squared_error(y_te, model.predict(x_te))

from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor().fit(x_tr, y_tr)
score3 = model.score(x_tr, y_tr), model.score(x_te, y_te)
error3_mae = mean_absolute_error(y_te, model.predict(x_te))
error3_mse = mean_squared_error(y_te, model.predict(x_te))

from sklearn.ensemble import GradientBoostingRegressor
model = GradientBoostingRegressor().fit(x_tr, y_tr)
score4 = model.score(x_tr, y_tr), model.score(x_te, y_te)
error4_mae = mean_absolute_error(y_te, model.predict(x_te))
error4_mse = mean_squared_error(y_te, model.predict(x_te))

from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor(n_estimators = 500, random_state=0).fit(x_tr, y_tr)
score5 = model.score(x_tr, y_tr), model.score(x_te, y_te)
error5_mae = mean_absolute_error(y_te, model.predict(x_te))
error5_mse = mean_squared_error(y_te, model.predict(x_te))

# from lightgbm import LGBMRegressor
# model = LGBMRegressor().fit(x_tr, y_tr) # n_estimators : 500 하면 결과가 더 안좋아짐 
# score6 = model.score(x_tr, y_tr), model.score(x_te, y_te)
# error6 = mean_absolute_error(y_te, model.predict(x_te))

# from xgboost import XGBRegressor
# model = XGBRegressor(learning_rate=0.01, n_estimators=750).fit(x_tr, y_tr) 
# score7 = model.score(x_tr, y_tr), model.score(x_te, y_te)
# error7 = mean_absolute_error(y_te, model.predict(x_te))

print("\n***** Model Score 비교 *****")
print("KNeighbor(Train 모델, Test 모델): {:.3f}, {:.3f}".format(score1[0], score1[1]))
print("Linear Regression(Train 모델, Test 모델): {:.3f}, {:.3f}".format(score2[0], score2[1]))
print("Dicsion Tree Regression(Train 모델, Test 모델): {:.3f}, {:.3f}".format(score3[0], score3[1]))
print("Gradient Boosting Regresson(Train 모델, Test 모델): {:.3f}, {:.3f}".format(score4[0], score4[1]))
print("Random Forest Regression(Train 모델, Test 모델): {:.3f}, {:.3f}".format(score5[0], score5[1]))
# print("Light GBM Regresson: ", score6)
# print("XGB Regression: ", score7)
print("\n***** Error(MAE, MSE) 비교 *****")
print("KNeighbor(MAE, MSE): {:.2f}, {:.2f}".format(error1_mae, error1_mse))
print("Linear Regression(MAE, MSE): {:.2f}, {:.2f}".format(error2_mae, error2_mse))
print("Dicsion Tree Regression(MAE, MSE): {:.2f}, {:.2f}".format(error3_mae, error3_mse))
print("Gradient Boosting Regresson(MAE, MSE): {:.2f}, {:.2f}".format(error4_mae, error4_mse))
print("Random Forest Regression(MAE, MSE): {:.2f}, {:.2f}".format(error5_mae, error5_mse))
올린날: 2024년 2월 3일
주제: 코드 관련 포스팅 클릭!!

* 올린이: 마이클

* VIEW: 36       0           위키홈     게시판     수정