python有多少库存房_用Python研究了三千套房子,告诉你究竟是什么抬高了房价?...

该博客介绍了房价预测的模型构建过程,包括数据预处理、缺失值处理、特征分析、模型建立(岭回归和随机森林)以及参数调优。通过分析数据分布,使用众数、均值等填充缺失值,并进行one-hot编码和数值特征标准化。在模型建立后,通过学习曲线观察过拟合现象,并进行参数优化以提高模型性能。最终采用模型融合技术结合岭回归和随机森林的预测结果,得出最终预测。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

122271863_1_20180118100839622

关于房价,一直都是全民热议的话题,毕竟不少人终其一生都在为之奋斗。

房地产的泡沫究竟有多大不得而知?今天我们抛开泡沫,回归房屋最本质的内容,来分析一下房价的影响因素究竟是什么?

1、导入数据

importnumpyasnp

importpandasaspd

importmatplotlib.pyplotasplt

importseabornassn

importmissingnoasmsno

%matplotlibinline

train = pd.read_csv('train.csv',index_col=0)#导入训练集

test = pd.read_csv('test.csv',index_col=0)#导入测试集

train.head(3)

print('train训练集缺失数据分布图')

msno.matrix(train)

print('test测试集缺失数据分布图')

msno.matrix(test)

122271863_3_2018011810084029

122271863_4_20180118100840169

从上面的数据缺失可视化图中可以看出,部分特征的数据缺失十分严重,下面我们来对特征的缺失数量进行统计。

2、目标Y值分析

##分割Y和X数据

y=train['SalePrice']

#看一下y的值分布

prices = pd.DataFrame({'price':y,'log(price+1)':np.log1p(y)})

prices.hist()

122271863_5_20180118100840310

观察目标变量y的分布和取对数后的分布看,取完对数后更倾向于符合正太分布,故我们对y进行对数转化。

y = np.log1p(y)#+1的目的是防止对数转化后的值无意义

3、合并数据 缺失处理

#合并训练特征和测试集

all_df = pd.concat((X,test),axis=0)

print('all_df缺失数据图')

msno.matrix(all_df)

#定义缺失统计函数

defshow_missing(feature):

missing = feature.columns[feature.isnull().any()].tolist()

returnmissing

print('缺失特征的数据缺失量统计:')

all_df[show_missing(all_df)].isnull().sum()

#先处理numeric数值型数据

#挨个儿看一下分布

fig,axs = plt.subplots(3,2,figsize=(16,9))

all_df['BsmtFinSF1'].hist(ax = axs[0,0])#众数填充

all_df['BsmtFinSF2'].hist(ax = axs[0,1])#众数

all_df['BsmtUnfSF'].hist(ax =  axs[1,0])#中位数

all_df['TotalBsmtSF'].hist(ax = axs[1,1])#均值填充

all_df['BsmtFullBath'].hist(ax = axs[2,0])#众数

all_df['BsmtHalfBath'].hist(ax = axs[2,1])#众数

#lotfrontage用均值填充

mean_lotfrontage = all_df.LotFrontage.mean()

all_df.LotFrontage.hist()

print('用均值填充:')

cat_input(all_df,'LotFrontage',mean_lotfrontage)

cat_input(all_df,'BsmtFinSF1',0.0)

cat_input(all_df,'BsmtFinSF2',0.0)

cat_input(all_df,'BsmtFullBath',0.0)

cat_input(all_df,'BsmtHalfBath',0.0)

cat_input(all_df,'BsmtUnfSF',467.00)

cat_input(all_df,'TotalBsmtSF',1051.78)

#在处理字符型,同样,挨个看下分布

fig,axs = plt.subplots(4,2,figsize=(16,9))

all_df['MSZoning'].hist(ax = axs[0,0])#众数填充

all_df['Utilities'].hist(ax = axs[0,1])#众数

all_df['Exterior1st'].hist(ax =  axs[1,0])#众数

