https://www.kaggle.com/code/jimmyyeung/house-regression-beginner-catboost-top-2/notebook
🔥House Regression: Beginner Catboost (Top 2%)🚀
Explore and run machine learning code with Kaggle Notebooks | Using data from multiple data sources
www.kaggle.com
위의 글을 보고 참고하여 작성하였습니다.
마지막으로 모델링하고 제출해 보겠습니다.
pd.get_dummies() 함수는 범주형 변수를 원 - 핫 인코딩하여 새로운 이진 함수를 생성합니다.
train_test_dummy = pd.get_dummies(train_test)
train_test_dummy
train_test_dummy 데이터프레임에서 수치형 변수의 왜도를 계산하고, 왜도가 0.5를 초과하는 변수들에 대해 로그변환을 적용하는 과정입니다.
# 수치형 변수의 열 이름을 추출하여 numeric_features에 저장
numeric_features = train_test_dummy.dtypes[train_test_dummy.dtypes != object].index
# 변수들의 왜도를 계산하고, 이를 내림차순으로 정렬하여 저장
skewed_features = train_test_dummy[numeric_features].apply(lambda x: skew(x)).sort_values(ascending=False)
# 왜도가 0.5를 초과하는 변수들만 선택
high_skew = skewed_features[skewed_features > 0.5]
skew_index = high_skew.index
# 로그변환 적용
for i in skew_index:
train_test_dummy[i] = np.log1p(train_test_dummy[i])
SalePrice 변수의 로그 변환 후 분포와 QQ 플롯을 시각화합니다.
# target 설정 및 로그 변환
target = train['SalePrice']
target_log = np.log1p(target)
# 서브플롯 생성
fig, ax = plt.subplots(1, 2, figsize=(15,5))
fig.suptitle('qq-plot & distribution SalePrice', fontsize=15)
# QQ plot
sm.qqplot(target_log, stats.t, distargs=(4,), fit=True, line='45', ax=ax[0])
#분포 plot
sns.distplot(target_log, kde=True, hist=True, fit=norm, ax=ax[1])
plt.show()
HighQualSF 열의 로그 변환 값을 계산하고, 이 값을 사용하여 QQ 플롯과 분포 그래프를 그린 후, 원래 데이터 프레임에 변환된 값을 다시 저장합니다.
#로그 변환
HighQualSF_log = np.log1p(train_test["HighQualSF"])
fig, ax = plt.subplots(1, 2, figsize= (15, 5))
fig.suptitle("qq-plot & distribution SalePrice ", fontsize=15)
# QQ plot
sm.qqplot(HighQualSF_log, stats.t, distargs=(4,), fit=True, line="45", ax=ax[0])
# 히스토그램과 커널 밀도 추청(kde)으로 그림
sns.distplot(HighQualSF_log, kde=True, hist=True, fit=norm, ax=ax[1])
plt.show()
# 변환된 값을 다시 저장
train_test["HighQualSF"] = HighQualSF_log
GrLivArea 열의 로그 변환 값을 계산하고, 이 값을 사용하여 QQ 플롯과 분포 그래프를 그린 후, 원래 데이터 프레임에 변환된 값을 다시 저장합니다.
GrLivArea_log = np.log1p(train_test["GrLivArea"])
fig, ax = plt.subplots(1, 2, figsize= (15,5))
fig.suptitle("qq-plot & distribution SalePrice ", fontsize=15)
sm.qqplot(GrLivArea_log, stats.t, distargs=(4,), fit=True, line="45", ax=ax[0])
sns.distplot(GrLivArea_log, kde=True, hist=True, fit = norm, ax=ax[1])
plt.show()
train_test["GrLivArea"]= GrLivArea_log
train_test_dummy 데이터프레임을 사용하여 train과 test 데이터프레임으로 나누고, test 데이터프레임에서 'SalePrice' 열을 삭제합니다.
train = train_test_dummy[0:2930]
test = train_test_dummy[2930:]
test.drop('SalePrice', axis=1, inplace=True)
학습용 (X_train, y_train)과 검증용 (X_val, y_val)으로 나눕니다.
X_train과 y_train이 전체 데이터를 포함하게 되며, X_val, y_val은 train_test_split 함수에 의해 분할된 검증용 데이터입니다.
ytrain = target_log
xtrain = train.drop('SalePrice', axis=1)
X_train, X_val, y_train, y_val = train_test_split(xtrain, ytrain, test_size=0.5, random_state=42 )
X_train, y_train = xtrain, ytrain
X_train
X_val
최적의 하이퍼파라미터를 사용하여 CatBoostRegressor를 초기화하고, 주어진 학습 데이터로 모델을 학습한 후 테스트 데이터에 대한 예측을 수행합니다.
final_model = CatBoostRegressor(random_seed=42)
final_model.fit(X_train, y_train, eval_set=(X_val, y_val), verbose=False)
final_model.get_all_params()
{'nan_mode': 'Min',
'eval_metric': 'RMSE',
'iterations': 1000,
'sampling_frequency': 'PerTree',
'leaf_estimation_method': 'Newton',
'random_score_type': 'NormalWithModelSizeDecrease',
'grow_policy': 'SymmetricTree',
'penalties_coefficient': 1,
'boosting_type': 'Plain',
'model_shrink_mode': 'Constant',
'feature_border_type': 'GreedyLogSum',
'bayesian_matrix_reg': 0.10000000149011612,
'eval_fraction': 0,
'force_unit_auto_pair_weights': False,
'l2_leaf_reg': 3,
'random_strength': 1,
'rsm': 1,
'boost_from_average': True,
'model_size_reg': 0.5,
'pool_metainfo_options': {'tags': {}},
'subsample': 0.800000011920929,
'use_best_model': True,
'random_seed': 42,
'depth': 6,
'posterior_sampling': False,
'border_count': 254,
'classes_count': 0,
'auto_class_weights': 'None',
'sparse_features_conflict_fraction': 0,
'leaf_estimation_backtracking': 'AnyImprovement',
'best_model_min_trees': 1,
'model_shrink_rate': 0,
'min_data_in_leaf': 1,
'loss_function': 'RMSE',
'learning_rate': 0.06028300151228905,
'score_function': 'Cosine',
'task_type': 'CPU',
'leaf_estimation_iterations': 1,
'bootstrap_type': 'MVS',
'max_leaves': 64}
성능 측정 지표 RMSE 계산
def rmse(y, y_pred):
return np.sqrt(mean_squared_error(y, y_pred))
final_pred = final_model.predict(X_val)
final_score = rmse(y_val, final_pred)
final_score
0.04005029112771279
파일 제출
submission = pd.read_csv('/kaggle/input/house-prices-advanced-regression-techniques/sample_submission.csv')
test_pred = np.expm1(final_model.predict(test))
submission['SalePrice'] = test_pred
submission
'캐글(Kaggle) > 프로젝트' 카테고리의 다른 글
Kaggle(캐글) - 주택 가격 예측 초보자 튜토리얼[Hellfer](3) (0) | 2024.07.08 |
---|---|
Kaggle(캐글) - 주택 가격 예측 초보자 튜토리얼[Hellfer](2) (0) | 2024.07.08 |
Kaggle(캐글) - 주택 가격 예측 초보자 튜토리얼[Hellfer](1) (0) | 2024.07.07 |
Kaggle(캐글) - 타이타닉 생존자 예측 초보자 튜토리얼[Hellfer](5) (0) | 2024.06.29 |
Kaggle(캐글) - 타이타닉 생존자 예측 초보자 튜토리얼[Hellfer](4) (0) | 2024.06.28 |
Kaggle(캐글) - 타이타닉 생존자 예측 초보자 튜토리얼[Hellfer](3) (0) | 2024.06.28 |
Kaggle(캐글) - 타이타닉 생존자 예측 초보자 튜토리얼[Hellfer](2) (0) | 2024.06.28 |
Kaggle(캐글) - 타이타닉 생존자 예측 초보자 튜토리얼[Hellfer](1) (0) | 2024.06.27 |