Kaggle-Housing Prices-(回归预测+Ridge,Lasso,Xgboost模型融合)

news2026/2/13 1:42:26

Housing Prices

题意:

给出房子的各种特性,让你预测如今房子的价格。

思考:

数据处理:

1.用plt查看散点图,选择对价格影响高的特征值:YearBuilt,YearRemodAdd,GarageYrBlt。但是不能直接用时间,更好的是用房子的售卖时间减去这些初始时间,这样更有参考度。
2.筛选出数值型列,null值用平均值填充筛。选出非数值型列,null值用众数填充。
3.选出所有非object类型的特征值名称,正态化处理,取对数,标准化处理。避免数据炸了,消除量纲差异。
4.最后进行独热编码即可。

建立模型:

1.从all_data中分离出模型训练的train数据和test数据,以及Y标签。

2.定义均方根误差函数,使用5折交叉验证,去评估模型。

3.建立Ridge模型,先预处理设置alphas通过训练求出最佳的alphas,打出表格查看最佳参数。给Ridge模型传入数据进行训练,求出测试集的答案,并且求expm1,这是因为前面我们训练的时候把Y标签的数据已经取了log,所以这里要expm回来。然后输出答案为csv文件,然后print看一下Ridge这个模型对本数据的均值mean和标准差std。

4.建立Lasso模型,这里直接传入一些参数lasso会自行选择最佳alpha。同理求出预测结果,然后输出模型的mean和std。

5.建立Xgboost模型,首先使用DMatirx构造出xgboost专属的train和test数据集,用xgb_cv交叉验证来训练 xgboost模型求出最佳迭代参数,然后传入xgb.XGBRegressor模型。同理求出预测结果,然后输出模型的mean和std。

6.建立以Xgboost为主ridge、lasso为辅的模型。使用StackingCVRegressor融合xgboost、ridge、lasso,同理求出预测结果,然后输出模型的mean和std。

7.模型融合,分别求出ridge、lasso、xgb、xgb_r_l,的预测结果,分别分配权重然后求出融合结果。

代码:

import sys
import numpy as np
import pandas as pd
import xgboost
from matplotlib import pyplot as plt
from scipy.stats import skew
from sklearn.linear_model import Ridge, LassoCV
from sklearn.model_selection import cross_val_score
from mlxtend.regressor import StackingCVRegressor
import warnings

warnings.filterwarnings("ignore")
pd.set_option('display.width', 1000)
pd.set_option('display.max_colwidth', 1000)
pd.set_option("display.max_rows", 1000)
pd.set_option("display.max_columns", 1000)


# 数据初始化函数
def init_data(train_data, test_data):
    # 把id和saleprice删掉然后再拼接一起
    all_data = pd.concat([train_data.drop(['Id', 'SalePrice'], axis=1), test_data.drop(['Id'], axis=1)], axis=0)
    # 把房子的各种时间与房子售卖时间做差
    for i in ['YearBuilt', 'YearRemodAdd', 'GarageYrBlt']:
        all_data[i] = all_data['YrSold'] - all_data[i]

    # 筛选出数值型列,null值用平均值填充
    numeric_cols = all_data.select_dtypes(include=np.number).columns
    for col in numeric_cols:
        all_data[col] = all_data[col].fillna(all_data[col].mean())
    # 筛选出非数值型列,null值用众数填充
    non_numeric_cols = all_data.select_dtypes(exclude=np.number).columns
    for col in non_numeric_cols:
        all_data[col] = all_data[col].fillna(all_data[col].mode()[0])

    # 正态化
    train_data["SalePrice"] = np.log1p(train_data["SalePrice"])
    numeric_feats = all_data.dtypes[all_data.dtypes != 'object'].index  # 非object的特征个数
    skewed_feats = train_data[numeric_feats].apply(lambda x: skew(x.dropna()))
    skewed_feats = skewed_feats[skewed_feats > 0.75]
    skewed_feats = skewed_feats.index
    all_data[skewed_feats] = np.log1p(all_data[skewed_feats])
    # 连续值归一化
    all_data[numeric_feats] = all_data[numeric_feats].apply(lambda x: (x - x.mean()) / (x.std()))

    # 独热编码
    all_data = pd.get_dummies(all_data)

    return all_data