all_df['Exterior2nd'].hist(ax = axs[1,1])#众数填充

all_df['KitchenQual'].hist(ax = axs[2,0])#众数

all_df['Functional'].hist(ax = axs[2,1])#众数

all_df['SaleType'].hist(ax = axs[3,0])#众数

cat_input(all_df,'MSZoning','RL')

cat_input(all_df,'Utilities','AllPub')

cat_input(all_df,'Exterior1st','VinylSd')

cat_input(all_df,'Exterior2nd','VinylSd')

cat_input(all_df,'KitchenQual','TA')

cat_input(all_df,'Functional','Typ')

cat_input(all_df,'SaleType','WD')

#再看一下缺失分布

msno.matrix(all_df)

122271863_6_20180118100840451

122271863_7_20180118100840935

122271863_8_20180118100841294

122271863_9_20180118100841435

122271863_10_20180118100841701

binggo,数据干净啦!下面开始处理特征,经过上述略微复杂的处理,数据集中所有的缺失数据都已处理完毕,可以开始接下来的工作啦!

缺失处理总结:在本篇文章所使用的数据集中存在比较多的缺失,缺失数据包括数值型和字符型,处理原则主要有两个:

一、根据绘制数据分布直方图,观察数据分布的状态,采取合适的方式填充缺失数据;

二、非常重要的特征描述,认真阅读,按照特征描述填充可以解决大部分问题。

4、特征处理

让我们在重新仔细审视一下数据有没有问题?仔细观察发现MSSubClass特征实际上是分类特征,但是数据显示是int类型,这个需要改成str。

#观察特征属性发现,MSSubClass是分类特征,但是数据给的是数值型,需要对其做转换

all_df['MSSubClass']=all_df['MSSubClass'].astype(str)

#将分类变量转变成数值变量

all_df = pd.get_dummies(all_df)

print('分类变量转换完成后有{}行{}列'.format(*all_df.shape))

分类变量转换完成后有2919行316列

#标准化处理

numeric_cols = all_df.columns[all_df.dtypes !='uint8']

#x-mean(x)/std(x)

numeric_mean = all_df.loc[:,numeric_cols].mean()

numeric_std = all_df.loc[:,numeric_cols].std()

all_df.loc[:,numeric_cols] = (all_df.loc[:,numeric_cols]-numeric_mean)/numeric_std

再把数据拆分到训练集和测试集

train_df = all_df.ix[0:1460]#训练集

test_df = all_df.ix[1461:]#测试集

5、构建基准模型

fromsklearnimportcross_validation

fromsklearnimportlinear_model

fromsklearn.learning_curveimportlearning_curve

fromsklearn.metricsimportexplained_variance_score

fromsklearn.grid_searchimportGridSearchCV

fromsklearn.model_selectionimportcross_val_score

fromsklearn.ensembleimportRandomForestRegressor

y = y.values#转换成array数组

X = train_df.values#转换成array数组

cv = cross_validation.ShuffleSplit(len(X),n_iter=3,test_size=0.2)

print('岭回归交叉验证结果:')

fortrain_index,test_indexincv:

ridge = linear_model.Ridge(alpha=1).fit(X,y)

print('train_score:{0:.3f},test_score:{1:.3f}\n'.format(ridge.score(X[train_index],y[train_index]),

ridge.score(X[test_index],y[test_index])))

print('随机森林交叉验证结果:')

fortrain_index,test_indexincv:

rf =RandomForestRegressor().fit(X,y)

print('train_score:{0:.3f},test_score:{1:.3f}\n'.format(rf.score(X[train_index],y[train_index]),

rf.score(X[test_index],y[test_index])))

122271863_11_20180118100841826

哇!好意外啊,这两个模型的结果表现都不错,但是随机森林的结果似乎更好,下面来看看学习曲线情况。

122271863_12_20180118100841966

122271863_13_2018011810084291

