1. Tips on Discovering New Features
- Data docment에 언급된 feature를 이해한다
- 도메인 지식을 얻기위해 여러 자료를 통해 조사한다
- 이전 연구에서 어떻게 모델링 및 EDA를 진행했는지 살펴본다
- 데이터 시각화를 통해 feature에 대한 이해를 높인다
2. Mathematical Transforms
연속형 변수에대한 관계는 수학적 공식을 통해 표현될 수 있다. 판다스 라이브러리에서는 수학적 연산을 apply하여 데이터를 새롭게 변환할 수 있으며, 제곱이나 로그변환을 통해 모양을 바꿀 수 있다.
# 2) Mathematical Tranform
autos["displacement"] = (
np.pi * ((0.5 * autos.bore) ** 2) * autos.stroke * autos.num_of_cylinders
)
# If the feature has 0.0 values, use np.log1p (log(1+x)) instead of np.log
accidents["LogWindSpeed"] = accidents.WindSpeed.apply(np.log1p)
3. Counts
어떤 집합에 부재 혹은 존재, 양성 혹은 음성을 표현하기 위해 boolean type을 이용하여 데이터를 표현하는 경우가 있다. 이런 변수들을 상위 변수를 생성하여 얼마나 많은 특성들이 발생했는지를 나타내줄 수 있다.
# 3) Counts
roadway_features = ["Amenity", "Bump", "Crossing", "GiveWay",
"Junction", "NoExit", "Railway", "Roundabout", "Station", "Stop",
"TrafficCalming", "TrafficSignal"]
accidents["RoadwayFeatures"] = accidents[roadway_features].sum(axis=1)
4. Building-up and Breaking-down Features**
- ID numbers : '123-456-789'
- Phone numbers : '(999) 555-0123'
- Stret address : '8241 Kaggle Ln., Goose City, NV'
위와 같은 변수들은 함축적인 정보들을 추출할 수 있는데, 전화번호를 통해 나라와 지역을, 우편변호를 통해 도시를 알 수 있다. 대부분의 이런 정보들은 string type으로 구성되어 있는데, str.split()연산자를 통해 이런 정보들을 추출할 수 있다.
5. Group Transforms
Gropu Transforms는 특정 범주에 따라 가지고 있는 통계량을 요약하는 방식으로 데이터를 변환한다. 예를 들어 "주에 따른 평균 수입"이라는 새로운 변수명에서는 주에 따라 데이터를 grouping한 이후 평균값을 계산하여 실제 데이터 셋에 각각의 평균값을 붙여 넣게 된다.
customer['AverageIncome'] = (
customer.groupby('State')['Income']
.transform("mean")
)
# Frequency of categorical value
customer['StateFreq'] = (
customer.groupby('State')['State']
.transform('count') / customer.State.count()
)
6. Tips on Creating Features
- Linear models learn sums and differneces naturally, but can't learn anything more complex.
- Ratios seem to be difficult for most model to learn. Ratio combinations often lead to some easy performance gains.
- Linear models and neural nets generally do better with normalized features. Neural nets especially need features scaled to valud not too far from 0. Tree-based models (like random forest and XGBoost) can sometimes benefit from normalization, but usually much less so.
- Tree models can learn to approximate almost any combination of features, but when a combination is expecially important they can still benefit from having it explicitly created, especially when data is limited.
- Counts are especially helpful for tree models, since these models don't have a natural way of aggregating information across many features at once.
7. Exercise : Creating Features
Step 1 : Creating Mathematical Transforms
# YOUR CODE HERE
X_1 = pd.DataFrame() # dataframe to hold new features
X_1["LivLotRatio"] = df['GrLivArea']/df['LotArea']
X_1["Spaciousness"] = df[['FirstFlrSF', 'SecondFlrSF']].apply(np.sum, axis = 1)/df['TotRmsAbvGrd']
X_1["TotalOutsideSF"] = df[['WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch',
'Threeseasonporch', 'ScreenPorch']].apply(np.sum, axis = 1)
Step 2 : Interaction with a Categorical
# YOUR CODE HERE
# One-hot encode BldgType. Use `prefix="Bldg"` in `get_dummies`
X_2 = pd.get_dummies(df['BldgType'], prefix = 'Bldg')
# Multiply
X_2 = X_2.mul(df['GrLivArea'], axis = 0)
X_2.head()
Step 3 : Count Feature
X_3 = pd.DataFrame()
# YOUR CODE HERE
components = ['WoodDeckSF', 'OpenPorchSF', 'EnclosedPorch', 'Threeseasonporch', 'ScreenPorch']
X_3["PorchTypes"] = df[components].gt(0).sum(axis = 1)
Step 4 : Break Down a Categorical Feature
X_4 = pd.DataFrame()
# YOUR CODE HERE
X_4['MSClass'] = df['MSSubClass'].str.split('_', n = 1, expand = True)[0]
Step 5 : Use a Grouped Tansform
X_5 = pd.DataFrame()
# YOUR CODE HERE
X_5["MedNhbdArea"] = df.groupby('Neighborhood')['GrLivArea'].transform('median')
Source of the course : Kaggle Course _ Creating Features
Creating Features
Explore and run machine learning code with Kaggle Notebooks | Using data from FE Course Data
www.kaggle.com
'Course > [Kaggle] Data Science' 카테고리의 다른 글
[FE] Principal Component Analysis (0) | 2022.02.21 |
---|---|
[FE] Clustering with K-means (0) | 2022.02.21 |
[FE] Mutual Information (0) | 2022.02.21 |
[ML] GridSearchCV (0) | 2022.02.19 |
[ML] Data Leakage (0) | 2022.02.19 |