# 计算不同模型下在X_train与Y这组测试数据中的水平
def rmse_cv(model, X_train, Y):
    rmse = np.sqrt(-cross_val_score(model, X_train, Y, scoring='neg_mean_squared_error', cv=5))
    return rmse


if __name__ == '__main__':
    train_data = pd.read_csv('/kaggle/input/home-data-for-ml-course/train.csv')
    test_data = pd.read_csv('/kaggle/input/home-data-for-ml-course/test.csv')
    all_data = init_data(train_data, test_data)
    X_train = all_data[:train_data.shape[0]]
    X_test = all_data[train_data.shape[0]:]
    Y = train_data['SalePrice']

    # 建立Ridge回归模型
    alphas = [0.05, 0.1, 0.3, 1, 3, 5, 10, 15, 30, 50, 75]
    cv_ridge = [rmse_cv(Ridge(alpha=i), X_train, Y).mean() for i in alphas]
    cv_ridge = pd.Series(cv_ridge, index=alphas)
    cv_ridge.plot(title="Validation")
    plt.xlabel("Alpha")
    plt.ylabel("RMSE")
    plt.show()
    model_ridge = Ridge(alpha=10)
    ridge_model_after_fit = model_ridge.fit(X_train, Y)
    ridge_preds = np.expm1(model_ridge.predict(X_test))
    solution = pd.DataFrame({"id": test_data['Id'], "SalePrice": ridge_preds})
    solution.to_csv('ridge_sol.csv', index=False)
    print("model_ridge:" + str(rmse_cv(model_ridge, X_train, Y).mean()) + "   " + str(
        rmse_cv(model_ridge, X_train, Y).std()))

    # 建立Lasso回归模型
    model_lasso = LassoCV(alphas=[20, 10, 1, 0.1, 0.01, 0.001, 0.0005]).fit(X_train, Y)
    lasso_preds = np.expm1(model_lasso.predict(X_test))
    solution = pd.DataFrame({"id": test_data['Id'], "SalePrice": lasso_preds})
    solution.to_csv('lasso_sol.csv', index=False)
    print("model_lasso:" + str(rmse_cv(model_lasso, X_train, Y).mean()) + "   " + str(
        rmse_cv(model_lasso, X_train, Y).std()))

    # 建立xgboost回归模型
    xgb_cv_train = xgboost.DMatrix(X_train, label=Y)
    xgb_cv_test = xgboost.DMatrix(X_test)
    params = {"objective": "reg:squarederror",
              "max_depth": 4,
              "colsample_bylevel": 0.5,
              "learning_rate": 0.1,
              "random_state": 20}
    model_xgb_test = xgboost.cv(
        params,
        xgb_cv_train,
        num_boost_round=500,
        early_stopping_rounds=100,
        as_pandas=True
    )
    model_xgb = xgboost.XGBRegressor(n_estimators=model_xgb_test["test-rmse-mean"].idxmin(), max_depth=4, learning_rate=0.3)
    model_xgb.fit(X_train, Y)
    xgb_preds = np.expm1(model_xgb.predict(X_test))
    solution = pd.DataFrame({"id": test_data['Id'], "SalePrice": xgb_preds})
    solution.to_csv('xgb_sol.csv', index=False)
    print("model_xgb:" + str(rmse_cv(model_xgb, X_train, Y).mean()) + "   " + str(rmse_cv(model_xgb, X_train, Y).std()))

    # xgboost为主、ridge与lasso为辅
    model_x_r_l = StackingCVRegressor(regressors=(model_ridge, model_lasso, model_xgb),
                                      meta_regressor=model_xgb,
                                      use_features_in_secondary=True)
    model_x_r_l.fit(X_train, Y)
    model_x_r_l_preds = np.expm1(model_x_r_l.predict(X_test))
    solution = pd.DataFrame({"id": test_data['Id'], "SalePrice": model_x_r_l_preds})
    solution.to_csv('model_x_r_l.csv', index=False)
    print("model_x_r_l:" + str(rmse_cv(model_x_r_l, X_train, Y).mean()) + "   " + str(
        rmse_cv(model_x_r_l, X_train, Y).std()))

    # 尝试混合模型
    preds1 = model_ridge.predict(X_test)
    preds2 = model_lasso.predict(X_test)
    preds3 = model_xgb.predict(X_test)
    preds4 = model_x_r_l.predict(X_test)
    combine_preds = 0.4 * preds1 + 0.6 * preds4
    combine_preds = np.floor(np.expm1(combine_preds))
    solution = pd.DataFrame({"id": test_data['Id'], "SalePrice": combine_preds})
    solution.to_csv('/kaggle/working/Submission.csv', index=False)

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

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

