一芍秆、特征工程的目標
對于特征進行進一步分析都伪,并對于數(shù)據(jù)進行處理
二、常見的特征工程
1示罗、異常處理:
- 通過箱線圖(或 3-Sigma)分析刪除異常值惩猫;
- BOX-COX 轉(zhuǎn)換(處理有偏分布);
2蚜点、長尾截斷轧房;
- 特征歸一化/標準化:
- 標準化(轉(zhuǎn)換為標準正態(tài)分布);
- 歸一化(抓換到 [0,1] 區(qū)間)绍绘;
- 針對冪律分布锯厢,可以采用公式:
3、數(shù)據(jù)分桶:
- 等頻分桶脯倒;
- 等距分桶实辑;
- Best-KS 分桶(類似利用基尼指數(shù)進行二分類);
- 卡方分桶藻丢;
4剪撬、缺失值處理:
- 不處理(針對類似 XGBoost 等樹模型);
- 刪除(缺失數(shù)據(jù)太多)悠反;
- 插值補全残黑,包括均值/中位數(shù)/眾數(shù)/建模預(yù)測/多重插補/壓縮感知補全/矩陣補全等;
- 分箱斋否,缺失值一個箱梨水;
5、特征構(gòu)造:
- 構(gòu)造統(tǒng)計量特征茵臭,報告計數(shù)疫诽、求和、比例旦委、標準差等奇徒;
- 時間特征,包括相對時間和絕對時間缨硝,節(jié)假日摩钙,雙休日等;
- 地理信息查辩,包括分箱胖笛,分布編碼等方法网持;
- 非線性變換,包括 log/ 平方/ 根號等长踊;
- 特征組合功舀,特征交叉;
- 仁者見仁之斯,智者見智。
6遣铝、特征篩選
- 過濾式(filter):先對數(shù)據(jù)進行特征選擇佑刷,然后在訓(xùn)練學(xué)習(xí)器,常見的方法有 Relief/方差選擇發(fā)/相關(guān)系數(shù)法/卡方檢驗法/互信息法酿炸;
- 包裹式(wrapper):直接把最終將要使用的學(xué)習(xí)器的性能作為特征子集的評價準則瘫絮,常見方法有 LVM(Las Vegas Wrapper) ;
- 嵌入式(embedding):結(jié)合過濾式和包裹式填硕,學(xué)習(xí)器訓(xùn)練過程中自動進行了特征選擇麦萤,常見的有 lasso 回歸;
7扁眯、降維
- PCA/ LDA/ ICA壮莹;
- 特征選擇也是一種降維。
三姻檀、代碼示例
1命满、導(dǎo)入數(shù)據(jù)
#載入常用的庫
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from operator import itemgetter
%matplotlib inline
#導(dǎo)入數(shù)據(jù)
path = 'D:/Backup/桌面/二手車/'
Train_data = pd.read_csv(path+'used_car_train_20200313.csv', sep=' ')
Test_data = pd.read_csv(path+'used_car_testA_20200313.csv', sep=' ')
print(Train_data.shape)
print(Test_data.shape)
#數(shù)據(jù)預(yù)覽
Train_data.head()
Train_data.columns
Test_data.columns
2、刪除異常值
# 這里我包裝了一個異常值處理的代碼绣版,可以隨便調(diào)用胶台。
def outliers_proc(data, col_name, scale=3):
"""
用于清洗異常值,默認用 box_plot(scale=3)進行清洗
:param data: 接收 pandas 數(shù)據(jù)格式
:param col_name: pandas 列名
:param scale: 尺度
:return:
"""
def box_plot_outliers(data_ser, box_scale):
"""
利用箱線圖去除異常值
:param data_ser: 接收 pandas.Series 數(shù)據(jù)格式
:param box_scale: 箱線圖尺度杂抽,
:return:
"""
iqr = box_scale * (data_ser.quantile(0.75) - data_ser.quantile(0.25))
val_low = data_ser.quantile(0.25) - iqr
val_up = data_ser.quantile(0.75) + iqr
rule_low = (data_ser < val_low)
rule_up = (data_ser > val_up)
return (rule_low, rule_up), (val_low, val_up)
data_n = data.copy()
data_series = data_n[col_name]
rule, value = box_plot_outliers(data_series, box_scale=scale)
index = np.arange(data_series.shape[0])[rule[0] | rule[1]]
print("Delete number is: {}".format(len(index)))
data_n = data_n.drop(index)
data_n.reset_index(drop=True, inplace=True)
print("Now column number is: {}".format(data_n.shape[0]))
index_low = np.arange(data_series.shape[0])[rule[0]]
outliers = data_series.iloc[index_low]
print("Description of data less than the lower bound is:")
print(pd.Series(outliers).describe())
index_up = np.arange(data_series.shape[0])[rule[1]]
outliers = data_series.iloc[index_up]
print("Description of data larger than the upper bound is:")
print(pd.Series(outliers).describe())
fig, ax = plt.subplots(1, 2, figsize=(10, 7))
sns.boxplot(y=data[col_name], data=data, palette="Set1", ax=ax[0])
sns.boxplot(y=data_n[col_name], data=data_n, palette="Set1", ax=ax[1])
return data_n
# 我們可以刪掉一些異常數(shù)據(jù)诈唬,以 power 為例。
# 這里刪不刪同學(xué)可以自行判斷
# 但是要注意 test 的數(shù)據(jù)不能刪 = = 不能掩耳盜鈴是不是
Train_data = outliers_proc(Train_data, 'power', scale=3)
3缩麸、特征構(gòu)造
# 訓(xùn)練集和測試集放在一起铸磅,方便構(gòu)造特征
Train_data['train']=1
Test_data['train']=0
data = pd.concat([Train_data, Test_data], ignore_index=True)
# 使用時間:data['creatDate'] - data['regDate'],反應(yīng)汽車使用時間杭朱,一般來說價格與使用時間成反比
# 不過要注意愚屁,數(shù)據(jù)里有時間出錯的格式,所以我們需要 errors='coerce'
data['used_time'] = (pd.to_datetime(data['creatDate'], format='%Y%m%d', errors='coerce') -
pd.to_datetime(data['regDate'], format='%Y%m%d', errors='coerce')).dt.days
# 看一下空數(shù)據(jù)痕檬,有 15k 個樣本的時間是有問題的霎槐,我們可以選擇刪除,也可以選擇放著梦谜。
# 但是這里不建議刪除丘跌,因為刪除缺失數(shù)據(jù)占總樣本量過大袭景,7.5%
# 我們可以先放著,因為如果我們 XGBoost 之類的決策樹闭树,其本身就能處理缺失值耸棒,所以可以不用管;
data['used_time'].isnull().sum()
# 從郵編中提取城市信息报辱,相當于加入了先驗知識
data['city'] = data['regionCode'].apply(lambda x : str(x)[:-3])
data = data
# 計算某品牌的銷售統(tǒng)計量与殃,同學(xué)們還可以計算其他特征的統(tǒng)計量
# 這里要以 train 的數(shù)據(jù)計算統(tǒng)計量
Train_gb = Train_data.groupby("brand")
all_info = {}
for kind, kind_data in Train_gb:
info = {}
kind_data = kind_data[kind_data['price'] > 0]
info['brand_amount'] = len(kind_data)
info['brand_price_max'] = kind_data.price.max()
info['brand_price_median'] = kind_data.price.median()
info['brand_price_min'] = kind_data.price.min()
info['brand_price_sum'] = kind_data.price.sum()
info['brand_price_std'] = kind_data.price.std()
info['brand_price_average'] = round(kind_data.price.sum() / (len(kind_data) + 1), 2)
all_info[kind] = info
brand_fe = pd.DataFrame(all_info).T.reset_index().rename(columns={"index": "brand"})
data = data.merge(brand_fe, how='left', on='brand')
# 數(shù)據(jù)分桶 以 power 為例
# 這時候我們的缺失值也進桶了,
# 為什么要做數(shù)據(jù)分桶呢碍现,原因有很多幅疼,= =
# 1. 離散后稀疏向量內(nèi)積乘法運算速度更快,計算結(jié)果也方便存儲昼接,容易擴展爽篷;
# 2. 離散后的特征對異常值更具魯棒性,如 age>30 為 1 否則為 0慢睡,對于年齡為 200 的也不會對模型造成很大的干擾逐工;
# 3. LR 屬于廣義線性模型假颇,表達能力有限赘那,經(jīng)過離散化后,每個變量有單獨的權(quán)重骏庸,這相當于引入了非線性髓涯,能夠提升模型的表達能力窘俺,加大擬合;
# 4. 離散后特征可以進行特征交叉复凳,提升表達能力瘤泪,由 M+N 個變量編程 M*N 個變量,進一步引入非線形育八,提升了表達能力对途;
# 5. 特征離散后模型更穩(wěn)定,如用戶年齡區(qū)間髓棋,不會因為用戶年齡長了一歲就變化
# 當然還有很多原因实檀,LightGBM 在改進 XGBoost 時就增加了數(shù)據(jù)分桶,增強了模型的泛化性
bin = [i*10 for i in range(31)]
data['power_bin'] = pd.cut(data['power'], bin, labels=False)
data[['power_bin', 'power']].head()
# 刪除不需要的數(shù)據(jù)
data = data.drop(['creatDate', 'regDate', 'regionCode'], axis=1)
print(data.shape)
data.columns
# 目前的數(shù)據(jù)其實已經(jīng)可以給樹模型使用了按声,所以我們導(dǎo)出一下
data.to_csv('data_for_tree.csv', index=0)
# 我們可以再構(gòu)造一份特征給 LR NN 之類的模型用
# 之所以分開構(gòu)造是因為膳犹,不同模型對數(shù)據(jù)集的要求不同
# 我們看下數(shù)據(jù)分布:
data['power'].plot.hist()
# 我們剛剛已經(jīng)對 train 進行異常值處理了,但是現(xiàn)在還有這么奇怪的分布是因為 test 中的 power 異常值签则,
# 所以我們其實剛剛 train 中的 power 異常值不刪為好须床,可以用長尾分布截斷來代替
Train_data['power'].plot.hist()
# 我們對其取 log,在做歸一化
from sklearn import preprocessing
min_max_scaler = preprocessing.MinMaxScaler()
data['power'] = np.log(data['power'] + 1)
data['power'] = ((data['power'] - np.min(data['power'])) / (np.max(data['power']) - np.min(data['power'])))
data['power'].plot.hist()
# km 的比較正常渐裂,應(yīng)該是已經(jīng)做過分桶了
data['kilometer'].plot.hist()
# 所以我們可以直接做歸一化
data['kilometer'] = ((data['kilometer'] - np.min(data['kilometer'])) /
(np.max(data['kilometer']) - np.min(data['kilometer'])))
data['kilometer'].plot.hist()
# 除此之外 還有我們剛剛構(gòu)造的統(tǒng)計量特征:
# 'brand_amount', 'brand_price_average', 'brand_price_max',
# 'brand_price_median', 'brand_price_min', 'brand_price_std',
# 'brand_price_sum'
# 這里不再一一舉例分析了豺旬,直接做變換钠惩,
def max_min(x):
return (x - np.min(x)) / (np.max(x) - np.min(x))
data['brand_amount'] = ((data['brand_amount'] - np.min(data['brand_amount'])) /
(np.max(data['brand_amount']) - np.min(data['brand_amount'])))
data['brand_price_average'] = ((data['brand_price_average'] - np.min(data['brand_price_average'])) /
(np.max(data['brand_price_average']) - np.min(data['brand_price_average'])))
data['brand_price_max'] = ((data['brand_price_max'] - np.min(data['brand_price_max'])) /
(np.max(data['brand_price_max']) - np.min(data['brand_price_max'])))
data['brand_price_median'] = ((data['brand_price_median'] - np.min(data['brand_price_median'])) /
(np.max(data['brand_price_median']) - np.min(data['brand_price_median'])))
data['brand_price_min'] = ((data['brand_price_min'] - np.min(data['brand_price_min'])) /
(np.max(data['brand_price_min']) - np.min(data['brand_price_min'])))
data['brand_price_std'] = ((data['brand_price_std'] - np.min(data['brand_price_std'])) /
(np.max(data['brand_price_std']) - np.min(data['brand_price_std'])))
data['brand_price_sum'] = ((data['brand_price_sum'] - np.min(data['brand_price_sum'])) /
(np.max(data['brand_price_sum']) - np.min(data['brand_price_sum'])))
# 對類別特征進行 OneEncoder
data = pd.get_dummies(data, columns=['model', 'brand', 'bodyType', 'fuelType',
'gearbox', 'notRepairedDamage', 'power_bin'])
print(data.shape)
data.columns
# 這份數(shù)據(jù)可以給 LR 用
data.to_csv('data_for_lr.csv', index=0)
4、特征篩選
①過濾式
# 相關(guān)性分析
print(data['power'].corr(data['price'], method='spearman'))
print(data['kilometer'].corr(data['price'], method='spearman'))
print(data['brand_amount'].corr(data['price'], method='spearman'))
print(data['brand_price_average'].corr(data['price'], method='spearman'))
print(data['brand_price_max'].corr(data['price'], method='spearman'))
print(data['brand_price_median'].corr(data['price'], method='spearman'))
# 當然也可以直接看圖
data_numeric = data[['power', 'kilometer', 'brand_amount', 'brand_price_average',
'brand_price_max', 'brand_price_median']]
correlation = data_numeric.corr()
f , ax = plt.subplots(figsize = (7, 7))
plt.title('Correlation of Numeric Features with Price',y=1,size=16)
sns.heatmap(correlation,square = True, vmax=0.8)
②包裹式
# k_feature 太大會很難跑族阅,沒服務(wù)器篓跛,所以提前 interrupt 了
from mlxtend.feature_selection import SequentialFeatureSelector as SFS
from sklearn.linear_model import LinearRegression
sfs = SFS(LinearRegression(),
k_features=10,
forward=True,
floating=False,
scoring = 'r2',
cv = 0)
x = data.drop(['price'], axis=1)
x = x.fillna(0)
y = data['price']
sfs.fit(x, y)
sfs.k_feature_names_
# 畫出來,可以看到邊際效益
from mlxtend.plotting import plot_sequential_feature_selection as plot_sfs
import matplotlib.pyplot as plt
fig1 = plot_sfs(sfs.get_metric_dict(), kind='std_dev')
plt.grid()
plt.show()
3坦刀、嵌入式
三愧沟、經(jīng)驗總結(jié)
特征工程是比賽中最至關(guān)重要的的一塊,特別的傳統(tǒng)的比賽鲤遥,大家的模型可能都差不多沐寺,調(diào)參帶來的效果增幅是非常有限的,但特征工程的好壞往往會決定了最終的排名和成績渴频。
特征工程的主要目的還是在于將數(shù)據(jù)轉(zhuǎn)換為能更好地表示潛在問題的特征芽丹,從而提高機器學(xué)習(xí)的性能北启。
總的來說卜朗,特征工程是一個入門簡單,但想精通非常難的一件事