随机森林应用案例 —— otto产品分类

2023-10-20 17:50

本文主要是介绍随机森林应用案例 —— otto产品分类,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

otto产品分类

  • 1 案例背景
  • 2 数据集介绍
  • 3 评分标准
  • 4 流程实现
    • 4.1 获取数据集
    • 4.2 数据基本处理
    • 4.3 模型训练
    • 4.4 模型评估
    • 4.5 模型调优
    • 4.6 生成提交数据

1 案例背景

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

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

2 数据集介绍

本案例中,数据集包含大约200,000种产品的93个特征。其目的是建立一个能够区分otto公司主要产品类别的预测模型。所有产品共被分成九个类别(例如时装,电子产品等)
在这里插入图片描述

  • id - 产品id
  • feat_1, feat_2, …, feat_93 - 产品的各个特征
  • target - 产品被划分的类别

数据集:https://www.kaggle.com/c/otto-group-product-classification-challenge/overview

3 评分标准

在这里插入图片描述

4 流程实现

4.1 获取数据集

import pandas as pd
import numpy as np
import matplotlib.pyplot as pltdata = pd.read_csv("./Data/otto/train.csv")
data.head()

在这里插入图片描述
查看数据分布

import seaborn as snssns.countplot(data.target)
plt.show()

在这里插入图片描述
由上图可以看出,该数据类别不均衡,因数据量庞大,采用随机欠采样进行处理

4.2 数据基本处理

(1)确定特征值和标签值

# 采用随机欠采样之前需要确定数据的特征值和标签值
y=data["target"]
x=data.drop(["id","target"],axis=1)

(2)随机欠采样处理

from imblearn.under_sampling import RandomUnderSamplerrus = RandomUnderSampler()
x_resampled,y_resampled = rus.fit_resample(x,y)

查看欠采样后的数据形状

x.shape,y.shape
# ((61878, 93), (61878,))
x_resampled.shape,y_resampled.shape
# ((17361, 93), (17361,))

查看数据经过欠采样之后类别是否平衡

sns.countplot(y_resampled)
plt.show()

在这里插入图片描述

(3)把标签值转换为数字

y_resampled

在这里插入图片描述

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

在这里插入图片描述
(4)分割数据

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)

4.3 模型训练

from sklearn.ensemble import RandomForestClassifierestimator = RandomForestClassifier(oob_score=True)
estimator.fit(x_train,y_train)

4.4 模型评估

本题要求使用logloss进行模型评估

y_pre = estimator.predict(x_test)
y_test,y_pre

在这里插入图片描述

需要注意的是:logloss在使用过程中,必须要求将输出用one-hot表示

from sklearn.preprocessing import OneHotEncoderone_hot = OneHotEncoder(sparse=False)
y_pre = one_hot.fit_transform(y_pre.reshape(-1,1))
y_test = one_hot.fit_transform(y_test.reshape(-1,1))
y_test,y_pre

在这里插入图片描述

from sklearn.metrics import log_losslog_loss(y_test,y_pre,eps=1e-15,normalize=True)
# 7.637713870225003

改变预测值的输出模式,让输出结果为可能性的百分占比,降低logloss值

y_pre_proba = estimator.predict_proba(x_test)
y_pre_proba

在这里插入图片描述

log_loss(y_test,y_pre_proba,eps=1e-15,normalize=True)
# 0.7611795612521034

由此可见,log_loss值下降了许多

4.5 模型调优

(1)确定最优的n_estimators

# 确定n_estimators的取值范围
tuned_parameters = range(10,200,10)# 创建添加accuracy的一个numpy
accuracy_t = np.zeros(len(tuned_parameters)) # 创建添加error的一个numpy
error_t = np.zeros(len(tuned_parameters)) # 调优过程实现
for i,one_parameter in enumerate(tuned_parameters):estimator = RandomForestClassifier(n_estimators=one_parameter,max_depth=10,max_features=10,min_samples_leaf=10,oob_score=True,random_state=0,n_jobs=-1)estimator.fit(x_train,y_train)# 输出accuracyaccuracy_t[i] = estimator.oob_score_# 输出log_lossy_pre = estimator.predict_proba(x_test)error_t[i] = log_loss(y_test,y_pre,eps=1e-15,normalize=True)# 优化结果过程可视化 
fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,4),dpi=100)
axes[0].plot(tuned_parameters,accuracy_t)
axes[1].plot(tuned_parameters,error_t)axes[0].set_xlabel("n_estimators")
axes[0].set_ylabel("accuracy_t")axes[1].set_xlabel("n_estimators")
axes[1].set_ylabel("error_t")axes[0].grid()
axes[1].grid()