相关文章

GNSS有源天线和无源天线

区别 需要外部供电的就是有源天线,不需要外部供电的是无源天线。 无源天线 一般就是一个陶瓷片、金属片等,结构简单,成本低廉,占用空间及体积小,适合于强调紧凑型空间的导航类产品。 不需要供电,跟设备直…

欧税通香港分公司办公室正式乔迁至海港城!

3月20日,欧税通香港分公司办公室正式乔迁至香港油尖旺区的核心商业区海港城!左手挽着内地市场,右手牵起国际航道——这波乔迁选址操作堪称“地理课代表”! 乔迁仪式秒变行业大联欢!感谢亚马逊合规团队、亚马逊云、阿里国际站、Wayfair、coupang、美客多…

ETPNav:基于演进拓扑规划的连续环境视觉语言导航模型

1、现有工作的缺陷: 最近,出现了一种基于模块化航路点的方法的新兴趋势,该方法将复杂任务分为航路点生成、子目标规划和导航控制: (1)在每个决策循环中,代理使用预训练的网络来预测附近的几个…

Spring Cloud LoadBalancer负载均衡+算法切换

目录 介绍核心功能负载均衡启动两个支付服务订单模块引入依赖LoadBalanced 注解启动订单服务测试结果 负载均衡算法切换总结 介绍 Spring Cloud LoadBalancer 是 Spring Cloud 提供的客户端负载均衡解决方案,提供更现代化的 API 和更好的 Spring 生态系统集成。它支…

游戏引擎学习第210天

回顾并为今天的工作做准备 今天我们,进行一些编码工作。这部分的编码内容对那些对代码架构感兴趣的人非常有帮助,我认为今天的编码内容会很有教育意义,尤其是在展示一些代码转化的过程中,希望大家能够从中获得一些启发。 接下来…

UML类图综合实验三补档

1.使用简单工厂模式模拟女娲(Nvwa)造人(Person),如果传入参数“M”,则返回一个Man对象,如果传入参数“W”,则返回一个Woman对象,用Java语言实现该场景。现需要增加一个新的Robot类,如果传入参数“R”&#…

WinForm真入门(11)——ComboBox控件详解

WinForm中 ComboBox 控件详解‌ ComboBox 是 WinForms 中一个集文本框与下拉列表于一体的控件,支持用户从预定义选项中选择或直接输入内容。以下从核心属性、事件、使用场景到高级技巧的全面解析: 一、ComboBox 核心属性‌ 属性说明示例‌Items‌下拉…

DeepSeek底层揭秘——《推理时Scaling方法》技术对比浅析

4月初,DeepSeek 提交到 arXiv 上的最新论文正在 AI 社区逐渐升温。 笔者尝试对比了“关于推理时Scaling”与现有技术,粗浅分析如下: 与LoRA的对比 区别: 应用场景:LoRA是一种参数高效微调方法,主要用于在…

Android Coli 3 ImageView load two suit Bitmap thumb and formal,Kotlin(四)

