otto案例介绍 -- Otto Group Product Classification Challenge【xgboost实现】

本文主要是介绍otto案例介绍 -- Otto Group Product Classification Challenge【xgboost实现】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

【机器学习】otto案例介绍

  • 1. 背景介绍
  • 2. 思路分析
  • 3. 代码实现
    • 3.1 数据获取
    • 3.2 数据基本处理
      • 3.2.1 截取部分数据
      • 3.2.2 把标签值转换为数字
      • 3.2.3 分割数据
      • 3.2.4 数据标准化
      • 3.2.5 数据PCA降维
    • 3.3 模型训练
      • 3.3.1 基本模型训练
      • 3.3.2 模型调优
        • 3.3.2.1 确定最优的estimators
        • 3.3.2.2 确定最优的max_depth
        • 3.3.2.3 依据上面模式,运行调试下面参数
      • 3.3.3 最优模型

1. 背景介绍

奥托集团是世界上最⼤的电⼦商务公司之⼀,在20多个国家设有⼦公司。该公司每天都在世界各地销售数百万种产品, 所以对其产品根据性能合理的分类⾮常重要。

不过,在实际⼯作中,⼯作⼈员发现,许多相同的产品得到了不同的分类。本案例要求,你对奥拓集团的产品进⾏正确的分分 类。尽可能的提供分类的准确性。

链接:https://www.kaggle.com/c/otto-group-product-classification-challenge/overview

在这里插入图片描述

2. 思路分析

  • 1.数据获取
  • 2.数据基本处理
    • 2.1 截取部分数据
    • 2.2 把标签纸转换为数字
    • 2.3 分割数据(使⽤StratifiedShuffleSplit)
    • 2.4 数据标准化
    • 2.5 数据pca降维
  • 3.模型训练
    • 3.1 基本模型训练
    • 3.2 模型调优
      • 3.2.1 调优参数:
        • n_estimator,
        • max_depth,
        • min_child_weights,
        • subsamples,
        • consample_bytrees,
        • etas
      • 3.2.2 确定最后最优参数

3. 代码实现

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

3.1 数据获取

data = pd.read_csv("./data/otto/train.csv")

在这里插入图片描述

data.shape
(61878, 95)
data.describe()

在这里插入图片描述

# 图形可视化,查看数据分布
import seaborn as snssns.countplot(data.target)plt.show()

在这里插入图片描述
由上图可以看出,该数据类别不均衡,所以需要后期处理

3.2 数据基本处理

数据已经经过脱敏,不再需要特殊处理

3.2.1 截取部分数据

new1_data = data[:10000]
new1_data.shape
# 图形可视化,查看数据分布
import seaborn as snssns.countplot(new1_data.target)plt.show()

在这里插入图片描述
使用上面方式获取数据不可行,然后使用随机欠采样获取响应的数据

# 随机欠采样获取数据
# 首先需要确定特征值\标签值y = data["target"]
x = data.drop(["id", "target"], axis=1)

在这里插入图片描述

# 欠采样获取数据
from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler(random_state=0)X_resampled, y_resampled = rus.fit_resample(x, y)
x.shape, y.shape
X_resampled.shape, y_resampled.shape

在这里插入图片描述

# 图形可视化,查看数据分布
import seaborn as snssns.countplot(y_resampled)plt.show()

在这里插入图片描述

3.2.2 把标签值转换为数字

y_resampled.head()

在这里插入图片描述

from sklearn.preprocessing import LabelEncoderle = LabelEncoder()
y_resampled = le.fit_transform(y_resampled)

在这里插入图片描述

3.2.3 分割数据

from sklearn.model_selection import train_test_splitx_train, x_test, y_train, y_test = train_test_split(X_resampled, y_resampled, test_size=0.2)
x_train.shape, y_train.shape

在这里插入图片描述

# 图形可视化
import seaborn as snssns.countplot(y_test)
plt.show()

在这里插入图片描述

# 通过StratifiedShuffleSplit实现数据分割from sklearn.model_selection import StratifiedShuffleSplitsss = StratifiedShuffleSplit(n_splits=1, test_size=0.2, random_state=0)for train_index, test_index in sss.split(X_resampled.values, y_resampled):print(len(train_index))print(len(test_index))x_train = X_resampled.values[train_index]x_val = X_resampled.values[test_index]y_train = y_resampled[train_index]y_val = y_resampled[test_index]

13888
3473

print(x_train.shape, x_val.shape)
(13888, 93) (3473, 93)
# 图形可视化
import seaborn as snssns.countplot(y_val)
plt.show()

在这里插入图片描述

3.2.4 数据标准化

from sklearn.preprocessing import StandardScalerscaler = StandardScaler()
scaler.fit(x_train)x_train_scaled = scaler.transform(x_train)
x_val_scaled = scaler.transform(x_val)

3.2.5 数据PCA降维

x_train_scaled.shape
(13888, 93)
from sklearn.decomposition import PCApca = PCA(n_components=0.9)x_train_pca = pca.fit_transform(x_train_scaled)
x_val_pca = pca.transform(x_val_scaled)
print(x_train_pca.shape, x_val_pca.shape)
# 可视化数据降维信息变化程度
plt.plot(np.cumsum(pca.explained_variance_ratio_))plt.xlabel("元素数量")
plt.ylabel("表达信息百分占比")plt.show()

