《零基础入门数据挖掘 - 二手车交易价格预测》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

读入数据,文件存放在子目录data里。

path = './data/'
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)

2. 定义异常值删除方法:

# 这里我包装了一个异常值处理的代码,以便后面调用。
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进行处理
# 删掉power的一些异常数据。  
Train_data = outliers_proc(Train_data, 'power', scale=3) 

处理前后的比较如下图。
在这里插入图片描述

3. notRepairedDamage的异常值处理

notRepairedDamage是“汽车有尚未修复的损坏:是:0,否:1”。

Train_data['notRepairedDamage'].value_counts()

在这里插入图片描述
  在训练集中有24324行“-”,因为是旧车、即将报废的车,将其替换为“0”有未修复的故障比较合理。

# 用 0(有未修复的故障)替换。
Train_data['notRepairedDamage'].replace('-', '0.0', inplace=True)
Test_data['notRepairedDamage'].replace('-', '0.0', inplace=True)

将notRepairedDamage的类型转换为float

# 转换类型object到float
Train_data['notRepairedDamage'] = Train_data['notRepairedDamage'].astype("float")
Test_data['notRepairedDamage'] = Test_data['notRepairedDamage'].astype("float")

4. 合并训练集和测试集

# 训练集和测试集放在一起,方便构造特征
Train_data['train']=1
Test_data['train']=0
data = pd.concat([Train_data, Test_data], ignore_index=True, sort=False)

5. 汽车使用时间计算

# 使用时间: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

6. 从regionCode提取地区信息

# 从regionCode中提取地区信息,相当于加入了先验知识
# 原regionCode是四位,取前面两位
data['city'] = data['regionCode'].apply(lambda x : str(x)[:-2])
data = data

7. 增加品牌的统计特征

# 计算某品牌的销售统计量,还可以计算其他特征的统计量
# 这里要以 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')

8. 数据分桶

对Power进行分桶处理。

bin = [i*10 for i in range(31)]
data['power_bin'] = pd.cut(data['power'], bin, labels=False)
data[['power_bin', 'power']].head()

9. 删除不需要的数据

  • 删除均一值的两个字段“offerType”、 “seller”;
  • “creatDate”、“regDate“已经用于计算使用时间,可以删除;
  • “regionCode”已经用于计算地区码,可以删除。
# 删除不需要的数据
data = data.drop(['creatDate', 'regDate', 'regionCode', 'offerType', 'seller'], axis=1)

10. 数据导出

# 目前的数据其实已经可以给树模型使用了,所以我们导出一下
data.to_csv('.\output\data_for_tree.csv', index=0)

三、总结

因为是第一次做特征工程,对特征、数据对模型学习能力提升理解不透彻,以上特征工程完成后,模型的预测能力没有很大的提升。
初次训练时使用的是简单数据、特征选择,只是删除了感觉没有用的特征“offerType”、 “seller”,分数(MAE)是680。
进行了以上的特征工程后,分数有小幅的提到,MAE成绩是535。应该还有提升的空间。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值