Android Coli 3 ImageView load two suit Bitmap thumb and formal,Kotlin(四) 对 Android Coli 3 ImageView load two suit Bitmap thumb and formal,Kotlin(三)-CSDN博客 进行完善,注意完善 …

Adam优化器研究综述

摘要 Adam优化器(Adaptive Moment Estimation)是一种广泛应用于深度学习的优化算法,通过自适应学习率加速梯度下降过程。本文从Adam的定义、算法原理、优势与局限性、应用场景及变体等方面进行调研,结合学术文献和实践经验&#x…

在 macOS 上连接 PostgreSQL 数据库(pgAdmin、DBeaver)

在 macOS 上连接 PostgreSQL 数据库 pgAdmin 官方提供的图形化管理工具,支持 macOS。 下载地址:https://www.pgadmin.org/ pgAdmin 4 是对 pgAdmin 的完全重写,使用 Python、ReactJs 和 Javascript 构建。一个用 Electron 编写的桌面运行时…

2018年真题

数学基础 一、 (共4分)用逻辑符号表达下列语句(论域为包含一切事物的集合) 1、(2分)集合A的任一元素的元素都是A的元素 经过对图片文字的识别与逻辑分析,结果如下: 符号定义&…

Efficient Burst Raw Denoising:稳定噪声方差和分频率降噪

Efficient Burst Raw Denoising with Stabilization and Multi-Frequency Denoising Network Burst Raw Denoising必要性Burst Raw Image Denoising流程Main Contributions具体方法介绍集成noise priorCMOS sensor 噪声建模噪声变换(Variance stabilization&#xf…

mapbox进阶,使用本地dem数据,加载hillshade山体阴影图层

👨‍⚕️ 主页: gis分享者 👨‍⚕️ 感谢各位大佬 点赞👍 收藏⭐ 留言📝 加关注✅! 👨‍⚕️ 收录于专栏:mapbox 从入门到精通 文章目录 一、🍀前言1.1 ☘️mapboxgl.Map 地图对象1.2 ☘️mapboxgl.Map style属性1.3 ☘️hillshade 山体阴影图层 api1.3.1 ☘️…

【C++】Stack Queue 仿函数

📝前言: 这篇文章我们来讲讲STL中的stack和queue。因为前面我们已经有了string、vector和list的学习基础,所以这篇文章主要关注一些stack和queue的细节问题,以及了解一下deque(缝合怪)和priority_queue &am…

代码随想录_单调栈

代码随想录_单调栈 739.每日温度 739. 每日温度 给定一个整数数组 temperatures ,表示每天的温度,返回一个数组 answer ,其中 answer[i] 是指对于第 i 天,下一个更高温度出现在几天后。如果气温在这之后都不会升高,…

BoostSearch搜索引擎项目 —— 测试用例设计 + web自动化测试代码

web自动化代码: https://gitee.com/chicken-c/boost-search/tree/master/AutoTest

【Ansible自动化运维】一、初步了解,开启自动化运维之旅

在当今数字化时代,随着企业 IT 基础设施规模的不断扩大,传统的手工运维方式逐渐显得力不从心。自动化运维技术应运而生,其中 Ansible 凭借其简洁易用、功能强大的特点,成为众多运维工程师和开发人员的首选工具。本篇文章将从基础概…

条件概率、概率乘法公式、全概率公式和贝叶斯 (Bayes) 公式

定义 设 P ( A ) > 0 P(A) > 0 P(A)>0,若在随机事件 A A A发生的条件下随机事件 B B B发生的概率记作 P ( B ∣ A ) P(B|A) P(B∣A),定义 P ( B ∣ A ) P ( A B ) P ( A ) P(B|A) \frac{P(AB)}{P(A)} P(B∣A)P(A)P(AB)​ 则称 P ( B ∣ A ) …

kotlin,Android,jetpack compose,日期时间设置

AI生成,调试出来学习,这些小组件会用了,就可以组合一个大点的程序了。 package com.example.mydatetimeimport android.app.AlertDialog import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.co…