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

相关文章

中文分词jieba库的使用与实景应用(一)

知识星球:https://articles.zsxq.com/id_fxvgc803qmr2.html 目录 一.定义: 精确模式(默认模式): 全模式: 搜索引擎模式: paddle 模式(基于深度学习的分词模式): 二 自定义词典 三.文本解析   调整词出现的频率 四. 关键词提取 A. 基于TF-IDF算法的关键词提取 B. 基于TextRank算法的关键词提取

基于人工智能的图像分类系统

目录 引言项目背景环境准备 硬件要求软件安装与配置系统设计 系统架构关键技术代码示例 数据预处理模型训练模型预测应用场景结论 1. 引言 图像分类是计算机视觉中的一个重要任务,目标是自动识别图像中的对象类别。通过卷积神经网络(CNN)等深度学习技术,我们可以构建高效的图像分类系统,广泛应用于自动驾驶、医疗影像诊断、监控分析等领域。本文将介绍如何构建一个基于人工智能的图像分类系统,包括环境

水位雨量在线监测系统概述及应用介绍

在当今社会,随着科技的飞速发展,各种智能监测系统已成为保障公共安全、促进资源管理和环境保护的重要工具。其中,水位雨量在线监测系统作为自然灾害预警、水资源管理及水利工程运行的关键技术,其重要性不言而喻。 一、水位雨量在线监测系统的基本原理 水位雨量在线监测系统主要由数据采集单元、数据传输网络、数据处理中心及用户终端四大部分构成,形成了一个完整的闭环系统。 数据采集单元:这是系统的“眼睛”,

Hadoop企业开发案例调优场景

需求 (1)需求:从1G数据中,统计每个单词出现次数。服务器3台,每台配置4G内存,4核CPU,4线程。 (2)需求分析: 1G / 128m = 8个MapTask;1个ReduceTask;1个mrAppMaster 平均每个节点运行10个 / 3台 ≈ 3个任务(4    3    3) HDFS参数调优 (1)修改:hadoop-env.sh export HDFS_NAMENOD

认识、理解、分类——acm之搜索

普通搜索方法有两种:1、广度优先搜索;2、深度优先搜索; 更多搜索方法: 3、双向广度优先搜索; 4、启发式搜索(包括A*算法等); 搜索通常会用到的知识点:状态压缩(位压缩,利用hash思想压缩)。

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

深入探索协同过滤:从原理到推荐模块案例

文章目录 前言一、协同过滤1. 基于用户的协同过滤(UserCF)2. 基于物品的协同过滤(ItemCF)3. 相似度计算方法 二、相似度计算方法1. 欧氏距离2. 皮尔逊相关系数3. 杰卡德相似系数4. 余弦相似度 三、推荐模块案例1.基于文章的协同过滤推荐功能2.基于用户的协同过滤推荐功能 前言     在信息过载的时代,推荐系统成为连接用户与内容的桥梁。本文聚焦于

csu 1446 Problem J Modified LCS (扩展欧几里得算法的简单应用)

这是一道扩展欧几里得算法的简单应用题,这题是在湖南多校训练赛中队友ac的一道题,在比赛之后请教了队友,然后自己把它a掉 这也是自己独自做扩展欧几里得算法的题目 题意:把题意转变下就变成了:求d1*x - d2*y = f2 - f1的解,很明显用exgcd来解 下面介绍一下exgcd的一些知识点:求ax + by = c的解 一、首先求ax + by = gcd(a,b)的解 这个

hdu1394(线段树点更新的应用)

题意:求一个序列经过一定的操作得到的序列的最小逆序数 这题会用到逆序数的一个性质,在0到n-1这些数字组成的乱序排列,将第一个数字A移到最后一位,得到的逆序数为res-a+(n-a-1) 知道上面的知识点后,可以用暴力来解 代码如下: #include<iostream>#include<algorithm>#include<cstring>#include<stack>#in

zoj3820(树的直径的应用)

题意:在一颗树上找两个点,使得所有点到选择与其更近的一个点的距离的最大值最小。 思路:如果是选择一个点的话,那么点就是直径的中点。现在考虑两个点的情况,先求树的直径,再把直径最中间的边去掉,再求剩下的两个子树中直径的中点。 代码如下: #include <stdio.h>#include <string.h>#include <algorithm>#include <map>#