数据挖掘实战:二手车交易价格预测之特征工程

特征工程用于对特征进行进一步分析,并对数据进行处理
常见特征工程包括:

  1. 异常处理:
    通过箱线图(或 3-Sigma)分析删除异常值;
    BOX-COX 转换(处理有偏分布);
    长尾截断;
  2. 特征归一化/标准化:
    标准化(转换为标准正态分布);
    归一化(抓换到 [0,1] 区间);
    针对幂律分布,可以采用公式:
  3. 数据分桶:
    等频分桶;
    等距分桶;
    Best-KS 分桶(类似利用基尼指数进行二分类);
    卡方分桶;
  4. 缺失值处理:
    不处理(针对类似 XGBoost 等树模型);
    删除(缺失数据太多);
    插值补全,包括均值/中位数/众数/建模预测/多重插补/压缩感知补全/矩阵补全等;
    分箱,缺失值一个箱;
  5. 特征构造:
    构造统计量特征,报告计数、求和、比例、标准差等;
    时间特征,包括相对时间和绝对时间,节假日,双休日等;
    地理信息,包括分箱,分布编码等方法;
    非线性变换,包括 log/ 平方/ 根号等;
    特征组合,特征交叉;
    𝑙𝑜𝑔( 1+𝑚1+𝑒𝑑𝑥𝑖𝑎𝑛 )
  6. 特征筛选
    过滤式(filter):先对数据进行特征选择,然后在训练学习器,常见的方法有 Relief/方差选择发/相关系
    数法/卡方检验法/互信息法;
    包裹式(wrapper):直接把最终将要使用的学习器的性能作为特征子集的评价准则,常见方法有
    LVM(Las Vegas Wrapper) ;
    嵌入式(embedding):结合过滤式和包裹式,学习器训练过程中自动进行了特征选择,常见的有
    lasso 回归;
  7. 降维
    PCA/ LDA/ ICA;
    特征选择也是一种降维

导入数据

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('used_car_train_20200313.csv', sep=' ')
test = pd.read_csv('used_car_testA_20200313.csv', sep=' ')
print(train.shape)
print(test.shape)
(150000, 31)
(50000, 30)
train.head()
SaleIDnameregDatemodelbrandbodyTypefuelTypegearboxpowerkilometer...v_5v_6v_7v_8v_9v_10v_11v_12v_13v_14
007362004040230.061.00.00.06012.5...0.2356760.1019880.1295490.0228160.097462-2.8818032.804097-2.4208210.7952920.914762
1122622003030140.012.00.00.0015.0...0.2647770.1210040.1357310.0265970.020582-4.9004822.096338-1.030483-1.7226740.245522
221487420040403115.0151.00.00.016312.5...0.2514100.1149120.1651470.0621730.027075-4.8467491.8035591.565330-0.832687-0.229963
337186519960908109.0100.00.01.019315.0...0.2742930.1103000.1219640.0333950.000000-4.5095991.285940-0.501868-2.438353-0.478699
4411108020120103110.051.00.00.0685.0...0.2280360.0732050.0918800.0788190.121534-1.8962400.9107830.9311102.8345181.923482

5 rows × 31 columns

train.columns
Index(['SaleID', 'name', 'regDate', 'model', 'brand', 'bodyType', 'fuelType',
       'gearbox', 'power', 'kilometer', 'notRepairedDamage', 'regionCode',
       'seller', 'offerType', 'creatDate', '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'],
      dtype='object')
test.columns
Index(['SaleID', 'name', 'regDate', 'model', 'brand', 'bodyType', 'fuelType',
       'gearbox', 'power', 'kilometer', 'notRepairedDamage', 'regionCode',
       'seller', 'offerType', 'creatDate', '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'],
      dtype='object')

删除异常值

