본문 바로가기

코딩으로 익히는 Python/머신러닝

[Python] 2. 머신러닝_회귀

728x90
반응형
SMALL
# 경고 메시지가 안나오게.. import warnings warnings.filterwarnings('ignore') # 기본 import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # KFold from sklearn.model_selection import KFold from sklearn.model_selection import StratifiedKFold # 교차 검증 함수 from sklearn.model_selection import cross_val_score from sklearn.model_selection import cross_validate # 데이터 전처리 from sklearn.preprocessing import LabelEncoder from sklearn.preprocessing import StandardScaler # 하이퍼 파라미터 튜닝 from sklearn.model_selection import GridSearchCV # 평가함수 from sklearn.metrics import accuracy_score # 머신러닝 알고리즘 - 분류 from sklearn.neighbors import KNeighborsClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import SVC from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import GradientBoostingClassifier from xgboost import XGBClassifier # 머신러닝 알고리즘 - 회귀 from sklearn.neighbors import KNeighborsRegressor from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge from sklearn.linear_model import Lasso from sklearn.linear_model import ElasticNet from sklearn.svm import SVR from sklearn.tree import DecisionTreeRegressor from sklearn.ensemble import RandomForestRegressor from sklearn.ensemble import GradientBoostingRegressor from xgboost import XGBRegressor # 저장 import pickle # 그래프 설정 plt.rcParams['font.family'] = 'Malgun Gothic' # plt.rcParams['font.family'] = 'AppleGothic' plt.rcParams['font.size'] = 16 plt.rcParams['figure.figsize'] = 20, 10 plt.rcParams['axes.unicode_minus'] = False

데이터 준비

데이터 불러오기 (pd.read_csv)
python 파일 경로에 만든 후 data폴더에 다음의 'boston.csv' 파일 넣어놓기

boston.csv
0.02MB

 

df1 = pd.read_csv('data/boston.csv') df1.head()

머신러닝을 위한 전처리

x = df1.drop('target', axis=1) y = df1['target'] display(x) display(y)

scaler1 = StandardScaler() scaler1.fit(x) x = scaler1.transform(x) x
[OUT] : array([[-0.63326028, 0.12485095, -1.03628034, ..., -1.07088823, 0.41031054, -0.92655695], [-0.60097475, -0.58885279, -0.25831126, ..., 0.06047401, 0.41031054, -0.22972861], [-0.60100552, -0.58885279, -0.25831126, ..., 0.06047401, 0.31149419, -1.08568842], ..., [-0.56479774, -0.58885279, -0.56557636, ..., 1.14658176, 0.23574309, -0.80930218], [-0.5854857 , -0.58885279, -0.56557636, ..., 1.14658176, 0.22821654, -0.63006989], [-0.58205565, -0.58885279, -0.56557636, ..., 1.14658176, 0.41031054, -0.41901131]])

모델 선정

# KFold 생성 : 교차 검증을 위해 데이터 구성을 하는 작업 fold1 = KFold(n_splits=10, shuffle=True, random_state=1)


KNN

# 하이퍼 파라미터 튜닝 params = { 'n_neighbors' : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } model1 = KNeighborsRegressor() grid1 = GridSearchCV(model1, param_grid=params, scoring='r2', cv=fold1) grid1.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid1.best_params_}') print(f'최적의 모델 평균 성능 : {grid1.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'n_neighbors': 3} 최적의 모델 평균 성능 : 0.8376627503363364


선형 모델

  • LinearRegrssion : 가장 기본적인 선형 회귀, 통계에서의 선형 회귀에 해당한다.
  • Ridge : LinearRegression에서 규제함수 l2를 추가 한것.
  • Lasso : Linearregression에서 규제함수 l1을 추가 한것.
  • ElasticNet : Ridge와 Lasso의 절충안.

# Ridge params = { # 값이 낮으면 규제가 약해지고 값이 크면 규제가 강해진다 'alpha' : [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 1000] } model3 = Ridge() grid3 = GridSearchCV(model3, param_grid=params, scoring='r2', cv=fold1) grid3.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid3.best_params_}') print(f'최적의 모델 평균 성능 : {grid3.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'alpha': 1} 최적의 모델 평균 성능 : 0.851004741748298