在这里插入图片描述
经过图像展示,最后确定n_estimators=175时,效果不错

(2)确定最优的max_depth

# 确定max_depth的取值范围
tuned_parameters = range(10,100,10)# 创建添加accuracy的一个numpy
accuracy_t = np.zeros(len(tuned_parameters)) # 创建添加error的一个numpy
error_t = np.zeros(len(tuned_parameters)) # 调优过程实现
for i,one_parameter in enumerate(tuned_parameters):estimator = RandomForestClassifier(n_estimators=175,max_depth=one_parameter,max_features=10,min_samples_leaf=10,oob_score=True,random_state=0,n_jobs=-1)estimator.fit(x_train,y_train)# 输出accuracyaccuracy_t[i] = estimator.oob_score_# 输出log_lossy_pre = estimator.predict_proba(x_test)error_t[i] = log_loss(y_test,y_pre,eps=1e-15,normalize=True)# 优化结果过程可视化 
fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,4),dpi=100)
axes[0].plot(tuned_parameters,accuracy_t)
axes[1].plot(tuned_parameters,error_t)axes[0].set_xlabel("max_depth")
axes[0].set_ylabel("accuracy_t")axes[1].set_xlabel("max_depth")
axes[1].set_ylabel("error_t")axes[0].grid()
axes[1].grid()

在这里插入图片描述
经过图像展示,最后确定max_depth=30时,效果不错

(3)确定最优的max_features

# 确定max_features取值范围
tuned_parameters = range(5,40,5)# 创建添加accuracy的一个numpy
accuracy_t = np.zeros(len(tuned_parameters)) # 创建添加error的一个numpy
error_t = np.zeros(len(tuned_parameters)) # 调优过程实现
for i,one_parameter in enumerate(tuned_parameters):estimator = RandomForestClassifier(n_estimators=175,max_depth=30,max_features=one_parameter,min_samples_leaf=10,oob_score=True,random_state=0,n_jobs=-1)estimator.fit(x_train,y_train)# 输出accuracyaccuracy_t[i] = estimator.oob_score_# 输出log_lossy_pre = estimator.predict_proba(x_test)error_t[i] = log_loss(y_test,y_pre,eps=1e-15,normalize=True)# 优化结果过程可视化
fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,4),dpi=100)
axes[0].plot(tuned_parameters,accuracy_t)
axes[1].plot(tuned_parameters,error_t)axes[0].set_xlabel("max_features")
axes[0].set_ylabel("accuracy_t")axes[1].set_xlabel("max_features")
axes[1].set_ylabel("error_t")axes[0].grid()
axes[1].grid()

在这里插入图片描述
经过图像展示,最后确定max_features=15时,效果不错

(4)确定最优的min_samples_leaf

# 确定n_estimators的取值范围
tuned_parameters = range(1,10,2)# 创建添加accuracy的一个numpy
accuracy_t = np.zeros(len(tuned_parameters)) # 创建添加error的一个numpy
error_t = np.zeros(len(tuned_parameters)) # 调优过程实现
for i,one_parameter in enumerate(tuned_parameters):estimator = RandomForestClassifier(n_estimators=175,max_depth=30,max_features=15,min_samples_leaf=one_parameter,oob_score=True,random_state=0,n_jobs=-1)estimator.fit(x_train,y_train)# 输出accuracyaccuracy_t[i] = estimator.oob_score_# 输出log_lossy_pre = estimator.predict_proba(x_test)error_t[i] = log_loss(y_test,y_pre,eps=1e-15,normalize=True)# 优化结果过程可视化
fig,axes = plt.subplots(nrows=1,ncols=2,figsize=(20,4),dpi=100)
axes[0].plot(tuned_parameters,accuracy_t)
axes[1].plot(tuned_parameters,error_t)axes[0].set_xlabel("min_samples_leaf")
axes[0].set_ylabel("accuracy_t")axes[1].set_xlabel("min_samples_leaf")
axes[1].set_ylabel("error_t")axes[0].grid()
axes[1].grid()

在这里插入图片描述
经过图像展示,最后确定min_samples_leaf=1时,效果不错

(5)确定最优模型

estimator = RandomForestClassifier(n_estimators=175,max_depth=30,max_features=15,min_samples_leaf=1,oob_score=True,random_state=0,n_jobs=-1)
estimator.fit(x_train,y_train)
y_pre_proba = estimator.predict_proba(x_test)
log_loss(y_test,y_pre_proba)
# 0.7413651159154644

4.6 生成提交数据

test_data = pd.read_csv("./Data/otto/test.csv")
test_data.head()

在这里插入图片描述

注意:测试集是没有目标值的

为了便于模型预测,删去 id 列,仅保留特征列

