對於特徵進行進一步分析,並對於數據進行處理
完成對於特徵工程的分析,並對於數據進行一些圖表或者文字總結打卡
內容
常見特徵工程:
異常處理
通過箱線圖(或3-Sigma)分析刪除異常值;
BOX-COX轉換:處理有偏分佈
長尾截斷
特徵歸一化
標準化:轉換爲標準正態分佈
歸一化:轉換到0~1之間[0,1]
**針對冪律分佈,常採用公式:log((1+x)/(1+median))
數據分桶
等頻分桶
等距分桶
Beat-KS分桶:利用基尼指數進行二分類
卡方分桶
缺失值處理
不處理:針對類似XGBoost等樹模型
刪除:缺失數據太多
插值補全:包括均值/中位數/衆數/建模預測/多重插補/壓縮感知補全/矩陣補全等
分箱,缺失值一個箱
特徵構造
構造統計量特徵,報告計數、求和、比例、標準差等;
時間特徵,包括相對時間和絕對時間,節假日,雙休日等;
地理信息,包括分箱,分佈編碼等方法;
非線性變換,包括 log/ 平方/ 根號等;
特徵組合,特徵交叉;
仁者見仁,智者見智;
特徵篩選
過濾式(filter):先對數據進行特徵選擇,然後在訓練學習器,常見的方法有 Relief/方差選擇發/相關係數法/卡方檢驗法/互信息法;
包裹式(wrapper):直接把最終將要使用的學習器的性能作爲特徵子集的評價準則,常見方法有 LVM(Las Vegas Wrapper) ;
嵌入式(embedding):結合過濾式和包裹式,學習器訓練過程中自動進行了特徵選擇,常見的有 lasso 迴歸;
降維
PCA/ LDA/ ICA;
特徵選擇也是一種降維
代碼實現:
## 代碼實現
### 導入數據
常用操作:常引用庫包函數
## 刪除異常值
## 特徵構造
## 特徵篩選
代碼實現:
#!/usr/bin/env python
# coding: utf-8
# # 導入數據
# ## 先導入庫包、庫函數
# In[1]:
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
from operator import itemgetter
get_ipython().run_line_magic('matplotlib', 'inline')
# ## 指定路徑,導入數據
# In[2]:
path = 'C:/Users/Administrator/MyFirstJupyter/datalab/' ## 注意這個目錄下的斜杆問題,在這裏面是正斜杆
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)
# In[3]:
Train_data.head()
# In[4]:
Train_data.columns
# In[5]:
Test_data.columns
# # 刪除特徵值
# In[12]:
# 這裏我包裝了一個異常值處理的代碼,可以隨便調用。
def outliers_proc(data, col_name, scale=3):
"""
用於清洗異常值,默認用 box_plot(scale=3)進行清洗
:param data: 接收 pandas 數據格式
:param col_name: pandas 列名
:param scale: 尺度
:return:
"""
def box_plot_outliers(data_ser, box_scale):
"""
利用箱線圖去除異常值
:param data_ser: 接收 pandas.Series 數據格式
: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
# In[13]:
# 我們可以刪掉一些異常數據,以 power 爲例。
# 這裏刪不刪同學可以自行判斷
# 但是要注意 test 的數據不能刪 = = 不能掩耳盜鈴是不是
Train_data = outliers_proc(Train_data, 'power', scale=3)
# # 特徵構造
# In[15]:
# 訓練集和測試集放在一起,方便構造特徵
Train_data['train']=1
Test_data['train']=0
data = pd.concat([Train_data, Test_data], ignore_index=True)
# In[16]:
# 使用時間:data['creatDate'] - data['regDate'],反應汽車使用時間,一般來說價格與使用時間成反比
# 不過要注意,數據裏有時間出錯的格式,所以我們需要 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
# In[17]:
# 看一下空數據,有 15k 個樣本的時間是有問題的,我們可以選擇刪除,也可以選擇放着。
# 但是這裏不建議刪除,因爲刪除缺失數據佔總樣本量過大,7.5%
# 我們可以先放着,因爲如果我們 XGBoost 之類的決策樹,其本身就能處理缺失值,所以可以不用管;
data['used_time'].isnull().sum()
# In[18]:
# 從郵編中提取城市信息,相當於加入了先驗知識
data['city'] = data['regionCode'].apply(lambda x : str(x)[:-3])
data = data
# In[19]:
# 計算某品牌的銷售統計量,同學們還可以計算其他特徵的統計量
# 這裏要以 train 的數據計算統計量
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')
# In[20]:
# 數據分桶 以 power 爲例
# 這時候我們的缺失值也進桶了,
# 爲什麼要做數據分桶呢,原因有很多,= =
# 1. 離散後稀疏向量內積乘法運算速度更快,計算結果也方便存儲,容易擴展;
# 2. 離散後的特徵對異常值更具魯棒性,如 age>30 爲 1 否則爲 0,對於年齡爲 200 的也不會對模型造成很大的干擾;
# 3. LR 屬於廣義線性模型,表達能力有限,經過離散化後,每個變量有單獨的權重,這相當於引入了非線性,能夠提升模型的表達能力,加大擬合;
# 4. 離散後特徵可以進行特徵交叉,提升表達能力,由 M+N 個變量編程 M*N 個變量,進一步引入非線形,提升了表達能力;
# 5. 特徵離散後模型更穩定,如用戶年齡區間,不會因爲用戶年齡長了一歲就變化
# 當然還有很多原因,LightGBM 在改進 XGBoost 時就增加了數據分桶,增強了模型的泛化性
bin = [i*10 for i in range(31)]
data['power_bin'] = pd.cut(data['power'], bin, labels=False)
data[['power_bin', 'power']].head()
# In[21]:
# 刪除不需要的數據
data = data.drop(['creatDate', 'regDate', 'regionCode'], axis=1)
# In[22]:
print(data.shape)
data.columns
# In[23]:
# 目前的數據其實已經可以給樹模型使用了,所以我們導出一下
data.to_csv('data_for_tree.csv', index=0)
# In[24]:
# 我們可以再構造一份特徵給 LR NN 之類的模型用
# 之所以分開構造是因爲,不同模型對數據集的要求不同
# 我們看下數據分佈:
data['power'].plot.hist()
# In[25]:
# 我們剛剛已經對 train 進行異常值處理了,但是現在還有這麼奇怪的分佈是因爲 test 中的 power 異常值,
# 所以我們其實剛剛 train 中的 power 異常值不刪爲好,可以用長尾分佈截斷來代替
Train_data['power'].plot.hist()
# In[26]:
# 我們對其取 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()
# In[27]:
# km 的比較正常,應該是已經做過分桶了
data['kilometer'].plot.hist()
# In[28]:
# 所以我們可以直接做歸一化
data['kilometer'] = ((data['kilometer'] - np.min(data['kilometer'])) /
(np.max(data['kilometer']) - np.min(data['kilometer'])))
data['kilometer'].plot.hist()
# In[29]:
# 除此之外 還有我們剛剛構造的統計量特徵:
# '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'])))
# In[30]:
# 對類別特徵進行 OneEncoder
data = pd.get_dummies(data, columns=['model', 'brand', 'bodyType', 'fuelType',
'gearbox', 'notRepairedDamage', 'power_bin'])
# In[31]:
print(data.shape)
data.columns
# In[32]:
# 這份數據可以給 LR 用
data.to_csv('data_for_lr.csv', index=0)
# ## 特徵篩選
# ### 過濾式
# In[34]:
# 相關性分析
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'))
# In[35]:
# 當然也可以直接看圖
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)
# ### 包裹式
# In[36]:
# !pip install mlxtend # 不要點,下載速度很慢
# In[38]:
# k_feature 太大會很難跑,沒服務器,所以提前 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_
# In[40]:
# 畫出來,可以看到邊際效益
#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()
# In[41]:
# 下一章介紹,Lasso 迴歸和決策樹可以完成嵌入式特徵選擇
# 大部分情況下都是用嵌入式做特徵篩選
小結
特徵工程的主要目的還是在於將數據轉換爲能更好地表示潛在問題的特徵,從而提高機器學習的性能。比如,異常值處理是爲了去除噪聲,填補缺失值可以加入先驗知識等。
特徵構造也屬於特徵工程的一部分,其目的是爲了增強數據的表達。
對於知道特徵含義(非匿名)的特徵工程,特別是在工業類型比賽中,會基於信號處理,頻域提取,丰度,偏度等構建更爲有實際意義的特徵,這就是結合背景的特徵構建,在推薦系統中也是這樣的,各種類型點擊率統計,各時段統計,加用戶屬性的統計等等,這樣一種特徵構建往往要深入分析背後的業務邏輯或者說物理原理,從而才能更好的找到 magic。
當然特徵工程其實是和模型結合在一起的,這就是爲什麼要爲 LR NN 做分桶和特徵歸一化的原因,而對於特徵的處理效果和特徵重要性等往往要通過模型來驗證。
總的來說,特徵工程是一個入門簡單,但想精通非常難的一件事