# 这里封装一个异常值处理的代码,可供后续调用。
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:
        """
        # quantile 是分位函数,相当于取每列属性取值范围的3/4位置的值减去1/4位置的值,乘以scale
        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]]  # 将样本下标列出来,根据rule 返回的规则,筛选超出上界或下界的样本
    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)
Delete number is: 963
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 the 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

在这里插入图片描述

特征构造

# 训练集和测试集放在一起,方便构造特征
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()
15072
# 从邮编中提取城市信息,因为是德国的数据,所以参考德国的邮编,相当于加入了先验知识
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"}) # 将每个商标统计量转为df,转置后,每一行为商标下标,每一列为统计量名称如:brand_price,并替换列名index 为brand
data = data.merge(brand_fe, how='left', on='brand')
pd.DataFrame(all_info)
0123456789...30313233343536373839
brand_amount3.142900e+041.365600e+043.180000e+022.461000e+031.657500e+044.662000e+031.019300e+042.360000e+032.070000e+037.299000e+03...9.400000e+02318.0000005.880000e+022.010000e+02227.000000180.000000228.0000003.310000e+0265.0000009.000000
brand_price_max6.850000e+048.400000e+045.580000e+043.750000e+049.999900e+043.150000e+043.599000e+043.890000e+049.999900e+046.853000e+04...2.320000e+0411000.0000003.350000e+046.500000e+042900.00000028900.00000020900.0000008.650000e+048999.00000014500.000000
brand_price_median3.199000e+036.399000e+037.500000e+034.990000e+035.999000e+032.300000e+031.800000e+032.600000e+032.270000e+031.400000e+03...3.295000e+031000.0000002.350000e+035.600000e+03999.000000950.0000002250.0000001.325000e+042850.0000001900.000000
brand_price_min1.300000e+011.500000e+013.500000e+016.500000e+011.200000e+012.000000e+011.300000e+016.000000e+013.000000e+015.000000e+01...5.000000e+0150.0000005.000000e+019.800000e+0260.00000050.000000150.0000005.500000e+0299.000000750.000000
brand_price_sum1.737197e+081.240446e+083.766241e+061.595423e+071.382791e+081.541432e+073.645752e+079.905909e+061.001717e+071.780527e+07...3.939145e+06560155.0000002.360095e+061.839801e+06231776.000000297977.000000816001.0000005.371844e+06215620.00000039480.000000
brand_price_std6.261372e+038.988865e+031.057622e+045.396328e+038.089863e+033.344690e+034.562233e+034.752584e+036.053233e+032.975343e+03...3.659577e+031829.0792114.394596e+039.637135e+03554.1184453325.9333653922.7153891.354118e+042140.0831455520.867233
brand_price_average5.527190e+039.082860e+031.180640e+046.480190e+038.342130e+033.305670e+033.576370e+034.195640e+034.836880e+032.439080e+03...4.186130e+031755.9700004.006950e+039.107930e+031016.5600001646.2800003563.3200001.618025e+043266.9700003948.000000

7 rows × 40 columns

pd.DataFrame(all_info).T.head()
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
brand_fe.head()
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
data.head()
SaleIDnameregDatemodelbrandbodyTypefuelTypegearboxpowerkilometer...trainused_timecitybrand_amountbrand_price_maxbrand_price_medianbrand_price_minbrand_price_sumbrand_price_stdbrand_price_average
007362004040230.061.00.00.06012.5...14385.0110193.035990.01800.013.036457518.04562.2333313576.37
1122622003030140.012.00.00.0015.0...14757.0413656.084000.06399.015.0124044603.08988.8654069082.86
221487420040403115.0151.00.00.016312.5...14382.021458.045000.08500.0100.014373814.05425.0581409851.83
337186519960908109.0100.00.01.019315.0...17125.013994.092900.05200.015.0113034210.08244.6952878076.76
4411108020120103110.051.00.00.0685.0...11531.064662.031500.02300.020.015414322.03344.6897633305.67

5 rows × 41 columns

# 数据分桶 以 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()
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, 39)





Index(['SaleID', '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 0x2f2ec46f470>

在这里插入图片描述

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

在这里插入图片描述

# 我们对其取 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 0x2f2e9b510b8>

在这里插入图片描述

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

在这里插入图片描述

# 所以可以直接做归一化
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 0x2f2e9212048>

在这里插入图片描述

# 除此之外 还有刚刚构造的统计量特征:
# '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
(199037, 370)





Index(['SaleID', 'name', 'power', 'kilometer', 'seller', 'offerType', 'price',
       'v_0', 'v_1', 'v_2',
       ...
       'power_bin_20.0', 'power_bin_21.0', 'power_bin_22.0', 'power_bin_23.0',
       'power_bin_24.0', 'power_bin_25.0', 'power_bin_26.0', 'power_bin_27.0',
       'power_bin_28.0', 'power_bin_29.0'],
      dtype='object', length=370)
# 这份数据可以给 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'))
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 0x2f2e9c3b400>

在这里插入图片描述

包裹式

!pip install mlxtend
Collecting mlxtend
  Downloading mlxtend-0.17.2-py2.py3-none-any.whl (1.3 MB)
Requirement already satisfied: scipy>=1.2.1 in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (1.4.1)
Requirement already satisfied: setuptools in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (46.0.0.post20200311)
Requirement already satisfied: matplotlib>=3.0.0 in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (3.2.0)
Requirement already satisfied: scikit-learn>=0.20.3 in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (0.22.2.post1)
Requirement already satisfied: pandas>=0.24.2 in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (1.0.2)
Requirement already satisfied: numpy>=1.16.2 in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (1.18.1)
Requirement already satisfied: joblib>=0.13.2 in c:\anaconda3\envs\mytf\lib\site-packages (from mlxtend) (0.14.1)
Requirement already satisfied: cycler>=0.10 in c:\anaconda3\envs\mytf\lib\site-packages (from matplotlib>=3.0.0->mlxtend) (0.10.0)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\anaconda3\envs\mytf\lib\site-packages (from matplotlib>=3.0.0->mlxtend) (1.1.0)
Requirement already satisfied: python-dateutil>=2.1 in c:\anaconda3\envs\mytf\lib\site-packages (from matplotlib>=3.0.0->mlxtend) (2.8.1)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in c:\anaconda3\envs\mytf\lib\site-packages (from matplotlib>=3.0.0->mlxtend) (2.4.6)
Requirement already satisfied: pytz>=2017.2 in c:\anaconda3\envs\mytf\lib\site-packages (from pandas>=0.24.2->mlxtend) (2019.3)
Requirement already satisfied: six in c:\anaconda3\envs\mytf\lib\site-packages (from cycler>=0.10->matplotlib>=3.0.0->mlxtend) (1.14.0)
Installing collected packages: mlxtend
Successfully installed mlxtend-0.17.2
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_

在这里插入图片描述

嵌入式

Lasso 回归和决策树可以完成嵌入式特征选择
大部分情况下都是用嵌入式做特征筛选

总结

  • 模型在比赛中发挥的作用有时不如特征工程重要,没有好的特征再好的模型也发挥不了作用。
  • 特征工程是为了从数据中提取出与问题目标相关联的信息,提高机器学习的性能。
  • 特征构造有助于发掘原始数据没有直接给出的信息。
  • 匿名特征往往不清楚特征相互直接的关联性,只有单纯基于特征进行处理:装箱,groupby,agg 等特征统计,还可以对特征进行的 log,exp 等变换,或者对多个特征进行四则运算(如上面算出的使用时长),多项式组合等然后进行筛选。
  • 特性的匿名性限制了很多对于特征的处理,有些时候用 NN 去提取一些特征也会达到意想不到的良好效果。
  • 若知道特征含义,可以基于信号处理,频域提取,丰度,偏度等构建更为有实际意义的特征,如在推荐系统中,各种类型点击率统计,各时段统计,加用户属性的统计等等,这种特征构建往往要深入分析背后的业务逻辑,才能更好的找到 magic。
  • 特征工程往往与模型密切结合,所以要为 LR NN 做分桶和特征归一化,对于特征的处理效果和特征重要性等往往要通过模型来验证。
当使用Pandas进行数据挖掘实战,通常需要进行以下步骤: 1. 导入必要的库: ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error ``` 2. 加载数据集: ```python data = pd.read_csv('二手车交易数据.csv') ``` 3. 数据预处理: ```python # 删除不需要的列 data = data.drop(['列名1', '列名2'], axis=1) # 处理缺失值 data = data.fillna(data.mean()) # 处理分类变量 data = pd.get_dummies(data, columns=['分类变量1', '分类变量2']) # 特征选择 X = data.drop('目标变量', axis=1) y = data['目标变量'] ``` 4. 划分训练集和测试集: ```python X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) ``` 5. 构建模型并训练: ```python model = LinearRegression() model.fit(X_train, y_train) ``` 6. 模型评估: ```python y_pred = model.predict(X_test) mse = mean_squared_error(y_test, y_pred) ``` 完整代码如下: ```python import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.linear_model import LinearRegression from sklearn.metrics import mean_squared_error # 加载数据集 data = pd.read_csv('二手车交易数据.csv') # 删除不需要的列 data = data.drop(['列名1', '列名2'], axis=1) # 处理缺失值 data = data.fillna(data.mean()) # 处理分类变量 data = pd.get_dummies(data, columns=['分类变量1', '分类变量2']) # 特征选择 X = data.drop('目标变量', axis=1) y = data['目标变量'] # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 构建模型并训练 model = LinearRegression() model.fit(X_train, y_train) # 模型评估 y_pred = model.predict(X_test) mse = mean_squared_error(y_test, y_pred) print("均方误差:", mse) ``` 希望以上代码能够帮助到你!如果你有任何其他问题,请随提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值