零基礎入門數據挖掘-二手車交易價格預測(Day2特徵工程)

文章內容摘錄自atawhale 零基礎入門數據挖掘-Task3 特徵工程

特徵工程目標

對於特徵進行進一步分析,並對於數據進行處理
完成對於特徵工程的分析,並對於數據進行一些圖表或者文字總結並打卡。

常見的特徵工程

異常處理:
通過箱線圖(或 3-Sigma)分析刪除異常值;
BOX-COX 轉換(處理有偏分佈);
長尾截斷;
特徵歸一化/標準化:
標準化(轉換爲標準正態分佈);
歸一化(抓換到 [0,1] 區間);
針對冪律分佈,可以採用公式: log(1+x)/(1+median)

數據分桶:
等頻分桶;
等距分桶;
Best-KS 分桶(類似利用基尼指數進行二分類);
卡方分桶; 缺失值處理: 不處理(針對類似XGBoost 等樹模型);
刪除(缺失數據太多);
插值補全,包括均值/中位數/衆數/建模預測/多重插補/壓縮感知補全/矩陣補全等;

分箱,缺失值一個箱;
特徵構造:
構造統計量特徵,報告計數、求和、比例、標準差等;
時間特徵,包括相對時間和絕對時間,節假日,雙休日等;
地理信息,包括分箱,分佈編碼等方法;
非線性變換,包括 log/ 平方/ 根號等;
特徵組合,特徵交叉;
仁者見仁,智者見智。

特徵篩選
過濾式(filter):先對數據進行特徵選擇,然後在訓練學習器,常見的方法有
Relief/方差選擇發/相關係數法/卡方檢驗法/互信息法;
包裹式(wrapper):直接把最終將要使用的學習器的性能作爲特徵子集的評價準則,常見方法有 LVM(Las Vegas
Wrapper) ; 嵌入式(embedding):結合過濾式和包裹式,學習器訓練過程中自動進行了特徵選擇,常見的有 lasso 迴歸;

降維 
PCA/ LDA/ ICA; 
特徵選擇也是一種降維。

刪除異常值

# 這裏我包裝了一個異常值處理的代碼,可以隨便調用。
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
# 我們可以刪掉一些異常數據,以 power 爲例。  
# 這裏刪不刪同學可以自行判斷
# 但是要注意 test 的數據不能刪 = = 不能掩耳盜鈴是不是

Train_data = outliers_proc(Train_data, 'power', scale=3)

特徵構造

# 訓練集和測試集放在一起,方便構造特徵
Train_data['train']=1
Test_data['train']=0
data = pd.concat([Train_data, Test_data], ignore_index=True)
# 使用時間: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
# 從郵編中提取城市信息,相當於加入了先驗知識
data['city'] = data['regionCode'].apply(lambda x : str(x)[:-3])
data = data
# 計算某品牌的銷售統計量,同學們還可以計算其他特徵的統計量
# 這裏要以 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')
# 數據分桶 以 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()
# 刪除不需要的數據
data = data.drop(['creatDate', 'regDate', 'regionCode'], axis=1)
# 目前的數據其實已經可以給樹模型使用了,所以我們導出一下
data.to_csv('data_for_tree.csv', index=0)
# 我們對其取 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()
data['kilometer'] = ((data['kilometer'] - np.min(data['kilometer'])) / 
                        (np.max(data['kilometer']) - np.min(data['kilometer'])))
data['kilometer'].plot.hist()
# 除此之外 還有我們剛剛構造的統計量特徵:
# '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'])

OneEncoder知識

# 這份數據可以給 LR 用
data.to_csv('data_for_lr.csv', index=0)

特徵篩選

# 相關性分析
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)

經驗總結

特徵工程是比賽中最至關重要的的一塊,特別的傳統的比賽,大家的模型可能都差不多,調參帶來的效果增幅是非常有限的,但特徵工程的好壞往往會決定了最終的排名和成績。
特徵工程的主要目的還是在於將數據轉換爲能更好地表示潛在問題的特徵,從而提高機器學習的性能。比如,異常值處理是爲了去除噪聲,填補缺失值可以加入先驗知識等。
特徵構造也屬於特徵工程的一部分,其目的是爲了增強數據的表達。
有些比賽的特徵是匿名特徵,這導致我們並不清楚特徵相互直接的關聯性,這時我們就只有單純基於特徵進行處理,比如裝箱,groupby,agg 等這樣一些操作進行一些特徵統計,此外還可以對特徵進行進一步的 log,exp 等變換,或者對多個特徵進行四則運算(如上面我們算出的使用時長),多項式組合等然後進行篩選。由於特性的匿名性其實限制了很多對於特徵的處理,當然有些時候用 NN 去提取一些特徵也會達到意想不到的良好效果。
對於知道特徵含義(非匿名)的特徵工程,特別是在工業類型比賽中,會基於信號處理,頻域提取,丰度,偏度等構建更爲有實際意義的特徵,這就是結合背景的特徵構建,在推薦系統中也是這樣的,各種類型點擊率統計,各時段統計,加用戶屬性的統計等等,這樣一種特徵構建往往要深入分析背後的業務邏輯或者說物理原理,從而才能更好的找到 magic。
當然特徵工程其實是和模型結合在一起的,這就是爲什麼要爲 LR NN 做分桶和特徵歸一化的原因,而對於特徵的處理效果和特徵重要性等往往要通過模型來驗證。
總的來說,特徵工程是一個入門簡單,但想精通非常難的一件事。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章