DataWhale活动-二手车价格预测 task3

Task3 特征工程

特征工程目标

  • 对于特征进行进一步分析,并对于数据进行处理

  • 完成对于特征工程的分析,并对于数据进行一些图表或者文字总结

代码示例

1. 导入数据

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
train = pd.read_csv('./data/used_car_train_20200313.csv', sep=' ')
test = pd.read_csv('./data/used_car_testA_20200313.csv', sep=' ')
train = train.drop(['SaleID'],axis=1)
test = test.drop(['SaleID'], axis=1)
print(train.shape)
print(test.shape)
(150000, 30)
(50000, 29)
test.head()
nameregDatemodelbrandbodyTypefuelTypegearboxpowerkilometernotRepairedDamage...v_5v_6v_7v_8v_9v_10v_11v_12v_13v_14
06693220111212222.045.01.01.031315.00.0...0.2644050.1218000.0708990.1065580.078867-7.050969-0.8546264.8001510.620011-3.664654
11749601999021119.0210.00.00.07512.51.0...0.2617450.0000000.0967330.0137050.0523833.679418-0.729039-3.796107-1.541230-0.757055
253562009030482.0210.00.00.01097.00.0...0.2602160.1120810.0780820.0620780.050540-4.9266901.0011060.8265620.1382260.754033
350688201004050.000.00.01.01607.00.0...0.2604660.1067270.0811460.0759710.048268-4.8646370.5054931.8703790.3660381.312775
41614281997070326.0142.00.00.07515.00.0...0.2509990.0000000.0778060.0286000.0817093.616475-0.673236-3.197685-0.025678-0.101290

5 rows × 29 columns

'regDate' in train.columns
True

2. 删除异常值

def outliers_proc(data, col_name, scale=3):
    #用于清洗异常值,默认用 box_plot(scale=3)进行清洗
    #https://www.cnblogs.com/zhaohuanhuan/p/9055944.html
    def box_plot_outliers(data_ser, box_scale):
        #利用箱线图去除异常值
        #iqr = 四分位距
        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)))
    print("Before column number is: {}".format(data_n.shape[0]))
    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 tne 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, palette='Set1', ax=ax[1])
    return data_n
train = outliers_proc(train, 'power', scale=3)
Delete number is: 963
Before column number is: 150000
Now column number is: 149037
Description of data less than the lower bound is:
count    0.0
mean     NaN
std      NaN
min      NaN
25%      NaN
50%      NaN
75%      NaN
max      NaN
Name: power, dtype: float64
Description of data larger than tne upper bound is:
count      963.000000
mean       846.836968
std       1929.418081
min        376.000000
25%        400.000000
50%        436.000000
75%        514.000000
max      19312.000000
Name: power, dtype: float64

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IWDTbiYo-1585393328693)(output_8_1.png)]

2.特征构造

