# -*- coding: utf-8 -*-
"""
Created on Sat Oct 20 14:03:05 2018 @author: 12958
""" import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns # 忽略警告
import warnings
warnings.filterwarnings('ignore')
# 读取训练集和测试集
train = pd.read_csv('train.csv')
train_len = len(train)
test = pd.read_csv('test.csv') #print(train.head())
#print(test.head())
# 查看训练集的房价分布,左图是原始房价分布,右图是将房价对数化之后的分布
all_data = pd.concat([train, test], axis = 0, ignore_index= True)
all_data.drop(labels = ["SalePrice"],axis = 1, inplace = True)
fig = plt.figure(figsize=(12,5))
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
g1 = sns.distplot(train['SalePrice'],hist = True,label='skewness:{:.2f}'.format(train['SalePrice'].skew()),ax = ax1)
g1.legend()
g1.set(xlabel = 'Price')
g2 = sns.distplot(np.log1p(train['SalePrice']),hist = True,label='skewness:{:.2f}'.format(np.log1p(train['SalePrice']).skew()),ax=ax2)
g2.legend()
g2.set(xlabel = 'log(Price+1)') plt.show()
# 由于房价是有偏度的,将房价对数化
train['SalePrice'] = np.log1p(train['SalePrice'])
# 将有偏的数值特征对数化
num_features_list = list(all_data.dtypes[all_data.dtypes != "object"].index) for i in num_features_list:
if all_data[i].dropna().skew() > 0.75:
all_data[i] = np.log1p(all_data[i]) # 将类别数值转化为虚拟变量
all_data = pd.get_dummies(all_data) # 查看缺失值
print(all_data.isnull().sum())
# 将缺失值用该列的均值填充
all_data = all_data.fillna(all_data.mean())
# 将测试集和训练集分开
X_train = all_data[:train_len]
X_test = all_data[train_len:]
Y_train = train['SalePrice']
from sklearn.linear_model import Ridge, LassoCV
from sklearn.model_selection import cross_val_score # 定义交叉验证,用均方根误差来评价模型的拟合程度
def rmse_cv(model):
rmse = np.sqrt(-cross_val_score(model, X_train, Y_train, scoring = 'neg_mean_squared_error', cv=5))
return rmse
# Ridge模型
model_ridge = Ridge()
alphas = [0.05, 0.1, 0.3, 1, 3, 5, 10, 15, 30, 50, 75]
cv_ridge = [rmse_cv(Ridge(alpha = a)).mean() for a in alphas]
cv_ridge = pd.Series(cv_ridge, index = alphas)
cv_ridge
# 交叉验证可视化
fig = plt.figure(figsize=(8,5))
cv_ridge.plot(title = 'Cross Validation Score with Model Ridge')
plt.xlabel("alpha")
plt.ylabel("rmse")
plt.show()
# 当alpha为10时,均方根误差最小
cv_ridge.min()
# lasso模型,均方根误差的均值更小,因此最终选择lasso模型
model_lasso = LassoCV(alphas = [1, 0.1, 0.001, 0.0005]).fit(X_train, Y_train)
rmse_cv(model_lasso).mean()
# 查看模型系数, lasso模型能选择特征,将不重要的特征系数设置为0
coef = pd.Series(model_lasso.coef_, index = X_train.columns)
print("Lasso picked {} variables and eliminated the other {} variables".format(sum(coef != 0), sum(coef==0)))
# 查看重要的特征, GrLivArea地上面积是最重要的正相关特征
imp_coef = pd.concat([coef.sort_values().head(10),coef.sort_values().tail(10)])
fig = plt.figure(figsize=(6,8))
imp_coef.plot(kind = "barh")
plt.title("Coefficients in the Lasso Model")
plt.show()
# 查看残差
est = pd.DataFrame({"est":model_lasso.predict(X_train), "true":Y_train})
plt.rcParams["figure.figsize"] = [6,6]
est["resi"] = est["true"] - est["est"]
est.plot(x = "est", y = "resi",kind = "scatter")
plt.show() # xgboost模型
import xgboost as xgb dtrain = xgb.DMatrix(X_train, label = Y_train)
dtest = xgb.DMatrix(X_test)
# 交叉验证
params = {"max_depth":2, "eta":0.1}
cv_xgb = xgb.cv(params, dtrain, num_boost_round=500, early_stopping_rounds=100)
cv_xgb.loc[30:,["test-rmse-mean", "train-rmse-mean"]].plot()
plt.show() # 训练模型
model_xgb = xgb.XGBRegressor(n_estimators=360, max_depth=2, learning_rate=0.1)
model_xgb.fit(X_train, Y_train) '''
XGBRegressor(base_score=0.5, booster='gbtree', colsample_bylevel=1,
colsample_bytree=1, gamma=0, learning_rate=0.1, max_delta_step=0,
max_depth=2, min_child_weight=1, missing=None, n_estimators=360,
n_jobs=1, nthread=None, objective='reg:linear', random_state=0,
reg_alpha=0, reg_lambda=1, scale_pos_weight=1, seed=None,
silent=True, subsample=1)
''' # 查看两种模型的预测结果, 将结果指数化
lasso_preds = np.expm1(model_lasso.predict(X_test))
xgb_preds = np.expm1(model_xgb.predict(X_test))
predictions = pd.DataFrame({"xgb":xgb_preds, "lasso":lasso_preds})
predictions.plot(x = "xgb", y = "lasso", kind = "scatter")
plt.show()
# 最终结果采用两种模型预测的加权平均值,提交结果
preds = 0.7*lasso_preds + 0.3*xgb_preds
result = pd.DataFrame({"id":test.Id, "SalePrice":preds})
result.to_csv('result.csv', index = False)

