• ML_1016_01_feature_engineering.ipynb

Feature Scaling

  • StandardScaler : 표준화, 주로 신경망 모델
  • MinMaxScaler : 0~1
  • RobustScaler : oulier에 강함
  • PowerTransformer : 분산 안정화, 왜도 최소화, box-cox와 yeo-johnson변환 지원
#여-존슨 변환은 음의 값에도 적용 가능
# 특정 금액이나 횟수를 나타내는 변수에서는 어느 한 방향으로 치우쳐 뻗은 분포가 되기 쉬우므로 로그 변환을 할 때가 있다. 
# (출처: 데이터가 뛰어노는 AI 놀이터, 캐글)
# 로그변환을 일반화한 박스-칵스 변환, 여-존슨변환 중 음의 값에도 적용할 수 있는 여-존슨 변환 적용 
from sklearn.preprocessing import PowerTransformer

pt=PowerTransformer(method='yeo-johnson')
X_train[num_features]=pt.fit_transform(X_train[num_features])
X_test[num_features]=pt.transform(X_test[num_features])

All about Feature Scaling

Feature Selection

  • Model Based feature Selection
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier

select1 = SelectFromModel(RandomForestClassifier(random_state=0), threshold=None)

X_train_sc3_fs1 = select1.fit(X_train_sc3, y_train).transform(X_train_sc3)

print("X_train_sc3.shape: {}, X_train_sc3_fs1.shape: {}".format(X_train_sc3.shape, X_train_sc3_fs1.shape))

mask = select1.get_support()
plt.matshow(mask.reshape(1,-1), cmap="gray_r")
plt.show()

X_test_sc3_fs1 = select1.transform(X_test_sc3)
svm.fit(X_train_sc3_fs1, y_train).score(X_test_sc3_fs1, y_test)
  • Univarate(단변량) Feature Selection
    -통계 모델 기반
    - y값과 하나의 feature간의 통계적 유의미를 분석
    - 주로 선형 모델에서 유용
from sklearn.feature_selection import SelectKBest

select2 = SelectKBest(k=10)
X_train_sc3_fs2 = select2.fit_transform(X_train_sc3, y_train)
X_train_sc3_fs2.shape

mask = select2.get_support()
plt.matshow(mask.reshape(1,-1), cmap="gray_r")
plt.show()

X_test_sc3_fs2 = select2.transform(X_test_sc3)
svm.fit(X_train_sc3_fs2, y_train).score(X_test_sc3_fs2, y_test)
  • Recursive feature elimination
from sklearn.feature_selection import RFE

select3 = RFE(estimator=RandomForestClassifier(random_state=0), n_features_to_select=10, step=1)
X_train_sc3_fs3 = select3.fit_transform(X_train_sc3, y_train)
X_train_sc3_fs3.shape

X_test_sc3_fs3 = select3.transform(X_test_sc3)
svm.fit(X_train_sc3_fs3, y_train).score(X_test_sc3_fs3, y_test)
  • 다중공선성 고려 Feature 선택(Correaltion)
from collections import Counter
# 관계수 행렬 계산
correlation_matrix = df.corr()

# 상관 계수가 높은 순서대로 feature쌍 추출
pairs =[]
for i in range(len(correlation_matrix.columns)):
	for j in range(i+1, len(correlation_matrix.columns)):
    	pairs.append((correlation_matrix.columns[i], correlation_matrix.columns[j], correlation_matrix.iloc[i,j]))

pairs = sorted(pairs, key=lambda x: -x[2])

# 결과를 DataFrame으로 저장
result_df = pd.DataFrame(pairs, columns =['col1', 'col2', 'correlation'])

# 상관계수 0.7 이상에 존재하는 column만 추출
high_corr_cols = result_df.loc[result_df['Correlation']>0.7, 'col1'].tolist() + result_df.loc[result_df['Correaltion']>0.7, 'col2'].tolsit()

C=Counter(high_corr_cols)  # column 출현 횟수 count 

d_cols = pd.DataFrame(C.most_common()[:10]).iloc[:,0].tolist()  # 출현 횟수 상위 10개 column 제외 
df_ = df.drop(columns= d_cols)  

Feature Generation

  • Automatic generating polynomial and interaction features
