一、准备工作
(1)查看项目概述
网址:https://www.kaggle.com/competitions/house-prices-advanced-regression-techniques/overview
简单来说,就是我们需要根据一些房子的信息数据(所有房子的79个特征表现,部分房子的真实房价),来预测其他的房子的价格。
(2)下载数据集
一直往下翻
(3)导入部分必要的库
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from scipy.stats import skew
(4)参数设置(图形显示大小+屏蔽警告)
- %matplotlib inline 是一个 Jupyter Notebook 中的魔术命令(magic command),用于设置 Matplotlib 图形直接在 Notebook 单元格中显示,而不是在一个单独的窗口中显示
- matplotlib.rcParams[‘figure.figsize’] = (12.0, 6.0) 设置 Matplotlib 绘图时的默认图形尺寸。具体来说,rcParams 是 Matplotlib 的运行时配置参数,figure.figsize 是其中一个参数,用于指定图形的宽度和高度。
%matplotlib inline
matplotlib.rcParams['figure.figsize'] = (12.0, 6.0)
import warnings
warnings.filterwarnings("ignore")
(5)导入数据集
train = pd.read_csv('train.csv')
test = pd.read_csv('test.csv')
二、特征分析
(1)分析数据特征
(2)分析时间序列特征
year_feats = [col for col in all_data.columns if "Yr" in col or 'Year' in col]
year_feats
- 然后检查一下这些特征与销售价格是否有关系
根据 YrSold 列对 all_data 中此列数据框进行分组,并计算每个分组中 SalePrice 列的中位数,然后绘制这些中位数随时间变化的折线图
combined_df = pd.concat([train,test],axis=0)
combined_df.groupby('YrSold')['SalePrice'].median().plot()
plt.xlabel('Year Sold')
plt.ylabel('House Price')
plt.title('House price vs YearSold')
- 绘制其他三个特征与销售价格的散点对应图
for feature in year_feats:
if feature != 'YrSold':
hs = combined_df.copy()
plt.scatter(hs[feature],hs['SalePrice'])
plt.xlabel(feature)
plt.ylabel('SalePrice')
plt.show()
可以看到随着时间的增加,价格是逐增加的
三、数据预处理
(一)合并数据
all_data = pd.concat([train.loc[:, 'MSSubClass':'SaleCondition'],test.loc[:, 'MSSubClass':'SaleCondition']])
(二)对于数字特征
(1)减小时间特征值的大小
- 用售卖时间减去 build/remodadd/garageBuild 的时间
在某些情况下,直接使用年份数据可能不如使用年龄数据有效,年龄数据可以减少年份数据中的噪声,并可能提高模型的性能
for feature in ['YearBuilt','YearRemodAdd','GarageYrBlt']:
all_data[feature]=all_data['YrSold']-all_data[feature]
(2) 正态化 SalePrice
- skew() 是一个统计函数,用于计算数据集的偏度(skewness)。偏度是描述数据分布形态的一个统计量,它衡量数据分布的不对称程度。对偏斜程度大于0.75的做log1p处理,减少数据的偏度,使其更接近正态分布
prices = pd.DataFrame({
"price":train["SalePrice"],"log(price + 1)":np.log1p(train["SalePrice"])})
train["SalePrice"] = np.log1p(train["SaleP