# Lasso params = { # 값이 낮으면 규제가 약해지고 값이 크면 규제가 강해진다 'alpha' : [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 1000] } model4 = Lasso() grid4 = GridSearchCV(model4, param_grid=params, scoring='r2', cv=fold1) grid4.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid4.best_params_}') print(f'최적의 모델 평균 성능 : {grid4.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'alpha': 0.0001} 최적의 모델 평균 성능 : 0.8509776005061424

# ElasticNet params = { # 값이 낮으면 규제가 약해지고 값이 크면 규제가 강해진다 'alpha' : [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 1000] } model5 = ElasticNet() grid5 = GridSearchCV(model5, param_grid=params, scoring='r2', cv=fold1) grid5.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid5.best_params_}') print(f'최적의 모델 평균 성능 : {grid5.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'alpha': 0.01} 최적의 모델 평균 성능 : 0.8509925475043933

# SVR params = { # 값이 크면 규제가 약해지고, 값이 작으면 규제가 강해진다. 'C' : [0.0001, 0.001, 0.01, 0.1, 1, 10, 100, 1000, 10000] } model6 = SVR() grid6 = GridSearchCV(model6, param_grid=params, scoring='r2', cv=fold1) grid6.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid6.best_params_}') print(f'최적의 모델 평균 성능 : {grid6.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'C': 100} 최적의 모델 평균 성능 : 0.9086789533233992

결정트리

# 결정트리 params = { # 질문의 깊이 'max_depth' : [None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } model7 = DecisionTreeRegressor() grid7 = GridSearchCV(model7, param_grid=params, scoring='r2', cv=fold1) grid7.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid7.best_params_}') print(f'최적의 모델 평균 성능 : {grid7.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'max_depth': 5} 최적의 모델 평균 성능 : 0.8502108252024421

앙상블