from sklearn.preprocessing import PolynomialFeatures
poly = PolynomialFeatures(interaction_only=True) #교호작용 효과만 보겠다. 

poly = PolynomialFeatures(2, include_bias=False)
X_train_sc3_poly = poly.fit_transform(X_train_sc3)
X_test_sc3_poly = poly.transform(X_test_sc3)
print(X_train_sc3_poly.shape, X_test_sc3_poly.shape)

svm.fit(X_train_sc3_poly, y_train).score(X_test_sc3_poly, y_test)

#다시 feature selection 
select2 = SelectKBest(k=20)
X_train_sc3_poly_fs2 = select2.fit(X_train_sc3_poly, y_train).transform(X_train_sc3_poly)
X_test_sc3_poly_fs2 = select2.transform(X_test_sc3_poly)
print(X_train_sc3_poly_fs2.shape)

svm.fit(X_train_sc3_poly_fs2, y_train).score(X_test_sc3_poly_fs2, y_test)

mask = select2.get_support()
np.array(poly.get_feature_names())[mask]
  • ratio features
  • product features : feature importance를 봤을 때, 상위 feature들 중 numerical feature끼리 곱하여 추가함
  • Addition or Subtraction features : 중요한 feature끼리 더하거나 빼서 새로운 feature 생성
  • Aggregation features: Category와 numerical feature의 조합으로 생성하며, Category 각 그룹당 mean, median, variance, standard deviation을 feature로 사용
group_object = credit_card.groupby(by=['SK_ID_CURR'])['AMT_DRAWINGS_ATM_CURRENT'].agg('sum').reset_index()
  • Featuretoos : MIT 알고리즘. 오픈소스 라이브러리
  • feature 생성 예시
for m in [3,6,12]:
    start = str(pd.to_datetime(tr.tran_date.max()) - pd.offsets.MonthBegin(m))
    f = tr.query('tran_date >= @start').groupby('cust_id')['amount'].agg([
        (f'최근{m}개월_구매금액', np.sum), 
        (f'최근{m}개월_구매건수', np.size)
    ]).reset_index()
    display(f)
    features = features.merge(f, how='left'); features
  • Clustering 기반 Feature generation
    Classifiation 문제일 때
### 1. 군집 수 K의 탐색 ###
  results = []
  for k in range(2,51):
      kmeans = MiniBatchKMeans(n_clusters=k)
      pred = kmeans.fit_predict(x_train)
      results.append(v_measure_score(y_train, pred))
  # v_measure_score 시각화 -> k값 선정 
  sns.lineplot(x=range(2,51), y=results);
  sns.lineplot(x=range(2,10), y=results[:8]);
  
### 2. 군집별 특성 확인 ### 
kmeans = MiniBatchKMeans(n_clusters=3)
clusters = pd.DataFrame(x_train, columns=col, index=idx).join(y_train)
clusters['group'] = kmeans.fit_predict(x_train)

clusters.groupby('group').mean().T
# 전체 평균과 각 그룹(cluster)별 평균 
c_summary = pd.DataFrame(clusters.mean(), columns =['overall'])
c_summary = c_summary.join(clusters.groupby('group').mean().T)

# 각 그룹별 평균에서 전체 평균을 뺀 값
c_diff = c_summary.substract(c_summary['overall'], axis=0)
c_diff['overall'] = c_summary['overall']
c_diff  # 각 feature들의 group별 숫자를 보고 중요도에 대한 힌트를 얻을 수 있다. 

### 3. 확률 처리 ### 
churn_prob = clusters.groupby('group')[['churn']].mean().reset_index()
# 어느 그룹이 churn 확률이 높은지 알 수 있다. 
groupchurn
000.119900
110.143210
220.515434
### 5. train ,test에 군집 번호로 feature 추가 ### 
x_train = np.hstack((x_train, kmeans.predict(x_train).reshape(len(x_train), 1)))
x_test = np.hstack((x_test, kmeans.predict(x_test).reshape(len(x_test), 1)))

rf= RandomForestClassifier(max_depth=10)
rf.fit(x_train, y_train)
rf_pred = rf.predict_proba(x_test)
roc_auc_score(y_test, rf_pred(:1])
profile
ML/DL swimmer

0개의 댓글