
지난 시간에는 Datset을 처리하는 과정을 진행했다. 이제 학습 모델을 선정하고 학습을 시킨 후 최종 제출을 해보자!
📌 이전 글
[Kaggle]집값 예측하기(House Prices prediction) - 1
[Kaggle]집값 예측하기(House Prices prediction) - 2
train Data와 test Data를 한꺼번에 처리하기 위해 all dataset을 만들었기 때문에 이것을 다시 split할 필요가 있고, 따로 Valid data를 만들어 학습을 검증하도록 하자.
결측치 처리 과정에서 일부 행을 삭제 했기 때문에 인덱스가 맞는 것끼리 매칭을 하여 train data의 SalePrice를 넣어줘야 한다.
# train, test split
train = all_dataset.loc[all_dataset.index.isin(train_df.index)]
print('Train_data.shape :', train.shape)
test = all_dataset[len(train):]
print('Test_data.shape :', test.shape)
train_df_sale_price = train_df["SalePrice"] # train_df의 SalePrice를 따로 빼두고
train_df_sale_price
train = train.join(train_df_sale_price) # index를 기준으로 데이터프레임 합치기
# index 값 재설정
train.reset_index(drop = True, inplace = True)
test.reset_index(drop = True, inplace = True)
train.shape, test.shape
학습을 검증하기 위해 valid data를 따로 만든다. train data에서 20%를 valid data로 설정한다.
from sklearn.model_selection import train_test_split
X_train = train.drop(['SalePrice'], axis=1)
y_train = train['SalePrice']
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.2, shuffle=True)
print('X_train :', len(X_train))
print('X_val :', len(X_val))
print('y_train :', len(y_train))
print('y_val :', len(y_val))
학습을 위한 데이터를 준비했으니 모델을 선정하여 학습시키자. xgboost와 Lasso 모델을 선택하여 학습을 시킨다.
from sklearn.model_selection import GridSearchCV
from sklearn.metrics import mean_squared_error
from sklearn.linear_model import Lasso
from xgboost import XGBRegressor
xgbreg = XGBRegressor()
Laleg = Lasso()
# GridSearchCV를 사용하기 위해 후보 파라미터 선정
param_xgb = {'max_depth' : [30, 20, 10], 'min_child_weight' : [1, 3, 6, 10],
'n_estimators' : [100, 200, 300], 'learning_rate' : [0.001, 0.003, 0.005, 0.01]}
param_Laleg = {'alpha': [0.001, 0.003, 0.005, 0.01]}
gscv_xgb = GridSearchCV(estimator = xgbreg, param_grid = param_xgb, scoring = 'neg_mean_squared_error', cv = 3, verbose = 2)
gscv_Laleg = GridSearchCV(estimator = Laleg, param_grid = param_Laleg, scoring = 'neg_mean_squared_error', cv = 3, verbose = 2)
gscv_xgb.fit(X_train, y_train)
gscv_Laleg.fit(X_train, y_train)
# xgbreg 학습
xgbreg = XGBRegressor(learning_rate = 0.01, max_depth = 10, min_child_weight = 10, n_estimators = 300, eval_metric= mean_squared_error)
xgbreg.fit(X_train, y_train, eval_set = [(X_val, y_val)])
pred_val = xgbreg.predict(X_val)
mean_squared_error(y_val, pred_val)
>>> 0.023253598358027695
# 결과 제출
pred_test = xgbreg.predict(test)
id_pred_df = pd.DataFrame()
id_pred_df['Id'] = test_id
id_pred_df['SalePrice'] = pred_test
id_pred_df.to_csv('/content/drive/MyDrive/kaggle/house-prices/submission_xgbReg.csv', index=False)
© 참고
Stacked Regressions : Top 4% on LeaderBoard
[Kaggle] 보스턴 주택 가격 예측(House Prices: Advanced Regression Techniques)