params = { # 트리의 개수 'n_estimators' : [10, 50, 100, 150, 200], # 질문 깊이 'max_depth' : [None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } model8 = RandomForestRegressor() grid8 = GridSearchCV(model8, param_grid=params, scoring='r2', cv=fold1) grid8.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid8.best_params_}') print(f'최적의 모델 평균 성능 : {grid8.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'max_depth': 10, 'n_estimators': 100} 최적의 모델 평균 성능 : 0.8997741099362445

params = { # 트리의 개수 'n_estimators' : [10, 50, 100, 150, 200], # 질문 깊이 'max_depth' : [None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } model9 = GradientBoostingRegressor() grid9 = GridSearchCV(model9, param_grid=params, scoring='r2', cv=fold1) grid9.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid9.best_params_}') print(f'최적의 모델 평균 성능 : {grid9.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'max_depth': 3, 'n_estimators': 150} 최적의 모델 평균 성능 : 0.9142126290224757

params = { # 트리의 개수 'n_estimators' : [10, 50, 100, 150, 200], # 질문 깊이 'max_depth' : [None, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } model10 = XGBRegressor(silent=True, verbosity=0, tree_method='gpu_hist') grid10 = GridSearchCV(model10, param_grid=params, scoring='r2', cv=fold1) grid10.fit(x, y) print(f'최적의 하이퍼 파라미터 : {grid10.best_params_}') print(f'최적의 모델 평균 성능 : {grid10.best_score_}')
[OUT] : 최적의 하이퍼 파라미터 : {'max_depth': 2, 'n_estimators': 200} 최적의 모델 평균 성능 : 0.9047450804232156

best1 = grid1.best_estimator_ best2 = LinearRegression() best3 = grid3.best_estimator_ best4 = grid4.best_estimator_ best5 = grid5.best_estimator_ best6 = grid6.best_estimator_ best7 = grid7.best_estimator_ best8 = grid8.best_estimator_ best9 = grid9.best_estimator_ best10 = grid10.best_estimator_

print(best1) print(best2) print(best3) print(best4) print(best5) print(best6) print(best7) print(best8) print(best9) print(best10)
[OUT] : KNeighborsRegressor(n_neighbors=3) LinearRegression() Ridge(alpha=1) Lasso(alpha=0.0001) ElasticNet(alpha=0.01) SVR(C=100) DecisionTreeRegressor(max_depth=5) RandomForestRegressor(max_depth=10) GradientBoostingRegressor(n_estimators=150) XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, gamma=0, gpu_id=0, importance_type='gain', interaction_constraints='', learning_rate=0.300000012, max_delta_step=0, max_depth=2, min_child_weight=1, missing=nan, monotone_constraints='()', n_estimators=200, n_jobs=12, num_parallel_tree=1, random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, silent=True, subsample=1, tree_method='gpu_hist', validate_parameters=1, verbosity=0)

# 교차 검증 r1 = cross_val_score(best1, x, y, scoring='r2', cv=fold1) r2 = cross_val_score(best2, x, y, scoring='r2', cv=fold1) r3 = cross_val_score(best3, x, y, scoring='r2', cv=fold1) r4 = cross_val_score(best4, x, y, scoring='r2', cv=fold1) r5 = cross_val_score(best5, x, y, scoring='r2', cv=fold1) r6 = cross_val_score(best6, x, y, scoring='r2', cv=fold1) r7 = cross_val_score(best7, x, y, scoring='r2', cv=fold1) r8 = cross_val_score(best8, x, y, scoring='r2', cv=fold1) r9 = cross_val_score(best9, x, y, scoring='r2', cv=fold1) r10 = cross_val_score(best10, x, y, scoring='r2', cv=fold1)

# 평균 성능 출력 print(r1.mean()) print(r2.mean()) print(r3.mean()) print(r4.mean()) print(r5.mean()) print(r6.mean()) print(r7.mean()) print(r8.mean()) print(r9.mean()) print(r10.mean())
[OUT] : 0.8376627503363364 0.8509777564842589 0.851004741748298 0.8509776005061424 0.8509925475043933 0.9086789533233992 0.8403694300798271 0.8986578110715369 0.9139323024461488 0.9047450804232156

plt.plot(r1, label='KNN') plt.plot(r2, label='LinearRegrssion') plt.plot(r3, label='Ridge') plt.plot(r4, label='Lasso') plt.plot(r5, label='ElasticNet') plt.plot(r6, label='SVR') plt.plot(r7, label='DecisionTree') plt.plot(r8, label='RandomForest') plt.plot(r9, label='GradianBoosting') plt.plot(r10, label='XGBoost') plt.legend() plt.ylim(0, 1.2) plt.show()

# 모든 모델에 데이터를 학습시킨다. best1.fit(x, y) best2.fit(x, y) best3.fit(x, y) best4.fit(x, y) best5.fit(x, y) best6.fit(x, y) best7.fit(x, y) best8.fit(x, y) best9.fit(x, y) best10.fit(x, y)
[OUT] : XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1, colsample_bynode=1, colsample_bytree=1, gamma=0, gpu_id=0, importance_type='gain', interaction_constraints='', learning_rate=0.300000012, max_delta_step=0, max_depth=2, min_child_weight=1, missing=nan, monotone_constraints='()', n_estimators=200, n_jobs=12, num_parallel_tree=1, random_state=0, reg_alpha=0, reg_lambda=1, scale_pos_weight=1, silent=True, subsample=1, tree_method='gpu_hist', validate_parameters=1, verbosity=0)

# 예측 결과를 추출한다. pred1 = best1.predict(x) pred2 = best2.predict(x) pred3 = best3.predict(x) pred4 = best4.predict(x) pred5 = best5.predict(x) pred6 = best6.predict(x) pred7 = best7.predict(x) pred8 = best8.predict(x) pred9 = best9.predict(x) pred10 = best10.predict(x)

#KNN plt.plot(y, label='original') plt.plot(pred1, label='prediction') plt.title('KNN') plt.legend() plt.show()

#LinearRegrssion plt.plot(y, label='original') plt.plot(pred2, label='prediction') plt.title('LinearRegrssion') plt.legend() plt.show()

#Ridge plt.plot(y, label='original') plt.plot(pred3, label='prediction') plt.title('Ridge') plt.legend() plt.show()

#Lasso plt.plot(y, label='original') plt.plot(pred4, label='prediction') plt.title('Lasso') plt.legend() plt.show()

#ElasticNet plt.plot(y, label='original') plt.plot(pred5, label='prediction') plt.title('ElasticNet') plt.legend() plt.show()

#SVR plt.plot(y, label='original') plt.plot(pred6, label='prediction') plt.title('SVR') plt.legend() plt.show()

#DecistionTreeRegressor plt.plot(y, label='original') plt.plot(pred7, label='prediction') plt.title('DecisionTree') plt.legend() plt.show()

#RandomForest plt.plot(y, label='original') plt.plot(pred8, label='prediction') plt.title('RandomForest') plt.legend() plt.show()

#GradianBoosting plt.plot(y, label='original') plt.plot(pred9, label='prediction') plt.title('GradianBoosting') plt.legend() plt.show()

#XGBoost plt.plot(y, label='original') plt.plot(pred10, label='prediction') plt.title('XGBoost') plt.legend() plt.show()

예측 결과 가져오기

데이터 불러오기 (pd.read_csv)
python 파일 경로에 만든 후 data폴더에 다음의 'boston_new.csv' 파일 넣어놓기

boston_new.csv
0.01MB

df2 = pd.read_csv('data/boston_new.csv') df2.head()

x2 = scaler1.transform(df2) x2
[OUT] : array([[-0.59026931, -0.58885279, -0.56557636, ..., 1.14658176, 0.41031054, -0.11917412], [-0.59620652, -0.58885279, -0.56557636, ..., 1.14658176, 0.35956701, 0.00813106], [-0.59213046, -0.58885279, -0.56557636, ..., 1.14658176, 0.39185835, -0.3352579 ], ..., [-0.54952402, -0.58885279, 0.5360017 , ..., 1.50861767, 0.41031054, -0.81600245], [-0.47441672, -0.58885279, 0.5360017 , ..., 1.50861767, 0.3265473 , -0.67529673], [-0.57005817, -0.58885279, 0.5360017 , ..., 1.50861767, 0.41031054, -0.4407872 ]])

pred100 = best6.predict(x2) pred100
[OUT] : array([20.51501073, 19.97609198, 22.07743581, 21.57850312, 20.63577072, 33.09434575, 19.41991211, 27.24836563, 33.45943581, 20.67432748, 18.61799618, 25.91578457, 28.15750737, 29.28080029, 26.30081614, 28.60607442, 26.49084744, 32.05948208, 25.50885044, 26.41668337, 25.76754983, 25.76756237, 25.76754901, 25.7675969 , 25.76757751, 25.76761111, 25.76762899, 25.76754399, 25.76761443, 25.7675572 , 25.76760232, 25.76754974, 25.76757203, 25.76755395, 25.76755086, 25.76754984, 25.7675498 , 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.7675498 , 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76755005, 25.76755148, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76755108, 25.76755316, 25.76755948, 25.76754974, 25.76755023, 25.76754974, 25.76755019, 25.76755585, 25.76755188, 25.76754974, 25.7675498 , 25.76754974, 25.76754974, 25.76754985, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76755105, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76755105, 25.76754974, 25.76754904, 25.76754971, 25.76754974, 25.76754974, 25.76754974, 25.76754889, 25.76754972, 25.76754965, 25.76754974, 25.76754783, 25.76754151, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754974, 25.76754997, 25.76754974, 25.76754984, 25.76755613, 25.7675498 , 25.76754974, 25.76754974, 25.76755063, 25.7675498 , 25.76754994, 25.76755067, 25.76754834, 25.7675541 , 25.76756329, 25.76755023, 25.76754973, 25.76753516, 25.76753623, 25.76754959, 25.76755002, 25.76755293, 25.76755025, 25.76766789, 25.7675529 , 25.76755507, 25.76755063, 25.76775971, 25.76753035, 25.76758249, 25.76754974, 25.76754974, 25.7676254 , 25.76767469, 25.76775314, 25.76759605, 25.76755048, 25.76755064, 25.76757794, 25.76754974, 25.76754976, 25.76754974, 25.76755884, 25.76755879, 25.76755705, 25.76792666, 25.76799283, 25.76774188, 25.76755972, 25.7675936 , 21.63329389, 22.14159748, 22.80017235, 21.55155693, 22.22613197, 20.98619541, 22.98468362, 22.03471005, 20.78061473, 20.57386093, 21.99685551, 20.14524309, 20.83824721, 19.28180837, 16.79624365, 19.75797992, 19.04362365, 16.43691347])

df2['target'] = pred100

df2.to_csv('data/boston_result.csv')

728x90
반응형
LIST

'코딩으로 익히는 Python > 머신러닝' 카테고리의 다른 글

[Python] 1. 머신러닝_분류  (0) 2021.02.03