在这里插入图片描述

3.3 模型训练

3.3.1 基本模型训练

from xgboost import XGBClassifierxgb = XGBClassifier()
xgb.fit(x_train_pca, y_train)
# 输出预测值,一定输出带有百分占比的预测值
y_pre_proba = xgb.predict_proba(x_val_pca)
y_pre_proba

在这里插入图片描述

# logloss评估
from sklearn.metrics import log_losslog_loss(y_val, y_pre_proba, eps=1e-15, normalize=True)
0.735851001353164
xgb.get_params

在这里插入图片描述

3.3.2 模型调优

3.3.2.1 确定最优的estimators
scores_ne = []
n_estimators = [100, 200, 300, 400, 500, 550, 600, 700]
for nes in n_estimators:print("n_estimators:", nes)xgb = XGBClassifier(max_depth=3,learning_rate=0.1, n_estimators=nes, objective="multi:softprob", n_jobs=-1, nthread=4, min_child_weight=1,subsample=1,colsample_bytree=1,seed=42)xgb.fit(x_train_pca, y_train)y_pre = xgb.predict_proba(x_val_pca)score = log_loss(y_val, y_pre)scores_ne.append(score)print("每次测试的logloss值是:{}".format(score))
# 图形化展示相应的logloss值
plt.plot(n_estimators, scores_ne, "o-")plt.xlabel("n_estimators")
plt.ylabel("log_loss")
plt.show()print("最优的n_estimators值是:{}".format(n_estimators[np.argmin(scores_ne)]))
3.3.2.2 确定最优的max_depth
scores_md = []
max_depths = [1,3,5,6,7]
for md in max_depths:print("max_depth:", md)xgb = XGBClassifier(max_depth=md,learning_rate=0.1, n_estimators=n_estimators[np.argmin(scores_ne)], objective="multi:softprob", n_jobs=-1, nthread=4, min_child_weight=1,subsample=1,colsample_bytree=1,seed=42)xgb.fit(x_train_pca, y_train)y_pre = xgb.predict_proba(x_val_pca)score = log_loss(y_val, y_pre)scores_md.append(score)print("每次测试的logloss值是:{}".format(score))
# 图形化展示相应的logloss值
plt.plot(max_depths, scores_md, "o-")plt.xlabel("max_depths")
plt.ylabel("log_loss")
plt.show()print("最优的max_depths值是:{}".format(max_depths[np.argmin(scores_md)]))
3.3.2.3 依据上面模式,运行调试下面参数
min_child_weights,subsamples,consample_bytrees,etas

3.3.3 最优模型

xgb = XGBClassifier(learning_rate =0.1, n_estimators=550, max_depth=3, min_child_weight=3, subsample=0.7, colsample_bytree=0.7, nthread=4, seed=42, objective='multi:softprob')xgb.fit(x_train_scaled, y_train)y_pre = xgb.predict_proba(x_val_scaled)print("测试数据的log_loss值为 : {}".format(log_loss(y_val, y_pre, eps=1e-15, normalize=True)))

加油!

感谢!

努力!

这篇关于otto案例介绍 -- Otto Group Product Classification Challenge【xgboost实现】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/404845

相关文章

使用Redis快速实现共享Session登录的详细步骤

《使用Redis快速实现共享Session登录的详细步骤》在Web开发中,Session通常用于存储用户的会话信息,允许用户在多个页面之间保持登录状态,Redis是一个开源的高性能键值数据库,广泛用于... 目录前言实现原理:步骤:使用Redis实现共享Session登录1. 引入Redis依赖2. 配置R

SpringBoot实现RSA+AES自动接口解密的实战指南

《SpringBoot实现RSA+AES自动接口解密的实战指南》在当今数据泄露频发的网络环境中,接口安全已成为开发者不可忽视的核心议题,RSA+AES混合加密方案因其安全性高、性能优越而被广泛采用,本... 目录一、项目依赖与环境准备1.1 Maven依赖配置1.2 密钥生成与配置二、加密工具类实现2.1

在Java中实现线程之间的数据共享的几种方式总结

《在Java中实现线程之间的数据共享的几种方式总结》在Java中实现线程间数据共享是并发编程的核心需求,但需要谨慎处理同步问题以避免竞态条件,本文通过代码示例给大家介绍了几种主要实现方式及其最佳实践,... 目录1. 共享变量与同步机制2. 轻量级通信机制3. 线程安全容器4. 线程局部变量(ThreadL

python使用Akshare与Streamlit实现股票估值分析教程(图文代码)

《python使用Akshare与Streamlit实现股票估值分析教程(图文代码)》入职测试中的一道题,要求:从Akshare下载某一个股票近十年的财务报表包括,资产负债表,利润表,现金流量表,保存... 目录一、前言二、核心知识点梳理1、Akshare数据获取2、Pandas数据处理3、Matplotl

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

MySQL常用字符串函数示例和场景介绍

《MySQL常用字符串函数示例和场景介绍》MySQL提供了丰富的字符串函数帮助我们高效地对字符串进行处理、转换和分析,本文我将全面且深入地介绍MySQL常用的字符串函数,并结合具体示例和场景,帮你熟练... 目录一、字符串函数概述1.1 字符串函数的作用1.2 字符串函数分类二、字符串长度与统计函数2.1

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买