모델의 복잡도와 데이터에 대한 적합도를 함꼐 고려하는 지표
Regression이면 MLE는 RMSE로 정의 → 결국 AIC는 RMSE값에 비례해서 증감
즉, AIC값이 작을수록 좋은 모델
def backward_elimination(df, target_col, feature_cols):
X = sm.add_constant(df[current_cols])
best_aic = sm.OLS(df[target_col], X).fit().aic
while True:
worst_feature = None
best_new_aic = best_aic
for feature in current_cols:
test_cols = [c for c in current_cols if c != feature]
X = sm.add_constant(df[test_cols])
model = sm.OLS(df[target_col], X).fit()
if model.aic < best_new_aic:
best_new_aic = model.aic
worst_feature = feature
if worst_feature is not None:
current_cols.remove(worst_feature)
est_aic = beat_new_aic
else:
break
return current_cols, best_aic
import statsmodels.api as sm
def forward_selection(df, target_col, feature_cols):
selected_cols = []
remaining_cols = list(feature_cols) # 아직 선택 안 된 변수 pool
# 초기 AIC: 절편만 있는 모델
X = sm.add_constant(pd.Series([1] * len(df)))
best_aic = sm.OLS(df[target_col], X).fit().aic
while remaining_cols:
best_feature = None
best_new_aic = best_aic # ← 0이 아닌 현재 AIC 기준
for feature in remaining_cols: # ← 선택 안 된 변수 순회
X = sm.add_constant(df[selected_cols + [feature]]) # ← 리스트로 감싸기
model = sm.OLS(df[target_col], X).fit() # ← target_col (오타 수정)
if model.aic < best_new_aic:
best_new_aic = model.aic
best_feature = feature # ← 최적 변수 기록
if best_feature is not None: # backward의 worst_feature와 동일한 패턴
selected_cols.append(best_feature)
remaining_cols.remove(best_feature) # ← pool에서 제거
best_aic = best_new_aic
else:
break # 개선 없으면 종료
return selected_cols
import statsmodels.api as sm