我们采用的是默认的参数,没有调优处理,得到的两个基准模型都存在过拟合现象。下面,我们开始着手参数的调整,希望能够改善模型的过拟合现象。

6、参数调优

岭回归正则项缩放系数alpha调整

alphas =[0.01,0.1,1,10,20,50,100,300]

test_scores = []

foralpinalphas:

clf = linear_model.Ridge(alp)

test_score = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

test_scores.append(np.mean(test_score))

importmatplotlib.pyplotasplt

%matplotlibinline

plt.plot(alphas,test_scores)

plt.title('alpha vs test_score')

122271863_14_20180118100842263

alpha在10-20附近均方误差最小

随机森林参数调优

随机森林算法,本篇中主要调整三个参数:maxfeatures,maxdepth,n_estimators

#随机森林的深度参数

max_depth=[2,4,6,8,10]

test_scores_depth = []

fordepthinmax_depth:

clf =RandomForestRegressor(max_depth=depth)

test_score_depth = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

test_scores_depth.append(np.mean(test_score_depth))

#随机森林的特征个数参数

max_features =[.1, .3, .5, .7, .9, .99]

test_scores_feature = []

forfeatureinmax_features:

clf =RandomForestRegressor(max_features=feature)

test_score_feature = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

test_scores_feature.append(np.mean(test_score_feature))

#随机森林的估计器个位数参数

n_estimators =[10,50,100,200,500]

test_scores_n = []

forninn_estimators:

clf =RandomForestRegressor(n_estimators=n)

test_score_n = -cross_val_score(clf,X,y,cv=10,scoring='neg_mean_squared_error')

test_scores_n.append(np.mean(test_score_n))

122271863_15_20180118100842388

122271863_16_20180118100842513

122271863_17_20180118100842607

随机森林的各项参数来看,深度位于8,选择特征个数比例为0.5,估计器个数为500时,效果最好。下面分别利用上述得到的最优参数分别重新训练,看一下学习曲线,过拟合现象是否得到缓解?

122271863_18_20180118100842716

122271863_19_20180118100842873

再回想一下,我们最初的基线模型学习曲线的形状,是不是得到了一定程度的缓解?OK,下面我们采用模型融合技术,对数据进行预测。

#预测

ridge = linear_model.Ridge(alpha=10).fit(X,y)

rf =RandomForestRegressor(n_estimators=500,max_depth=8,max_features=.5).fit(X,y)

y_ridge = np.expm1(ridge.predict(test_df.values))

y_rf = np.expm1(rf.predict(test_df.values))

y_final = (y_ridge + y_rf)/2

122271863_20_20180118100842998

本篇房价预测的模型搭建已经完成。同样,再梳理一边思路:

一、本篇用到的房价数据集存在比较多的数据缺失,且分类变量十分多。在预处理阶段需要将训练集和测试集合并,进行缺失填充和one-hot独热变量处理,保证数据处理过程的一致性,在数据缺失填充过程中,需要综合考虑特征的实际描述和数据的分布,选择合适的填充方式填充;

二、为防止数据变量不统一带来的模型准确率下降,将数值型特征进行标准化处理,数据处理完成后,按照数据合并的方式,再还原到训练集和测试集;

三、先构建岭回归和随机森林基准模型,进行三折交叉验证,绘制学习曲线,存在明显的过拟合现象;

四、接下来分别对两个基准模型进行参数调优,获得使得均方误差最小的参数,返回到训练集进行训练;

五、采用并行模型融合的方式,计算两个模型预测结果的均值作为测试集的预测结果。

本文作者122271863_22_20180118100843388熊小莉Python中文社区专栏作者。985硕士,本科统计专业,迷途知返的统计人,热爱数学,喜欢数据,狂爱钻研,目前转型做数据挖掘工程师,期待与更多同业人交流。

现在能赶上房价涨幅的,恐怕只有比特币了!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值