首页 > 其他分享 >随机森林代码实现(奥拓数据分类)

随机森林代码实现(奥拓数据分类)

时间:2023-12-13 19:14:40浏览次数:31  
标签:parameters 代码 axes tuned estimator 随机 test 奥拓 accuracy

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

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

import seaborn as sns

sns.countplot(data.target)
plt.show()

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

from imblearn.under_sampling import RandomUnderSampler
rus = RandomUnderSampler()
x_resampled,y_resampled = rus.fit_resample(x,y)
sns.countplot(y_resampled)
plt.show()

y_resampled
#j将标签转化为编码
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y_resampled = le.fit_transform(y_resampled)
y_resampled

#数据集分割
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test = train_test_split(x_resampled,y_resampled,test_size=0.2)

from sklearn.ensemble import RandomForestClassifier

estimator = RandomForestClassifier(oob_score=True)
estimator.fit(x_train,y_train)
y_pre = estimator.predict(x_test)
y_test,y_pre
from sklearn.preprocessing import OneHotEncoder

one_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_loss

log_loss(y_test,y_pre,eps=1e-15,normalize=True)
# 7.637713870225003
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

# 确定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)
    
    # 输出accuracy
    accuracy_t[i] = estimator.oob_score_
    
    # 输出log_loss
    y_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()

 确定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)
    
    # 输出accuracy
    accuracy_t[i] = estimator.oob_score_
    
    # 输出log_loss
    y_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_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)
    
    # 输出accuracy
    accuracy_t[i] = estimator.oob_score_
    
    # 输出log_loss
    y_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()

# 确定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)
    
    # 输出accuracy
    accuracy_t[i] = estimator.oob_score_
    
    # 输出log_loss
    y_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()


#确定最优模型
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

 

标签:parameters,代码,axes,tuned,estimator,随机,test,奥拓,accuracy
From: https://www.cnblogs.com/copyjames/p/17899733.html

相关文章

  • 代驾系统开发:驾驶智能化的代码之路
    代驾系统的开发涉及到许多复杂而精密的技术,这些技术的融合不仅提升了出行服务的水平,也为开发者带来了独特的挑战。让我们深入探讨代驾系统的关键技术和相应的代码实现。1.实时定位技术:代驾系统的核心在于实时定位,这涉及到全球定位系统(GPS)和无线通信技术的高效应用。以下是一个简单......
  • 低代码配置式软件——组态软件
    随着物联网、大数据等技术高速发展,我们逐步向数字化、可视化的人工智能(AI)时代的方向不断迈进。智能时代是工业4.0时代,我国工业领域正努力从“制造”迈向“智造”的新跨越。什么是组态软件?组态软件,又称组态监控软件。它们处在自动控制系统监控层一级的软件平台和开发环境,使用灵活......
  • cbindgen rust 代码生成c binding 的工具
    rust与c以及c与rust的互调用还是比较常见的需求,很多时候自己写可能比较费事,但是使用一些工具就比较方便了cbindgen是一个对于rust代码生成cbinding的工具参考使用基于cbindgen将rust的代码生成对应的c头文件,之后基于cmake构建项目项目结构 ├──......
  • Google代码规范工具之cpplint
    谷歌代码规范链接:https://zh-google-styleguide.readthedocs.io/en/latest/google-cpp-styleguide/ 代码规范工具—cpplint:1)在Vscode中搜索并安装插件cpplint2)接着打开终端,输入sudopipinstallcpplint3)再次输入ls-l/usr/local/bin/cpplint检查安装目录,一般会安装......
  • 车机 Android 调节音量的三种方式及底层代码逻辑
    注意:本文基于Android12/S进行分析Qidi2023.07.20(MarkDown&EnterpriseArchitect&Haroopad)0.车机环境下音量调节的特殊性车机环境下的音频使用场景,相较于原始Android的音频使用场景,存在这些特殊性:使用专门的aDSP芯片进行音效处理;需要播放/控制原始Android......
  • 随机模拟——蒙特卡洛算法的Python实现
    蒙特卡洛方法是一类基于随机抽样的数值计算技术,通过模拟随机事件的概率过程,从而近似计算复杂问题的数学期望或积分。其核心思想是通过大量的随机抽样来逼近问题的解,从而在随机性中获得问题的统计特性。蒙特卡洛方法广泛应用于概率统计、物理学、金融工程、生物学等领域。在蒙特卡......
  • 通过 VS Code 优雅地编辑 Pod 内的代码(非 NodePort)
    目录1.概述2.NodePort方式3.Ingress方式4.救命稻草5.其他1.概述今天聊点啥呢,话说,你有没有想过怎样用VSCode连上K8s集群内的某个Pod,然后直接更新Pod内的代码?当我听到这个需求的时候,第一反应是在Pod内搞一个sshd,然后NodePort方式暴露Pod,接着用VSCode的......
  • 代码随想录算法训练营Day1 | 704.二分查找、27.移除元素
    LeetCode704.二分查找二分查找是一种基础的算法,其核心思想在高中数学中就已经被大家所熟知了,然而对于代码的实现,其细节问题常常令人头疼,比如while循环的条件是什么?middle是该+1还是-1?这些问题需要有一个清晰的认知。题目链接如下:704.二分查找Carl的讲解链接:二分查找算法......
  • 阅读笔记:《代码大全》阅读笔记十
    《代码大全》是我在软件开发领域的一本必读书籍。这本书几乎涵盖了软件开发的方方面面,从编码到设计、测试到调试等各个环节都有详细的讲解和指导。首先,我被作者对于代码的重视所深深吸引。他在书中强调,代码质量决定了软件的可靠性和可维护性。好的代码应该易读、易懂、易维护。通......
  • WebSocket硬核入门:200行代码,教你徒手撸一个WebSocket服务器
    1、引言最近正在研究WebSocket相关的知识,想着如何能自己实现WebSocket协议。到网上搜罗了一番资料后用Node.js实现了一个WebSocket协议服务器,倒也没有想象中那么复杂,除去注释语句和console语句后,大约200行代码左右。本文分享了自已开发一个WebSocket服务端实现......