特徵工程

打卡Datawhale數據挖掘學習,數據挖掘之二手車交易價格預測,該內容來自 Datawhale與天池聯合發起的“0基礎入門系列”特徵工程。https://tianchi.aliyun.com/competition/entrance/231784/introduction

目標

對於特徵進行進一步分析,並對於數據進行處理,完成對於特徵工程的分析,並對於數據進行一些圖表或者文字總結。將數據轉換爲能更好表示潛在問題的特徵,從而更好提高機器學習的性能。

內容

常見的特徵工程包括:

  1. 異常處理:
  2. 特徵歸一化/標準化:
  3. 數據分桶:
  4. 缺失值處理:
  5. 特徵構造:
  6. 特徵篩選
  7. 降維
#導入數據
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
path = './data/'
train = pd.read_csv(path+'train.csv', sep=' ')
test = pd.read_csv(path+'testA.csv', sep=' ')
print(train.shape)
print(test.shape)

#查看數據
train.head()
train.columns


test.columns


# 刪除異常值
# 這裏我包裝了一個異常值處理的代碼,可以隨便調用。
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 = outliers_proc(train, 'power', scale=3)
plt.show()
# 特徵構造
# 訓練集和測試集放在一起,方便構造特徵
train['train']=1
test['train']=0
data = pd.concat([train, test], ignore_index=True, sort=False)

# 使用時間: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
# 看一下空數據,有 15k 個樣本的時間是有問題的,我們可以選擇刪除,也可以選擇放着。
# 但是這裏不建議刪除,因爲刪除缺失數據佔總樣本量過大,7.5%
# 我們可以先放着,因爲如果我們 XGBoost 之類的決策樹,其本身就能處理缺失值,所以可以不用管;
data['used_time'].isnull().sum()

# 從郵編中提取城市信息,因爲是德國的數據,所以參考德國的郵編,相當於加入了先驗知識
data['city'] = data['regionCode'].apply(lambda x : str(x)[:-3])


# 計算某品牌的銷售統計量,同學們還可以計算其他特徵的統計量
# 這裏要以 train 的數據計算統計量
train_gb = train.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)

print(data.shape)
data.columns

# 目前的數據其實已經可以給樹模型使用了,所以我們導出一下
data.to_csv('data_for_tree.csv', index=0)
# 我們可以再構造一份特徵給 LR NN 之類的模型用
# 之所以分開構造是因爲,不同模型對數據集的要求不同
# 我們看下數據分佈:
data['power'].plot.hist()

# 我們剛剛已經對 train 進行異常值處理了,但是現在還有這麼奇怪的分佈是因爲 test 中的 power 異常值,
# 所以我們其實剛剛 train 中的 power 異常值不刪爲好,可以用長尾分佈截斷來代替
train['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 的比較正常,應該是已經做過分桶了
data['kilometer'].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'])

print(data.shape)
data.columns

# 這份數據可以給 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)



plt.grid()
plt.show()


包裹式運行數據優點問題,後續再補上。嵌入式,大部分情況下都是用嵌入式做特徵篩選。

經驗

通過對特徵工程的學習,基本知道這麼一回事。

特徵工程的意義是將數據轉換爲能更好地表示潛在問題的特徵,從而提高機器學習的性能。當然特徵工程其實是和模型結合在一起的,這就是爲什麼要爲 LR NN 做分桶和特徵歸一化的原因,而對於特徵的處理效果和特徵重要性等往往要通過模型來驗證。

總結一下特徵工程的過程:

讀取數據-->處理異常值(包括替換,刪除)-->特徵處理(歸一化,標準化)-->數據分桶--> 缺失值處理-->特徵構造,特徵篩選-->降維(這個後續補充)

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