train['train'] = 1
test['train'] = 0
#ignore_index 忽略原来的index
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'))
# 看一下空数据,有 15k 个样本的时间是有问题的,我们可以选择删除,也可以选择放着。
# 但是这里不建议删除,因为删除缺失数据占总样本量过大,7.5%
# 我们可以先放着,因为如果我们 XGBoost 之类的决策树,其本身就能处理缺失值,所以可以不用管;
data['used_time'].isnull().sum()
15072
# 从邮编中提取城市信息,因为是德国的数据,所以参考德国的邮编,相当于加入了先验知识
data['city'] = data['regionCode'].apply(lambda x : str(x)[:-3])
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')
pd.DataFrame(all_info).T
brand_amountbrand_price_maxbrand_price_medianbrand_price_minbrand_price_sumbrand_price_stdbrand_price_average
031429.068500.03199.013.0173719698.06261.3716275527.19
113656.084000.06399.015.0124044603.08988.8654069082.86
2318.055800.07500.035.03766241.010576.22444411806.40
32461.037500.04990.065.015954226.05396.3275036480.19
416575.099999.05999.012.0138279069.08089.8632958342.13
54662.031500.02300.020.015414322.03344.6897633305.67
610193.035990.01800.013.036457518.04562.2333313576.37
72360.038900.02600.060.09905909.04752.5841544195.64
82070.099999.02270.030.010017173.06053.2334244836.88
97299.068530.01400.050.017805271.02975.3428842439.08
1013994.092900.05200.015.0113034210.08244.6952878076.76
112944.034500.02900.030.013398006.04722.1604924549.41
121108.027490.02625.050.04494303.04066.9599504052.57
133813.035000.01600.020.010675790.03073.9151962799.11
1416073.038990.01700.012.049076652.03605.5951273053.17
151458.045000.08500.0100.014373814.05425.0581409851.83
162219.017900.02999.020.08078352.02450.9060893638.90
17913.055800.02200.015.03328679.03952.9133303641.88
18315.034599.01999.050.01519049.06358.4097614807.12
191386.042350.02800.020.07228288.06186.5389495211.45
201235.037800.01750.015.04292737.04400.5298093473.09
211546.035999.04225.050.08856481.05257.2350265724.94
221085.043900.03950.050.06543426.05877.1408866025.25
23183.064000.01200.099.0597132.07333.6951403245.28
24630.099999.027450.015.020422776.019855.49520132365.73
252059.022500.02500.025.07515546.03556.2498393648.32
26878.099999.05000.011.07242792.010282.9872748239.81
272049.062900.04200.035.010862559.04853.2892405298.81
28633.039900.03790.080.03373957.04509.0363015321.70
29406.019990.05250.0500.02459028.03639.7377226041.84
30940.023200.03295.050.03939145.03659.5772914186.13
31318.011000.01000.050.0560155.01829.0792111755.97
32588.033500.02350.050.02360095.04394.5960024006.95
33201.065000.05600.0980.01839801.09637.1353239107.93
34227.02900.0999.060.0231776.0554.1184451016.56
35180.028900.0950.050.0297977.03325.9333651646.28
36228.020900.02250.0150.0816001.03922.7153893563.32
37331.086500.013250.0550.05371844.013541.18031516180.25
3865.08999.02850.099.0215620.02140.0831453266.97
399.014500.01900.0750.039480.05520.8672333948.00
pd.DataFrame(all_info).T.reset_index()
indexbrand_amountbrand_price_maxbrand_price_medianbrand_price_minbrand_price_sumbrand_price_stdbrand_price_average
0031429.068500.03199.013.0173719698.06261.3716275527.19
1113656.084000.06399.015.0124044603.08988.8654069082.86
22318.055800.07500.035.03766241.010576.22444411806.40
332461.037500.04990.065.015954226.05396.3275036480.19
4416575.099999.05999.012.0138279069.08089.8632958342.13
554662.031500.02300.020.015414322.03344.6897633305.67
6610193.035990.01800.013.036457518.04562.2333313576.37
772360.038900.02600.060.09905909.04752.5841544195.64
882070.099999.02270.030.010017173.06053.2334244836.88
997299.068530.01400.050.017805271.02975.3428842439.08
101013994.092900.05200.015.0113034210.08244.6952878076.76
11112944.034500.02900.030.013398006.04722.1604924549.41
12121108.027490.02625.050.04494303.04066.9599504052.57
13133813.035000.01600.020.010675790.03073.9151962799.11
141416073.038990.01700.012.049076652.03605.5951273053.17
15151458.045000.08500.0100.014373814.05425.0581409851.83
16162219.017900.02999.020.08078352.02450.9060893638.90
1717913.055800.02200.015.03328679.03952.9133303641.88
1818315.034599.01999.050.01519049.06358.4097614807.12
19191386.042350.02800.020.07228288.06186.5389495211.45
20201235.037800.01750.015.04292737.04400.5298093473.09
21211546.035999.04225.050.08856481.05257.2350265724.94
22221085.043900.03950.050.06543426.05877.1408866025.25
2323183.064000.01200.099.0597132.07333.6951403245.28
2424630.099999.027450.015.020422776.019855.49520132365.73
25252059.022500.02500.025.07515546.03556.2498393648.32
2626878.099999.05000.011.07242792.010282.9872748239.81
27272049.062900.04200.035.010862559.04853.2892405298.81
2828633.039900.03790.080.03373957.04509.0363015321.70
2929406.019990.05250.0500.02459028.03639.7377226041.84
3030940.023200.03295.050.03939145.03659.5772914186.13
3131318.011000.01000.050.0560155.01829.0792111755.97
3232588.033500.02350.050.02360095.04394.5960024006.95
3333201.065000.05600.0980.01839801.09637.1353239107.93
3434227.02900.0999.060.0231776.0554.1184451016.56
3535180.028900.0950.050.0297977.03325.9333651646.28
3636228.020900.02250.0150.0816001.03922.7153893563.32
3737331.086500.013250.0550.05371844.013541.18031516180.25
383865.08999.02850.099.0215620.02140.0831453266.97
39399.014500.01900.0750.039480.05520.8672333948.00
pd.DataFrame(all_info).T.reset_index().rename(columns={'index':'brand'})
brandbrand_amountbrand_price_maxbrand_price_medianbrand_price_minbrand_price_sumbrand_price_stdbrand_price_average
0031429.068500.03199.013.0173719698.06261.3716275527.19
1113656.084000.06399.015.0124044603.08988.8654069082.86
22318.055800.07500.035.03766241.010576.22444411806.40
332461.037500.04990.065.015954226.05396.3275036480.19
4416575.099999.05999.012.0138279069.08089.8632958342.13
554662.031500.02300.020.015414322.03344.6897633305.67
6610193.035990.01800.013.036457518.04562.2333313576.37
772360.038900.02600.060.09905909.04752.5841544195.64
882070.099999.02270.030.010017173.06053.2334244836.88
997299.068530.01400.050.017805271.02975.3428842439.08
101013994.092900.05200.015.0113034210.08244.6952878076.76
11112944.034500.02900.030.013398006.04722.1604924549.41
12121108.027490.02625.050.04494303.04066.9599504052.57
13133813.035000.01600.020.010675790.03073.9151962799.11
141416073.038990.01700.012.049076652.03605.5951273053.17
15151458.045000.08500.0100.014373814.05425.0581409851.83
16162219.017900.02999.020.08078352.02450.9060893638.90
1717913.055800.02200.015.03328679.03952.9133303641.88
1818315.034599.01999.050.01519049.06358.4097614807.12
19191386.042350.02800.020.07228288.06186.5389495211.45
20201235.037800.01750.015.04292737.04400.5298093473.09
21211546.035999.04225.050.08856481.05257.2350265724.94
22221085.043900.03950.050.06543426.05877.1408866025.25
2323183.064000.01200.099.0597132.07333.6951403245.28
2424630.099999.027450.015.020422776.019855.49520132365.73
25252059.022500.02500.025.07515546.03556.2498393648.32
2626878.099999.05000.011.07242792.010282.9872748239.81
27272049.062900.04200.035.010862559.04853.2892405298.81
2828633.039900.03790.080.03373957.04509.0363015321.70
2929406.019990.05250.0500.02459028.03639.7377226041.84
3030940.023200.03295.050.03939145.03659.5772914186.13
3131318.011000.01000.050.0560155.01829.0792111755.97
3232588.033500.02350.050.02360095.04394.5960024006.95
3333201.065000.05600.0980.01839801.09637.1353239107.93
3434227.02900.0999.060.0231776.0554.1184451016.56
3535180.028900.0950.050.0297977.03325.9333651646.28
3636228.020900.02250.0150.0816001.03922.7153893563.32
3737331.086500.013250.0550.05371844.013541.18031516180.25
383865.08999.02850.099.0215620.02140.0831453266.97
39399.014500.01900.0750.039480.05520.8672333948.00
# 数据分桶 以 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)]
#labels=False 表示值返回数据在哪个bin
data['power_bin'] = pd.cut(data['power'], bin, labels=False)
data[['power_bin', 'power']].head()
power_binpower
05.060
1NaN0
216.0163
319.0193
46.068
# 利用好了,就可以删掉原始数据了
data = data.drop(['creatDate', 'regDate', 'regionCode'], axis=1)
print(data.shape)
data.columns
(199037, 38)





