该文章主要是对于链接内容学习的笔记细节部分见链接Datawhale 零基础入门数据挖掘-Task3 特征工程.
导入数据
Train_data = pd.read_csv('used_car_train_20200313.csv', sep=' ')
Test_data = pd.read_csv('used_car_testA_20200313.csv', sep=' ')
print(Train_data.shape)
print(Test_data.shape)
Train_data.head().append(Train_data.tail())
Train_data.columns
Test_data.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
定义了一个输入data和列名后可以删除outlier的function,方法是先找出data该列的上下四分位数,两者相减得到一个delta,把小于下四分位数scale倍delta,或者大于上四分位数scale倍delta的数据视为异常值,scale是方法的参数,默认为3。
打个比方,下四分位数等于10,上四分位数等于30,那么delta等于20,令scale等于2,那么小于10-2 * 20=-30以及大于30+20 * 2=70的都视为异常值去掉。
Train_data = outliers_proc(Train_data, 'power', scale=3)
这里用training data的power列为例来应用刚刚的方法,值得注意的是对test data不能做这样删除自认为是异常值的操作。因为test data要全部拿来预测且可能包含异常值,所以我们在对training data做处理不要把异常值删得太干净,可以把scale值放大一点把一部分异常但是偏离得不太严重的数据考虑进去,提高模型的鲁棒性,这也是定义的function的scale默认为3的原因。
特征构造
Train_data['train']=1
Test_data['train']=0
data = pd.concat([Train_data, Test_data], ignore_index=True, sort=False)
把training data和testing data合并在一起方便特征构造处理,sort=False取消warning,用’train’=0或1来区分data来源
print("Shape of training data:",Train_data.shape)
print("Shape of testing data:",Test_data.shape)
print("Shape of concat data:",data.shape)
>>> Shape of training data: (149037, 32)
>>> Shape of testing data: (50000, 31)
>>> Shape of concat data: (199037, 32)
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
通过创建时间和注册时间构造一个使用时间的特征,因为二手车的价格和已使用时间有很大的关系。因为里面有的时间格式出错了所以用error=‘coarse’,出错时用NaN而不是报错。
data['used_time'].isnull().sum()
>>> 15072
缺失值比较多,不建议删除,如果用决策树可以处理缺失值。
data['regionCode'] = data['regionCode'].astype('str')
data['regionCode'] = data['regionCode'].apply(lambda x : x.zfill(3))
data['city'] = data['regionCode'].apply(lambda x : str(x)[-3:])
从邮编提取城市信息,先把int类型转换为str类型再往前面补0,因为我们只需要后3位所以不需要补到5位。
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')
计算品牌的相关统计量,先groupby分组,再把price>0的提取出来即排除异常值,计算同一品牌的数量,最高价,中位数价格,最低价,总价,价格标准差,均值,然后用dictionary的格式保存。用dictionary保存可以转换为自带index的dataframe格式。再把这个新dataframe和原dataframe merge起来。
# 数据分桶 以 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']]
分箱也是一个重要的特征,分箱操作可以看成是分类问题,根据value大小给它贴上不同箱子的标签。
# 删除不需要的数据
data = data.drop(['creatDate', 'regDate', 'regionCode'], axis=1)
# 目前的数据其实已经可以给树模型使用了,所以我们导出一下
data.to_csv('data_for_tree.csv', index=0)
除了dataframe,numpy也有np.save方法用来保存训练模型得到的参数,或者调用sklearn得到的的模型可以在训练后直接保存模型本身。这些步骤都是为了避免重复操作而可以下一次直接从中间开始。
data['power'].plot.hist()
这个分布是因为power的最大值太大了,但分布都集中前面,导致后面的柱的高度太低了看不清
plt.figure()
plt.ylim((0,100))
data['power'].plot.hist()
可以看出,有long tail是这个数据一个天然的特性,如果用之前删除异常值的方法,求上下四分位数,那么求出来的都是在第一个柱里的,这样删异常值就把后面的都删除了,明显不合适。这样的数据,需要的是正确的feature transformation。
# 我们对其取 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()
对其它特征,如果不是集中分布在某个范围则不需要做log变换只需要做归一化
data['kilometer'].plot.hist()
# 先plot看分布是否需要做log变换,确定不需要后再直接做归一化
data['kilometer'] = ((data['kilometer'] - np.min(data['kilometer'])) /
(np.max(data['kilometer']) - np.min(data['kilometer'])))
同理还可以对刚刚构造的brand统计量特征做归一化
# 对类别特征进行 OneEncoder
data = pd.get_dummies(data, columns=['model', 'brand', 'bodyType', 'fuelType',
'gearbox', 'notRepairedDamage', 'power_bin'])
data.columns[-40:]
# 这份数据可以给 LR 用
data.to_csv('data_for_lr.csv', index=0)
特征筛选
1)过滤式
# 相关性分析
correlation = data.corr()
print(correlation['price'].sort_values(ascending = False),'\n')
# 当然也可以直接看图
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)
2) 包裹式
指令pip install mlxtend安装包
# 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_
# 画出来,可以看到边际效益
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()
可以看到随着feature数目增大,对performance的提升越来越不明显,达到边际效应。
3)嵌入式
下一章介绍,Lasso 回归和决策树可以完成嵌入式特征选择。
大部分情况下都是用嵌入式做特征筛选。
嵌入式的意思就是有的模型,根据它的原理,天然地会在训练过程中自己做了特征筛选。
总结
特征工程最重要的几点,特征构造,有的特征要相互结合起来才能对预测起到帮助;特征转换,有的特征不是不能用,而是需要先做一遍转换;特征选择,可以用相关性分析或者用嵌入式来做特征筛选,把不同的模型堆叠在一起,前面用决策树帮忙筛选特征,后面用其它适合该场景的模型来做预测或者分类。