随机森林应用案例 —— 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

相关文章

使用Navicat工具比对两个数据库所有表结构的差异案例详解

《使用Navicat工具比对两个数据库所有表结构的差异案例详解》:本文主要介绍如何使用Navicat工具对比两个数据库test_old和test_new,并生成相应的DDLSQL语句,以便将te... 目录概要案例一、如图两个数据库test_old和test_new进行比较:二、开始比较总结概要公司存在多

C#使用DeepSeek API实现自然语言处理,文本分类和情感分析

《C#使用DeepSeekAPI实现自然语言处理,文本分类和情感分析》在C#中使用DeepSeekAPI可以实现多种功能,例如自然语言处理、文本分类、情感分析等,本文主要为大家介绍了具体实现步骤,... 目录准备工作文本生成文本分类问答系统代码生成翻译功能文本摘要文本校对图像描述生成总结在C#中使用Deep

5分钟获取deepseek api并搭建简易问答应用

《5分钟获取deepseekapi并搭建简易问答应用》本文主要介绍了5分钟获取deepseekapi并搭建简易问答应用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需... 目录1、获取api2、获取base_url和chat_model3、配置模型参数方法一:终端中临时将加

JavaScript中的isTrusted属性及其应用场景详解

《JavaScript中的isTrusted属性及其应用场景详解》在现代Web开发中,JavaScript是构建交互式应用的核心语言,随着前端技术的不断发展,开发者需要处理越来越多的复杂场景,例如事件... 目录引言一、问题背景二、isTrusted 属性的来源与作用1. isTrusted 的定义2. 为

SpringBoot实现动态插拔的AOP的完整案例

《SpringBoot实现动态插拔的AOP的完整案例》在现代软件开发中,面向切面编程(AOP)是一种非常重要的技术,能够有效实现日志记录、安全控制、性能监控等横切关注点的分离,在传统的AOP实现中,切... 目录引言一、AOP 概述1.1 什么是 AOP1.2 AOP 的典型应用场景1.3 为什么需要动态插

Python调用另一个py文件并传递参数常见的方法及其应用场景

《Python调用另一个py文件并传递参数常见的方法及其应用场景》:本文主要介绍在Python中调用另一个py文件并传递参数的几种常见方法,包括使用import语句、exec函数、subproce... 目录前言1. 使用import语句1.1 基本用法1.2 导入特定函数1.3 处理文件路径2. 使用ex

Golang操作DuckDB实战案例分享

《Golang操作DuckDB实战案例分享》DuckDB是一个嵌入式SQL数据库引擎,它与众所周知的SQLite非常相似,但它是为olap风格的工作负载设计的,DuckDB支持各种数据类型和SQL特性... 目录DuckDB的主要优点环境准备初始化表和数据查询单行或多行错误处理和事务完整代码最后总结Duck

Python中的随机森林算法与实战

《Python中的随机森林算法与实战》本文详细介绍了随机森林算法,包括其原理、实现步骤、分类和回归案例,并讨论了其优点和缺点,通过面向对象编程实现了一个简单的随机森林模型,并应用于鸢尾花分类和波士顿房... 目录1、随机森林算法概述2、随机森林的原理3、实现步骤4、分类案例:使用随机森林预测鸢尾花品种4.1

将Python应用部署到生产环境的小技巧分享

《将Python应用部署到生产环境的小技巧分享》文章主要讲述了在将Python应用程序部署到生产环境之前,需要进行的准备工作和最佳实践,包括心态调整、代码审查、测试覆盖率提升、配置文件优化、日志记录完... 目录部署前夜:从开发到生产的心理准备与检查清单环境搭建:打造稳固的应用运行平台自动化流水线:让部署像

MySQL不使用子查询的原因及优化案例

《MySQL不使用子查询的原因及优化案例》对于mysql,不推荐使用子查询,效率太差,执行子查询时,MYSQL需要创建临时表,查询完毕后再删除这些临时表,所以,子查询的速度会受到一定的影响,本文给大家... 目录不推荐使用子查询和JOIN的原因解决方案优化案例案例1:查询所有有库存的商品信息案例2:使用EX