实验平台:Windows10 64位 + sublime text 3 + anaconda 2 64位(Python2) + numpy + pandas + matplotlib + sklearn
Step 0:引入相关的包
# coding:utf-8
# 注意读取文件时,Windows系统的\\和Linux系统的/的区别
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegressor
Step 1:读取数据
文件的组织形式是house price文件夹下面放house_price.py和input文件夹。
input文件夹下面放的是从https://www.kaggle.com/c/house-prices-advanced-regression-techniques/data下载的train.csv test.csv sample_submission.csv 和 data_description.txt 四个文件。
# 将csv数据转换为DataFrame数据,方便用pandas进行数据预处理
# 注意将print的注释打开,可以查看输出结果
train_df = pd.read_csv(".\\input\\train.csv",index_col = 0)
test_df = pd.read_csv('.\\input\\test.csv',index_col = 0)
# print train_df.shape
# print test_df.shape
# print train_df.head() # 默认展示前五行 这里是5行,80列
# print test_df.head() # 这里是5行,79列
Step 2:合并数据
这么做主要是为了用DF进行数据预处理的时候更加方便。等所有的需要的预处理进行完之后,我们再把他们分隔开。实际项目中,不会这样做。首先,SalePrice作为我们的训练目标,只会出现在训练集中,不会在测试集中。所以,我们先把SalePrice这一列给拿出来,不让它碍事儿。
# 看看SalePrice的形状和用log1p处理后的形状
prices = pd.DataFrame({
'price':train_df['SalePrice'],'log(price+1)':np.log1p(train_df['SalePrice'])})
# ps = prices.hist()
# plt.plot()
# plt.show()
# log1p即log(1+x),可以让label平滑化
y_train = np.log1p(train_df.pop('SalePrice'))
all_df = pd.concat((train_df,test_df),axis = 0)
# print all_df.shape
# print y_train.head()
Step 3:变量转化