→오늘 아침부터 현재 오후 3시까지 인코딩 디코딩 관련해서만 계속 들여다보고 싸우고 있었다... 인코딩 자체를 진행해서 모델에 넣는 것 까지는 한줄 혹은 두줄로 매우 쉽게 할 수 있었지만, 인코딩된 데이터를 학습 이후에 시각화 하기 위해서 디코딩을 하려고 하면 계속 오류가 나서 함수를 재정의하고, 재정의 하고 그러다 보니까 시간이 훌쩍 지나있었다 ㅠ 원-핫 인코딩을 디코딩 하는 작업은 생각보다 어렵지 않게 끝났는데, TargetEncoder을 사용한 타겟 인코딩을 사용한 피처들에서는 inverse()메소드가 존재하지 않아서 수작업으로 인코딩된 값을 인코딩시에 매핑해놓고, 디코딩시에 매핑된 값을 바탕으로 디코딩 하는 방법을 쓰도록 하였다
→실무에서는 get_dummies()로 범주형 데이터 원핫인코딩을 하지 않는다는 얘기를 들어서 무리해서라도 OneHotEncoder을 사용해보려고 하고 있지만, 아직은 익숙하지 않고 어렵다
●결국 해결한 원핫-인코딩, 타겟 인코딩 코드(물론 혼자 하진 않았고, 강사님과 AI의 도움을 조금,, 받았다)
#TargetEnc
self.Targetenc.fit(df[self.target_cols], df['y'])
encoded = pd.DataFrame(self.Targetenc.transform(df[self.target_cols]),
columns = self.target_cols,
index = df.index)
for col in self.target_cols :
temp = pd.DataFrame({
'category': df[col],
'value': encoded[col].round(6)
})
self.mappings[col] = (temp.drop_duplicates().set_index('category')['value'].to_dict())
df[self.target_cols] = encoded
#One-HotEnc
self.Onehotenc.fit(df[self.one_hot_cols])
one_hot_data = self.Onehotenc.transform(df[self.one_hot_cols])
one_hot_df = pd.DataFrame(one_hot_data, columns=self.Onehotenc.get_feature_names_out(self.one_hot_cols), index=df.index)
df = df.drop(columns = self.one_hot_cols)
df = pd.concat([df, one_hot_df], axis = 1)
df = df.dropna()
return df
#TargetEncoder Decoding 함수 정의
def inverse_target_encoding(self, df) :
for col in self.target_cols:
mapping = self.mappings[col]
inv_map = {round(v,6): k for k, v in mapping.items()}
df[col] = df[col].round(6).map(inv_map)
return df
주말에 다시 보면서 공부해야겠다.. 내 주말..
'TIL' 카테고리의 다른 글
| [TIL] #7 2026-03-11 (1) | 2026.03.11 |
|---|---|
| [TIL] #6 2026-03-10 (0) | 2026.03.10 |
| [TIL] #4 2026-03-05 (1) | 2026.03.05 |
| [TIL] #3 2026-03-04 (1) | 2026.03.05 |
| [TIL] 2026-02-27 TIL#2 (1) | 2026.02.27 |