Index(['name', 'model', 'brand', 'bodyType', 'fuelType', 'gearbox', 'power',
       'kilometer', 'notRepairedDamage', 'seller', 'offerType', 'price', 'v_0',
       'v_1', 'v_2', 'v_3', 'v_4', 'v_5', 'v_6', 'v_7', 'v_8', 'v_9', 'v_10',
       'v_11', 'v_12', 'v_13', 'v_14', 'train', 'used_time', 'city',
       'brand_amount', 'brand_price_max', 'brand_price_median',
       'brand_price_min', 'brand_price_sum', 'brand_price_std',
       'brand_price_average', 'power_bin'],
      dtype='object')
# 目前的数据其实已经可以给树模型使用了,所以我们导出一下
data.to_csv('data_for_tree.csv', index=0)
# 我们可以再构造一份特征给 LR NN 之类的模型用
# 之所以分开构造是因为,不同模型对数据集的要求不同
# 我们看下数据分布:
data['power'].plot.hist()
<matplotlib.axes._subplots.AxesSubplot at 0x12dd20050>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZOZb6VN3-1585393328695)(output_22_1.png)]

# 我们刚刚已经对 train 进行异常值处理了,但是现在还有这么奇怪的分布是因为 test 中的 power 异常值,
# 所以我们其实刚刚 train 中的 power 异常值不删为好,可以用长尾分布截断来代替
train['power'].plot.hist()
<matplotlib.axes._subplots.AxesSubplot at 0x12e680950>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-l4tN1W9t-1585393328695)(output_23_1.png)]

# 我们对其取 log,在做归一化
#why:服从长尾分布的都建议先取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()
<matplotlib.axes._subplots.AxesSubplot at 0x12e080950>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-LDcQ920T-1585393328696)(output_24_1.png)]

# km 的比较正常,应该是已经做过分桶了
data['kilometer'].plot.hist()
<matplotlib.axes._subplots.AxesSubplot at 0x137f21250>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-YXjw8R8g-1585393328696)(output_25_1.png)]

# 所以我们可以直接做归一化
data['kilometer'] = ((data['kilometer'] - np.min(data['kilometer'])) / 
                        (np.max(data['kilometer']) - np.min(data['kilometer'])))
data['kilometer'].plot.hist()
<matplotlib.axes._subplots.AxesSubplot at 0x137f86210>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vCxoDWrJ-1585393328696)(output_26_1.png)]

# 除此之外 还有我们刚刚构造的统计量特征:
# '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'])
# 这份数据可以给 LR 用
data.to_csv('data_for_lr.csv', index=0)

3特征筛选

1)过滤式

# 相关性分析
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'))
0.5728285196051496
-0.4082569701616764
0.058156610025581514
0.3834909576057687
0.259066833880992
0.38691042393409447
# 当然也可以直接看图
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)
<matplotlib.axes._subplots.AxesSubplot at 0x13807fc10>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-bSjSiFb6-1585393328697)(output_32_1.png)]

2)包裹式


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值