需要实验数据的请留言哦

kaggle预测房价的代码步骤的更多相关文章

  1. Kaggle竞赛 —— 房价预测 (House Prices)

    完整代码见kaggle kernel 或 Github 比赛页面:https://www.kaggle.com/c/house-prices-advanced-regression-technique ...

  2. CSDN博客添加量子恒道统计代码步骤

    CSDN博客添加量子恒道统计代码步骤. 1. 去量子恒道网站统计 注册账户: 2. 添加已有的CSDN博客地址: 3. 添加博客后恒道代码里面会给你一个JavaScript脚本,记下里面的一串数字: ...

  3. Git利用命令行提交代码步骤

    利用命令行提交代码步骤进入你的项目目录1:拉取服务器代码,避免覆盖他人代码git pull2:查看当前项目中有哪些文件被修改过git status具体状态如下:1:Untracked: 未跟踪,一般为 ...

  4. 量化投资_MATLAB在时间序列建模预测及程序代码

    1 ARMA时间序列机器特性 下面介绍一种重要的平稳时间序列——ARMA时间序列. ARMA时间序列分为三种: AR模型,auto regressiv model MA模型,moving averag ...

  5. MATLAB Coder从MATLAB生成C/C++代码步骤

    MATLAB Coder可以从MATLAB代码生成独立的.可读性强.可移植的C/C++代码. 使用MATLAB Coder产生代码的3个步骤: 准备用于产生代码的MATLAB算法: 检查MATLAB代 ...

  6. 用线性单元(LinearUnit)实现工资预测的Python3代码

    功能:通过样本进行训练,让线性单元自己找到(这就是所谓机器学习)工资计算的规律,然后用两组数据进行测试机器是否真的get到了其中的规律. 原文链接在文尾,文章中的代码为了演示起见,仅根据工作年限来预测 ...

  7. 转 举例说明使用MATLAB Coder从MATLAB生成C/C++代码步骤

    MATLAB Coder可以从MATLAB代码生成独立的.可读性强.可移植的C/C++代码. http://www.mathworks.cn/products/matlab-coder/ 使用MATL ...

  8. kaggle预测

    两个预测kaggle比赛 一 .https://www.kaggle.com/c/web-traffic-time-series-forecasting/overview Arthur Suilin• ...

  9. java读代码步骤

    一.读代码的步骤 1.知道代码时用什么IDE开发的 2.将代码导入到IDE 3.连接数据库 A)连接到测试数据库 B)有sql脚本,在本地创建一个数据库,执行脚本,建立数据结构和导入数据. 4.尝试运 ...

随机推荐

  1. 关于Ping和Tracert命令原理详解

    本文只是总结了两个常用的网络命令的实现原理和一点使用经验说明.这些东西通常都分布在各种书籍或者文章中的,我勤快那么一点点,总结一下,再加上我的一点理解和使用经验,方便大家了解.这些也是很基础的东西,没 ...

  2. java 字节→字符转换流

    OutputStreamWriter:把字节输出流对象转成字符输出流对象 InputStreamReader:把字节输入流对象转成字符输入流对象 FileWriter和FileReader分别是Out ...

  3. js实现小数点四舍五入

    js实现小数点四舍五入 其实这个问题,在之前的面试中被提问到了,由于笔者平时都是用原生的toFixed()的方法来保留小数点,所以当时并没有回答出来这个问题,呜呜呜~.~

  4. 用一篇文章了解ppi,dpr,物理像素,逻辑像素,以及二倍图

    这篇文章能让你了解到什么是分辨率.dpr.dip.ppi (dpi相当于ppi,dpi用点表示物理像素密度,ppi是逻辑像素密度) 首先从最简单的ppi开始: 一部手机,有大有小,怎么知道手机的大小用 ...

  5. P1052 国王放置问题

    题目描述 在n*m的棋盘上放置k个国王,要求k个国王互相不攻击,有多少种不同的放置方法.假设国王放置在第(x,y)格,国王的攻击的区域是:(x-1,y-1), (x-1,y),(x-1,y+1),(x ...

  6. 使用Python内置的smtplib包和email包来实现邮件的构造和发送。

    此文章github地址:https://github.com/GhostCNZ/Python_sendEmail Python_sendEmail 使用Python内置的smtplib包和email包 ...

  7. 在小程序内点击按钮分享H5网页给好友或者朋友圈

    在小程序内点击按钮分享H5网页给好友或者朋友圈 首先需要建立h5容器文件夹 页面.wxml <navigator url="/pages/report-await/fouryearh5 ...

  8. jQuery 工具类函数-浏览器信息

    在jQuery中,通过$.browser对象可以获取浏览器的名称和版本信息,如$.browser.chrome为true,表示当前为Chrome浏览器,$.browser.mozilla为true,表 ...

  9. 土旦:移动端 Vue+Vant 的Uploader 实现 :上传、压缩、旋转图片

    面向百度开发 html <van-uploader :after-read="onRead" accept="image/*"> <img s ...

  10. vue依赖

    ajax:vue-resource moke数据:body-parser