test_data_drop_id = test_data.drop("id",axis=1)
test_data_drop_id.head()

在这里插入图片描述

y_pre_test = estimator.predict_proba(test_data_drop_id)
y_pre_test

在这里插入图片描述
按要求生成列名

result_data = pd.DataFrame(y_pre_test,columns=["Class_"+str(i) for i in range(1,10)])
result_data.head()

在这里插入图片描述
在第一列添加 id 列

result_data.insert(loc=0,column="id",value=test_data.id)
result_data.head()

在这里插入图片描述
生成提交数据的csv文件

result_data.to_csv("./Data/otto/Submission.csv",index=False)

这篇关于随机森林应用案例 —— otto产品分类的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

Python使用Tkinter打造一个完整的桌面应用

《Python使用Tkinter打造一个完整的桌面应用》在Python生态中,Tkinter就像一把瑞士军刀,它没有花哨的特效,却能快速搭建出实用的图形界面,作为Python自带的标准库,无需安装即可... 目录一、界面搭建:像搭积木一样组合控件二、菜单系统:给应用装上“控制中枢”三、事件驱动:让界面“活”

MySQL 表的内外连接案例详解

《MySQL表的内外连接案例详解》本文给大家介绍MySQL表的内外连接,结合实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录表的内外连接(重点)内连接外连接表的内外连接(重点)内连接内连接实际上就是利用where子句对两种表形成的笛卡儿积进行筛选,我

如何确定哪些软件是Mac系统自带的? Mac系统内置应用查看技巧

《如何确定哪些软件是Mac系统自带的?Mac系统内置应用查看技巧》如何确定哪些软件是Mac系统自带的?mac系统中有很多自带的应用,想要看看哪些是系统自带,该怎么查看呢?下面我们就来看看Mac系统内... 在MAC电脑上,可以使用以下方法来确定哪些软件是系统自带的:1.应用程序文件夹打开应用程序文件夹

Java Stream.reduce()方法操作实际案例讲解

《JavaStream.reduce()方法操作实际案例讲解》reduce是JavaStreamAPI中的一个核心操作,用于将流中的元素组合起来产生单个结果,:本文主要介绍JavaStream.... 目录一、reduce的基本概念1. 什么是reduce操作2. reduce方法的三种形式二、reduce

Python Flask 库及应用场景

《PythonFlask库及应用场景》Flask是Python生态中​轻量级且高度灵活的Web开发框架,基于WerkzeugWSGI工具库和Jinja2模板引擎构建,下面给大家介绍PythonFl... 目录一、Flask 库简介二、核心组件与架构三、常用函数与核心操作 ​1. 基础应用搭建​2. 路由与参

Spring Boot中的YML配置列表及应用小结

《SpringBoot中的YML配置列表及应用小结》在SpringBoot中使用YAML进行列表的配置不仅简洁明了,还能提高代码的可读性和可维护性,:本文主要介绍SpringBoot中的YML配... 目录YAML列表的基础语法在Spring Boot中的应用从YAML读取列表列表中的复杂对象其他注意事项总

Spring Boot 整合 Redis 实现数据缓存案例详解

《SpringBoot整合Redis实现数据缓存案例详解》Springboot缓存,默认使用的是ConcurrentMap的方式来实现的,然而我们在项目中并不会这么使用,本文介绍SpringB... 目录1.添加 Maven 依赖2.配置Redis属性3.创建 redisCacheManager4.使用Sp

电脑系统Hosts文件原理和应用分享

《电脑系统Hosts文件原理和应用分享》Hosts是一个没有扩展名的系统文件,当用户在浏览器中输入一个需要登录的网址时,系统会首先自动从Hosts文件中寻找对应的IP地址,一旦找到,系统会立即打开对应... Hosts是一个没有扩展名的系统文件,可以用记事本等工具打开,其作用就是将一些常用的网址域名与其对应

springboot项目redis缓存异常实战案例详解(提供解决方案)

《springboot项目redis缓存异常实战案例详解(提供解决方案)》redis基本上是高并发场景上会用到的一个高性能的key-value数据库,属于nosql类型,一般用作于缓存,一般是结合数据... 目录缓存异常实践案例缓存穿透问题缓存击穿问题(其中也解决了穿透问题)完整代码缓存异常实践案例Red

CSS 样式表的四种应用方式及css注释的应用小结

《CSS样式表的四种应用方式及css注释的应用小结》:本文主要介绍了CSS样式表的四种应用方式及css注释的应用小结,本文通过实例代码给大家介绍的非常详细,详细内容请阅读本文,希望能对你有所帮助... 一、外部 css(推荐方式)定义:将 CSS 代码保存为独立的 .css 文件,通过 <link> 标签