[Kaggle] Housing Prices 房价预测

文章目录

    • 1. Baseline
      • 1. 特征选择
      • 2. 异常值剔除
      • 3. 建模预测
    • 2. 待优化特征工程

房价预测 kaggle 地址

参考文章:kaggle比赛:房价预测(排名前4%)

1. Baseline

import numpy as np
import pandas as pd
%matplotlib inline
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.model_selection import StratifiedShuffleSplit
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
from sklearn.preprocessing import LabelBinarizer
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import FeatureUnion
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import cross_val_score
train = pd.read_csv("./train.csv")
test = pd.read_csv("./test.csv")
# RangeIndex: 1460 entries, 0 to 1459
# Data columns (total 81 columns):

1. 特征选择

  • 数据有79个特征,我们选出相关系数最高的10个
abs(train.corr()['SalePrice']).sort_values(ascending=False).plot.bar()

在这里插入图片描述

most_10_important = abs(corrmat["SalePrice"]).sort_values(ascending=False)[1:11].index

最相关的特征 ['OverallQual', 'GrLivArea', 'GarageCars', 'GarageArea', otalBsmtSF', '1stFlrSF', 'FullBath', 'TotRmsAbvGrd', 'YearBuilt', 'YearRemodAdd']

2. 异常值剔除

  • 部分数据异常,删除
sns.pairplot(x_vars=most_10_important[0:5], y_vars=['SalePrice'], data=train, dropna=True)
sns.pairplot(x_vars=most_10_important[5:], y_vars=['SalePrice'], data=train, dropna=True)
# help(sns.pairplot)

在这里插入图片描述

#删除异常值
train = train.drop(train[(train['OverallQual']<5)&(train['SalePrice']>200000)].index)
train = train.drop(train[(train['GrLivArea']>4000)&(train['SalePrice']<300000)].index)
train = train.drop(train[(train['YearBuilt']<1900)&(train['SalePrice']>400000)].index)
train = train.drop(train[(train['TotalBsmtSF']>6000)&(train['SalePrice']<200000)].index)
sns.pairplot(x_vars=most_10_important[0:5], y_vars=['SalePrice'], data=train, dropna=True)
sns.pairplot(x_vars=most_10_important[5:], y_vars=['SalePrice'], data=train, dropna=True)
# help(sns.pairplot)

在这里插入图片描述

X_train = train[most_10_important]
X_test = test[most_10_important]
y_train = train['SalePrice']
  • 年份数据作为文字变量
X_train['YearBuilt'] = X_train['YearBuilt'].astype(str)
X_train['YearRemodAdd'] = X_train['YearRemodAdd'].astype(str)
X_test['YearBuilt'] = X_test['YearBuilt'].astype(str)
X_test['YearRemodAdd'] = X_test['YearRemodAdd'].astype(str)
def num_cat_splitor(X_train):s = (X_train.dtypes == 'object')object_cols = list(s[s].index)num_cols = list(set(X_train.columns) - set(object_cols))return num_cols, object_cols
num_cols, object_cols = num_cat_splitor(X_train)
class DataFrameSelector(BaseEstimator, TransformerMixin):def __init__(self, attribute_names):self.attribute_names = attribute_namesdef fit(self, X, y=None):return selfdef transform(self, X):return X[self.attribute_names].valuesnum_pipeline = Pipeline([('selector', DataFrameSelector(num_cols)),('imputer', SimpleImputer(strategy="median")),('std_scaler', StandardScaler()),])
cat_pipeline = Pipeline([('selector', DataFrameSelector(object_cols)),('cat_encoder', OneHotEncoder(sparse=False,handle_unknown='ignore')),])
full_pipeline = FeatureUnion(transformer_list=[("num_pipeline", num_pipeline),("cat_pipeline", cat_pipeline),])
X_prepared = full_pipeline.fit_transform(X_train)

3. 建模预测

prepare_select_and_predict_pipeline = Pipeline([('preparation', full_pipeline),('forst_reg', RandomForestRegressor(random_state=0))
])
param_grid = [{'preparation__num_pipeline__imputer__strategy': ['mean', 'median', 'most_frequent'],'forst_reg__n_estimators' : [50,100, 150, 200,250,300,330,350],'forst_reg__max_features':[45,50, 55, 65]
}]grid_search_prep = GridSearchCV(prepare_select_and_predict_pipeline, param_grid, cv=7,scoring='neg_mean_squared_error', verbose=2, n_jobs=-1)
grid_search_prep.fit(X_train,y_train)
grid_search_prep.best_params_
final_model = grid_search_prep.best_estimator_
y_pred_test = final_model.predict(X_test)
result = pd.DataFrame()
result['Id'] = test['Id']
result['SalePrice'] = y_pred_test
result.to_csv('housing_price_10_features.csv',index=False)

在这里插入图片描述
得分:19154.16762

2. 待优化特征工程

待学习 My Top 1% Approach: EDA, New Models and Stacking

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/474427.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

鼠标经过超链接文字变色

1、第一种方法 <a href"#" style" text-decoration:none;" onmouseover"javascript:this.style.colorred" onmouseout"javascript:this.style.colorblack">测试文字</a> 2、第二种方法 <style type"text/css"…

python中写入文件数据及文件定位操作命令

如果我们向文件中写入数据的话&#xff0c;我们可以使用write()函数。 写文件: #打开文件 f open("./index.cpp","w") #1. 写入数据 contents "hello world!" write(contents) #关闭文件 f.close() 文件定位&#xff1a; 函数名 含义 f.…

html炫酷弹幕特效,jQuery文字弹幕特效

特效描述&#xff1a;jQuery 文字弹幕特效。jQuery文字弹幕特效代码结构1. 引入JS2. HTML代码弹幕(点我呀&#xff01;&#xff01;)X让我来一个弹幕嘿嘿赞你哈哈51前端$(function(){init_screen();//alert("您好");$("#btn,.d_del").click(function(){$(&…

GridView 添加分害线

GridView没有setDivider方法,添加分割线时只能用spacing方法,但是这与圆角的GridView背景会冲突,百度google无果自己解决 (分割线是不通到边的) String[] sc scope.split(",");//when sc is not times 3, make it times 3.int rowNUM (sc.length%3)0? sc.length/3…

LeetCode 320. 列举单词的全部缩写(回溯/位运算)

文章目录1. 题目2. 解题2.1 回溯2.2 位运算1. 题目 请你写出一个能够举单词全部缩写的函数。 注意&#xff1a;输出的顺序并不重要。 示例&#xff1a; 输入: "word" 输出: ["word", "1ord", "w1rd", "wo1d", "wor1…

python中文件基本操作命令及注意事项

我们如果想通过程序去修改文件的名字、删除文件或文件夹、获得路径下的文件列表等等操作&#xff0c;python提供了有关这些操作的模块(os模块),需要导入模块import os. 1、修改文件名字&#xff0c;删除文件及目录相关操作: 函数名 描述 os.mkdir(dirname) 创建文件夹 os.…

IIS 7.0 安装SSL证书过程

记录一下维瑞的技术人员在IIS 7.0 安装SSL证书过程。本文参照维瑞技术中心SSL证书安装文档所编&#xff1a;http://www.willrey.com/support/ Windows 2008 - IIS 7.0 SSL证书安装指南 在获取SSL证书前要做制作生成CSR文件&#xff0c;也就是SSL证书请求文件&#xff0c;当收到…

华为nova4是不是鸿蒙系统,华为nova 4手机什么时候可以升级鸿蒙系统?鸿蒙系统nova4升级时间介绍...

华为鸿蒙系统已经上线好久了&#xff0c;许多用户都已经抢先一步体验了&#xff0c;而最近有一部分使用华为nova4手机的用户跑来问我&#xff0c;自己的手机什么可以升级鸿蒙系统吗&#xff1f;什么时候才能升级&#xff1f;首先可以肯定的告诉大家&#xff0c;可以。具体内容下…

LeetCode 548. 将数组分割成和相等的子数组(哈希set)

文章目录1. 题目2. 解题1. 题目 给定一个有 n 个整数的数组&#xff0c;你需要找到满足以下条件的三元组 (i, j, k) &#xff1a; 0 < i, i 1 < j, j 1 < k < n - 1子数组 (0, i - 1)&#xff0c;(i 1, j - 1)&#xff0c;(j 1, k - 1)&#xff0c;(k 1, n …

利用python创建学生管理系统软件代码赏析

目录 一、学生管理系统&#xff56;1.0&#xff08;需求&#xff09; 二、代码实现 一、学生管理系统&#xff56;1.0&#xff08;需求&#xff09; 1、添加学生信息 2、删除学生信息 3、查看学生信息 4、修改学生信息 二、代码实现 # 使用字典存储学生信息 students {}# 学…

html 仿ios选择控件,仿ios垂直滚动选择

注&#xff1a;必须在手机模式下才有效组件效果图组件效果图使用示例htmlcss.box{margin: 20px auto 20px auto;height: 188px;width: 90%;position: relative;}.box1{position: absolute;height: 100%;width: 60%;border-right: 1px solid #aaa;left: 0;}.box2{right: 0;posit…

asp.net中ADO.NET连接SQL数据库代码和连接Access数据库代码

连接SQL数据库方法&#xff1a; 一、建立连接 1、&#xff08;使用System.Data.SqlClient&#xff09; <1> string strcon; //声明连接字串 strcon "server(local);databasemytable;uidsa;pwdsa;"; //编写连接字串 …

LeetCode 469. 凸多边形(向量叉积)

文章目录1. 题目2. 解题1. 题目 给定一个按顺序连接的多边形的顶点&#xff0c;判断该多边形是否为凸多边形。 注&#xff1a; 顶点个数至少为 3 个且不超过 10,000。 坐标范围为 -10,000 到 10,000。 你可以假定给定的点形成的多边形均为简单多边形。 换句话说&#xff0c;保…

小案例:王者荣耀英雄对战python版代码(仅供娱乐)

直接上代码&#xff1a; #初始化用户信息 import randomprint("本比赛参赛英雄为&#xff1a;1老夫子 2典韦 3吕布") name int(input("请您选择出场英雄&#xff1a;"))if name 1:print("您本次选择的英雄为&#xff1a;老夫子——我会让你明白什么…

2016年10月计算机网络技术,2016年10月自考计算机网络技术练习题及答案(2)

2016年10月自考计算机网络技术练习题及答案(2)一、判断题(针对下面的描述&#xff0c;对的打‘√’&#xff0c;错的打‘X’)1.网络互联层的协议不包括ICMP协议.(错误)2.在同一个网络中&#xff0c;一个主机可有多个IP地址&#xff0c;多个主机也可同时使用一个IP地址.(错误)4.…

每日英语:Lighting: Twigs Shine in Home Decor

The humble twig is finding its way into high-end lighting. The sticks suggest rustic luxury -- think barn weddings and ski resorts -- but can also be found in modern interiors, giving spaces a clean, natural look. twigs:细枝&#xff0c;小树枝    high-e…

小案例:王者荣耀战绩查询系统代码赏析(自娱自乐)

直接上代码&#xff1a; #创建查询系统初始化信息 hero {} id 1000#创建初始化界面 def start():print("***"*9)print("欢迎您使用王者荣耀英雄查询系统&#xff1a;")print("***"*9)print("请按照以下提示信息进行操作&#xff1a;&quo…

LeetCode 1102. 得分最高的路径(优先队列BFS/极大极小化 二分查找)

文章目录1. 题目2. 解题2.1 优先队列BFS2.2 极大极小化 二分查找1. 题目 给你一个 R 行 C 列的整数矩阵 A。矩阵上的路径从 [0,0] 开始&#xff0c;在 [R-1,C-1] 结束。 路径沿四个基本方向&#xff08;上、下、左、右&#xff09;展开&#xff0c;从一个已访问单元格移动到任…

计算机语音未来发展趋势,语音助手横评:发展现状|未来展望

●语音助手现状Siri带动了业内人工智能语音的发展&#xff0c;各大手机厂商都纷纷推出自家的语音助手&#xff0c;不过总体来说&#xff0c;我们心中所期望的那个无所不能的人工智能机器人还是暂时没有办法出现。首先从国内的情况来看&#xff0c;我们使用语音助手的场景也大部…