Kaggler日志--Day5
进度24/12/15
昨日复盘
Intermediate Mechine Learning
之类型变量
读两篇讲解如何提问的文章,在提问区里发起一次提问
实战:自己从头到尾首先Housing Prices Competition for Kaggle Learn Users
并成功提交
Intermediate Mechine Learning
之管道(pipeline之前一直错译为工作流)
今日进度
Intermediate Mechine Learning
之交叉验证
Intermediate Mechine Learning
之XGBoost
Intermediate Mechine Learning
之数据泄露
利用以上所学刷一遍分数。
Cross-Validation
交叉验证用来更好的测评模型表现。
验证集越大,我们得到的测评结果约可靠,但是在数据集大小确定的情况下,验证集越大意味着训练集越小,这是我们不想面对的情况。
交叉验证将数据分为多个fold
,进行多次实验,每次实验使用其中一个fold
作为验证集,最终确保每一个已知数据都被当作验证集使用过。
优点是足够可靠,缺点是开销翻倍。如果运行一次时间可以接收,采用交叉验证无疑是一个不错的选择,但如果运行时间较长,且数据量足够大,则不宜采用交叉验证。
利用交叉验证选择最优参数:
#数据只保留了数字类型
numeric_cols = [cname for cname in train_data.columns if train_data[cname].dtype in ['int64', 'float64']]
X = train_data[numeric_cols].copy()
X_test = test_data[numeric_cols].copy()from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.model_selection import cross_val_scoredef get_score(n_estimators):"""Return the average MAE over 3 CV folds of random forest model.Keyword argument:n_estimators -- the number of trees in the forest"""# Replace this body with your own codemy_pipeline = Pipeline(steps=[('preprocessor', SimpleImputer()),('model', RandomForestRegressor(n_estimators=n_estimators, random_state=0))])scores = -1 * cross_val_score(my_pipeline, X, y,cv=3,scoring='neg_mean_absolute_error')return scores.mean()n_list = list(range(50, 401, 50))
results = {}
for ns in n_list:mean_s = get_score(ns)results[ns] = mean_sprint(results)import matplotlib.pyplot as plt
%matplotlib inlineplt.plot(list(results.keys()), list(results.values()))
plt.show()
后续可以学习超参数优化课程,可以从网格搜索grid search
开始
XGBoost
对于结构化数据最准确的建模技术
gradient boosting
梯度迭代模型是Kaggle比赛中实现了多种数据集的SOTA
对于随机森林方法,它本质上使用了多个单独的决策树进行学习,可以称作ensemble methods
集成学习方法。另外一种集成学习方法叫做graient boosting
基本流程:先使用一个基本模型做出预测,计算损失函数。利用这个损失值去训练新的模型。具体来说,我们决定了模型参数以便新的模型加入后可以降低损失。
XGBoost代表了极致的梯度迭代,专注于表现和效率。
from xgboost import XGBRegressor
my_model = XGBRegressor()
my_model.fit(X_train, y_train)# 更多参数
my_model = XGBRegressor(n_estimators=500, learning_rate=0.05, n_jobs=4) # 迭代次数,学习率和并行数
my_model.fit(X_train, y_train, early_stopping_rounds=5, #自动停止eval_set=[(X_valid, y_valid)], #测试用集合verbose=False)
Data Leakage
数据泄露使得模型在训练时看起来非常准确,但是用来预测时准确率不高。
两种类型的数据泄露:target leakage
和train-test contamination
训练、测试污染
Target leakage
目标泄露发生在时间或时间顺序类型的数据上。
任何在目标产生那一刻以后生成的数据都不应该出现在已知变量集合中。
示例:生病的人会用抗生素,如果是否服用抗生素信息出现在训练数据中,在训练和验证时依据这个信息就可以准确地判断一个人是否生病。但是实际用来预测时,一个人未来是否会生病和当前是否服用抗生素没有直接的必然联系,原本学习到的经验变成了错误的。
Train-test Contamination
如果验证和测试数据通过某种方式影响了模型的训练过程,就会导致这种泄露。这种泄露的发生有时是不易察觉的,需要注意数据预处理的时间。
一个建议是:When using cross-validation, it’s even more critical that you do your preprocessing inside the pipeline!
观察这样一组数据
- card: 1 if credit card application accepted, 0 if not
- reports: Number of major derogatory reports
- age: Age n years plus twelfths of a year
- income: Yearly income (divided by 10,000)
- share: Ratio of monthly credit card expenditure to yearly income
- expenditure: Average monthly credit card expenditure
- owner: 1 if owns home, 0 if rents
- selfempl: 1 if self-employed, 0 if not
- dependents: 1 + number of dependents
- months: Months living at current address
- majorcards: Number of major credit cards held
- active: Number of active credit accounts
expenditures_cardholders = X.expenditure[y]
expenditures_noncardholders = X.expenditure[~y]print('Fraction of those who did not receive a card and had no expenditures: %.2f' \%((expenditures_noncardholders == 0).mean()))
print('Fraction of those who received a card and had no expenditures: %.2f' \%(( expenditures_cardholders == 0).mean()))
"""
Fraction of those who did not receive a card and had no expenditures: 1.00
Fraction of those who received a card and had no expenditures: 0.02
"""potential_leaks = ['expenditure', 'share', 'active', 'majorcards'] #排除潜在可能的泄露
X2 = X.drop(potential_leaks, axis=1)# Evaluate the model with leaky predictors removed
cv_scores = cross_val_score(my_pipeline, X2, y, cv=5,scoring='accuracy')print("Cross-val accuracy: %f" % cv_scores.mean()) # 准确率大大下降
一般只会发生在自己构建的数据集上,标准数据集一般不会有这种情况。如果不能详尽的了解每一项数据的由来,排除所有可能的泄露也许是更好的选择。
另一个好用的方法是:在实际的预测场景中能用相同的方法获取到的数据用在训练中都不算泄露。
实际应用场景中,还要考虑预测结果是否真的有效。
一个加深理解的例子
Step 4: Preventing Infections
An agency that provides healthcare wants to predict which patients from a rare surgery are at risk of infection, so it can alert the nurses to be especially careful when following up with those patients.
You want to build a model. Each row in the modeling dataset will be a single patient who received the surgery, and the prediction target will be whether they got an infection.
Some surgeons may do the procedure in a manner that raises or lowers the risk of infection. But how can you best incorporate the surgeon information into the model?
You have a clever idea.
- Take all surgeries by each surgeon and calculate the infection rate among those surgeons.
- For each patient in the data, find out who the surgeon was and plug in that surgeon’s average infection rate as a feature.
Does this pose any target leakage issues?
Does it pose any train-test contamination issues?
This poses a risk of both target leakage and train-test contamination (though you may be able to avoid both if you are careful).
You have target leakage if a given patient’s outcome contributes to the infection rate for his surgeon, which is then plugged back into the prediction model for whether that patient becomes infected. You can avoid target leakage if you calculate the surgeon’s infection rate by using only the surgeries before the patient we are predicting for. Calculating this for each surgery in your training data may be a little tricky.
You also have a train-test contamination problem if you calculate this using all surgeries a surgeon performed, including those from the test-set. The result would be that your model could look very accurate on the test set, even if it wouldn’t generalize well to new patients after the model is deployed. This would happen because the surgeon-risk feature accounts for data in the test set. Test sets exist to estimate how the model will do when seeing new data. So this contamination defeats the purpose of the test set.
非常有帮助的例子。直觉上没有问题,但是考虑到手术数据本身就很少,感觉结果又会对某些变量有影响。(当数据量很大时,某个病人是否感染对比例产生的影响微乎其微)
但是从原理上将,只要结果参与到某个用于预测的变量的计算中,这就叫数据泄露,本例中毫无疑问是发生了数据泄露的。
实战XGBoost–pipelien
# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to loadimport numpy as np # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)# Input data files are available in the read-only "../input/" directory
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directoryimport os
for dirname, _, filenames in os.walk('/kaggle/input'):for filename in filenames:print(os.path.join(dirname, filename))# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using "Save & Run All"
# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session# Load original data
from sklearn.model_selection import train_test_splitX_full = pd.read_csv("/kaggle/input/home-data-for-ml-course/train.csv")
X_test = pd.read_csv("/kaggle/input/home-data-for-ml-course/test.csv")X_full.dropna(axis=0, subset=['SalePrice'], inplace=True)
y = X_full.SalePrice
X_full.drop(['SalePrice'], axis=1, inplace=True)# X_train, X_valid, y_train, y_valid = train_test_split(X_full, y, train_size=0.8, test_size=0.2,# random_state=0)print("Load data successfully.")# print(X_full.isnull().sum()[X_full.isnull().sum()>0])
# # 对于缺失值过多的列,采用丢弃策略
# X_drop_cols = [col for col in X_full.columns if X_full[col].isnull().sum() > 100]
# X_full.drop(X_drop_cols, axis=1, inplace=True)numerical_cols = [col for col in X_full.columns if X_full[col].dtype in ["int64", "float64"]]
categorical_cols = [col for col in X_full.columns if X_full[col].dtype == "object"]# print(X_drop_cols)# define pipelinefrom sklearn.compose import ColumnTransformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
from sklearn.compose import ColumnTransformer
from sklearn.model_selection import cross_val_scorenumerical_transformer = SimpleImputer(strategy="constant")categorical_transformer = Pipeline(steps=[('imputer', SimpleImputer(strategy="most_frequent")),('one_hot', OneHotEncoder(handle_unknown="ignore"))
])preprocessor = ColumnTransformer(transformers=[('num', numerical_transformer, numerical_cols),('cat', categorical_transformer, categorical_cols)]
)def get_score(model):my_pipeline = Pipeline(steps=[('preprocessor', preprocessor),('model', model)])scores = -1 * cross_val_score(my_pipeline, X_full, y,cv=3,scoring='neg_mean_absolute_error')return scores.mean()print("get_score defined.")# 挑选最佳模型
from xgboost import XGBRegressor
# my_model = XGBRegressor(n_estimators=2000,
# learning_rate=0.01,
# random_state=0,
# n_jobs=4)
# s = get_score(my_model)
# print(f"MAE is {s}")
- 最原始模型:17468
- 丢弃缺失值超过10的:17562
- 丢弃缺失值超过40的:17524
- 丢弃缺失值超过100的:17516
不丢弃(原始500):
- epoch-200: 17489
- epoch-300: 17467
- epoch-400: 17463
- epoch-450: 17467
学习率–0.05–>0.01
- 轮次450: 17818
- 轮次600:17504
- 轮次700:17403
- 轮次800:17343
- 轮次900:17319
- 轮次1000:17307
- 轮次1500:17271
- 轮次2000:17268
final_model = XGBRegressor(n_estimators=2000, learning_rate=0.01,random_state=0,n_jobs=4)
final_pipeline = Pipeline(steps=[('preprocessor', preprocessor),('model', final_model)])final_pipeline.fit(X_full, y)predictions = final_pipeline.predict(X_test)
print("Predictions on test set:", predictions)output = pd.DataFrame({'Id': X_test.Id,'SalePrice': predictions})
output.to_csv("submission.csv", index=False)
print("Sub saved")
最终损失14898,排名到了140/4711
相关文章:

Kaggler日志--Day5
进度24/12/15 昨日复盘 Intermediate Mechine Learning之类型变量 读两篇讲解如何提问的文章,在提问区里发起一次提问 实战:自己从头到尾首先Housing Prices Competition for Kaggle Learn Users并成功提交 Intermediate Mechine Learning之管道&#…...

VScode MAC按任意键关闭终端 想要访问桌面文件
说明 最近配置MAC上CPP的运行环境,在安装必要的CPP插件后,配置launch和task等json文件后,点击运行三角形,每次都会跳出main想要访问桌面上的文件。并且输出也是在调试控制台,非常逆天。 尝试 尝试1:尽管我尝试将ta…...
小粑记故乡的记忆
小粑,是我的故乡一安徽池州一带盛行的小吃。约成人掌心大小,厚度只三、四厘米,故谓之“小”。 小粑,主打取材随性,方便常做常吃。这也许就是它抓住人的味蕾,渐次流行开来,成为当地名小吃的主要原…...
git使用小记
环境(centos为例): yum -y install gitmkdir git_dir && cd git_dirgit clone *** 修改代码: git checkout master 切到主分支git pull 拉取最新代码git branch dev 创建开发分支git checkout dev 切换到开发分支修…...
Python实现办公自动化——自动编写word文档
Python实现办公自动化——自动编写word文档 前言安装python-docxpython-docx使用创建word文档设置纸张方向、大小和页边距统一设置格式插入文本插入表格插入图片 结语 前言 工作中有大量的报告编写需求,在不停地复制粘贴之后,突然想到,这种高…...

番外篇 | BGF-YOLO:引入双层路由注意力、广义特征金字塔网络和第四检测头,提高YOLOv8检测性能
前言:Hello大家好,我是小哥谈。本文提出了一种名为BGF-YOLO的新模型,通过引入双层路由注意力、广义特征金字塔网络和第四检测头,提高YOLOv8在脑肿瘤检测中的性能,采用多层特征融合与动态稀疏注意机制以减少特征冗余。 🌈 目录 🚀1.基础概念 🚀2.网络结构 �…...
Python运维自动化之字典Dict
字典Dict(哈希表) Dict即Dictionary,也称为mapping。 Python中,字典由任意个元素构成的集合,每一个元素称为Item,也称为Entry。这个Item是由(key, value)组成的二元组。 字典是可变的、无序的、key不重复的key-value键值对集合。…...

axios请求拦截器和响应拦截器,封装naive-ui的 Loading Bar加载条和useMessage消息提示
接之前的博客设计从0开始边做边学,用vue和python做一个博客,非规范化项目,怎么简单怎么弄,跑的起来有啥毛病解决啥毛病(三),目前已经完成了基本的功能demo,但是请求接口不可能每个页…...
9.Python 条件语句和循环语句
文章目录 Python 条件语句和循环语句1. **条件语句 (Conditional Statements)**1.1 if 语句1.2 if-else 语句1.3 if-elif-else 语句 2. **循环语句 (Loop Statements)**2.1 while 循环2.2 for 循环2.3 循环嵌套 (Nested Loops) 3. **控制循环的语句**3.1 break 语句3.2 continu…...
智能家居控制系统设计
设计智能家居控制系统是一个复杂但有趣的项目,它涉及硬件与软件的集成、网络通信、用户界面设计等多个方面。以下是一个智能家居控制系统的基本设计思路: 1. 需求分析- 功能需求:明确系统需要实现的功能,如灯光控制、空调温度调节…...

Windows系统word插入公式自动编号并交叉引用
一、定义新的多级列表 鼠标单击页面空白处 二、插入域 鼠标单击要插入公式编号的地方 三、交叉引用 鼠标单击要引用公式编号的地方 四、更新编号(域) CtrlA:全选全文 鼠标右键:更新域...
0.基础语法
文章目录 1. 第一个 Python 程序2. Python2.x 和 Python3.x 的差异3. 标识符和保留字符4. 行和缩进5. 多行语句6. 引号7. 注释8. 空行9. 用户输入10. Print 输出11. 代码组12. 命令行参数 Python 基础语法涵盖了从安装和运行 Python 程序到理解语言核心概念的各个方面。以下是基…...

mysql命令行界面(黑框)的登录
文章目录 开启关闭服务报错登录mysql退出mysql数据据database在电脑中的存放位置删除数据库语句 drop注意 cmd用管理员打开 开启关闭服务 报错 我有这个报错,但是使用没什么影响 登录mysql root替换成自己的用户名 退出mysql exit 数据据database在电脑中的…...

【机器学习】解构概率,重构世界:贝叶斯定理与智能世界的暗语
文章目录 条件概率与贝叶斯定理:深入理解机器学习中的概率关系前言一、条件概率与贝叶斯定理1.1 条件概率的定义与公式1.1.1 条件概率的定义1.1.2 条件概率的实例讲解 1.2 条件概率的性质与法则1.2.1 链式法则1.2.2 全概率公式1.2.3 贝叶斯定理的推导 1.3 贝叶斯定理…...

threejs——无人机概念切割效果
主要技术采用着色器的切割渲染,和之前写的风车可视化的文章不同,这次的切割效果是在着色器的基础上实现的,并新增了很多可调节的变量,兄弟们,走曲儿~ 线上演示地址,点击体验 源码下载地址,点击下载 正文 从图中大概可以看出以下信息,一个由线组成的无人机模型,一个由…...

electron学习笔记(一)
1.创建项目 mkdir myelectron npm init npm install --save-dev electron //安装通过以上命令, 我们就有了一个 electron 的项目 之后, 设置主文件入口 , 添加热启动 nodemon 2. nodemon 的使用和配置 要根目录下添加 nodemon.json 文件,配…...

基于Arduino蹲便器的自动清洁系统(论文+源码)
1系统整体设计 经过上述的方案分析,最终确定了Arduino UNO开发板为核心,结合蓝牙模块,舵机,电磁阀,红外传感器,步进电机,舵机等硬件设备来构成整个控制系统,整体框图如图2.1所示。其…...
【JavaWeb后端学习笔记】使用HttpClient发送Http请求
使用HttpClient发送Http请求需要在项目中导入相关依赖: <dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version> </dependency>1、 HttpClient…...

2024告别培训班 数通、安全、云计算、云服务、存储、软考等1000G资源分享
大类有:软考初级 软考中级 软考高级 华为认证 华三认证: 软考初级: 信息处理技术员 程序员 网络管理员 软考中级: 信息安全工程师 信息系统监理师 信息系统管理工程师 嵌入式系统设计时 数据库系统工程师 电子商务设…...

【C++】- 掌握STL List类:带你探索双向链表的魅力
文章目录 前言:一.list的介绍及使用1. list的介绍2. list的使用2.1 list的构造2.2 list iterator的使用2.3 list capacity2.4 list element access2.5 list modifiers2.6 list的迭代器失效 二.list的模拟实现1. list的节点2. list的成员变量3.list迭代器相关问题3.1…...

接口测试中缓存处理策略
在接口测试中,缓存处理策略是一个关键环节,直接影响测试结果的准确性和可靠性。合理的缓存处理策略能够确保测试环境的一致性,避免因缓存数据导致的测试偏差。以下是接口测试中常见的缓存处理策略及其详细说明: 一、缓存处理的核…...

Prompt Tuning、P-Tuning、Prefix Tuning的区别
一、Prompt Tuning、P-Tuning、Prefix Tuning的区别 1. Prompt Tuning(提示调优) 核心思想:固定预训练模型参数,仅学习额外的连续提示向量(通常是嵌入层的一部分)。实现方式:在输入文本前添加可训练的连续向量(软提示),模型只更新这些提示参数。优势:参数量少(仅提…...
k8s从入门到放弃之Ingress七层负载
k8s从入门到放弃之Ingress七层负载 在Kubernetes(简称K8s)中,Ingress是一个API对象,它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress,你可…...
使用van-uploader 的UI组件,结合vue2如何实现图片上传组件的封装
以下是基于 vant-ui(适配 Vue2 版本 )实现截图中照片上传预览、删除功能,并封装成可复用组件的完整代码,包含样式和逻辑实现,可直接在 Vue2 项目中使用: 1. 封装的图片上传组件 ImageUploader.vue <te…...

学习STC51单片机31(芯片为STC89C52RCRC)OLED显示屏1
每日一言 生活的美好,总是藏在那些你咬牙坚持的日子里。 硬件:OLED 以后要用到OLED的时候找到这个文件 OLED的设备地址 SSD1306"SSD" 是品牌缩写,"1306" 是产品编号。 驱动 OLED 屏幕的 IIC 总线数据传输格式 示意图 …...

SpringCloudGateway 自定义局部过滤器
场景: 将所有请求转化为同一路径请求(方便穿网配置)在请求头内标识原来路径,然后在将请求分发给不同服务 AllToOneGatewayFilterFactory import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; impor…...

AI书签管理工具开发全记录(十九):嵌入资源处理
1.前言 📝 在上一篇文章中,我们完成了书签的导入导出功能。本篇文章我们研究如何处理嵌入资源,方便后续将资源打包到一个可执行文件中。 2.embed介绍 🎯 Go 1.16 引入了革命性的 embed 包,彻底改变了静态资源管理的…...

使用 SymPy 进行向量和矩阵的高级操作
在科学计算和工程领域,向量和矩阵操作是解决问题的核心技能之一。Python 的 SymPy 库提供了强大的符号计算功能,能够高效地处理向量和矩阵的各种操作。本文将深入探讨如何使用 SymPy 进行向量和矩阵的创建、合并以及维度拓展等操作,并通过具体…...

以光量子为例,详解量子获取方式
光量子技术获取量子比特可在室温下进行。该方式有望通过与名为硅光子学(silicon photonics)的光波导(optical waveguide)芯片制造技术和光纤等光通信技术相结合来实现量子计算机。量子力学中,光既是波又是粒子。光子本…...

招商蛇口 | 执笔CID,启幕低密生活新境
作为中国城市生长的力量,招商蛇口以“美好生活承载者”为使命,深耕全球111座城市,以央企担当匠造时代理想人居。从深圳湾的开拓基因到西安高新CID的战略落子,招商蛇口始终与城市发展同频共振,以建筑诠释对土地与生活的…...