使用随机森林完成csv文件分类


前言

主要介绍了如何使用随机森林完成csv数据的自动分类

一、使用步骤

1.引入库

代码如下(示例):

from sklearn.ensemble import RandomForestRegressor

from sklearn.model_selection import train_test_split

import pandas as pd

import numpy as np

#  用于保存和提取模型

import joblib

import matplotlib.pyplot as plt  # 图库

import warnings

from sklearn.tree import DecisionTreeClassifier, plot_tree  # 这里添加了对plot_tree函数的导入

2.初始化操作(完成字体与警告避免设置)

代码如下(示例):

# 解决画图中文字体显示的问题

plt.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei', 'Times New Roman']  # 汉字字体集

plt.rcParams['font.size'] = 12  # 字体大小

plt.rcParams['axes.unicode_minus'] = False

# 忽略警告

import warnings

warnings.filterwarnings('ignore')

3.读取数据操作

数据内容如下:第一行分别为对应的自变量,

# 读取数据集
data = pd.read_csv('D:/data.csv', encoding='gbk')
 
# 特征 此处选取除了label这列数据,作为自变量
X = data.drop('label', axis=1)
# 目标变量,已label这列名作为标签
y = data['label']
 
# 数据集拆分出训练集和验证集 这里设置训练集与验证集比例为8:2
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=500)
 

#使用交叉验证来选择最佳参数,确保随机森林的最优值
from sklearn.model_selection import KFold, cross_val_score
kf = KFold(n_splits=5)
best_n_estimators = 0
best_score = -np.inf
for n_estimators in range(100, 500, 100):
    RF = RandomForestRegressor(n_jobs=-1, n_estimators=n_estimators)
    scores = cross_val_score(RF, X_train, y_train, cv=kf)
    mean_score = np.mean(scores)
    if mean_score > best_score:
        best_score = mean_score
        best_n_estimators = n_estimators
# 定义一个默认随机森林回归模型  max_depth为最深随机森林层数为5
RF = RandomForestRegressor(n_jobs=-1,n_estimators=best_n_estimators, max_depth=5)
# 训练模型
RF.fit(X_train, y_train)

# 保存模型
joblib.dump(RF, r'./RF.pkl')

4:决策树可视化展示:

# 获取第一棵决策树
first_tree = RF.estimators_[0]

5:与前2000轮进行测试:

# 读取模型
RF = joblib.load(r'./RF.pkl')
 
# 模型预测
y_pred = RF.predict(X_test)
 
# 绘制线图
# 前2000条预测结果的可视化
plt.figure(figsize=(20, 6))
y_tesy_t = np.asarray(y_test)
plt.plot(y_tesy_t[:2000], label='True Values')
plt.plot(y_pred[:2000], label='Predicted Values')
plt.xlabel('Index')
plt.ylabel('Value')
plt.legend()
plt.savefig('./前200条预测结果图.jpg', dpi=400, bbox_inches='tight')
plt.show()

6:模型参数计算显示:

下文会计算随机森林的均方误差、均方根误差、平均绝对误差以及决定系数。

import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
 
# 模型评估
# 计算均方误差(MSE)
mse = mean_squared_error(y_test, y_pred)
print("均方误差(MSE):", mse)
 
# 计算均方根误差(RMSE)
rmse = np.sqrt(mse)
print("均方根误差(RMSE):", rmse)
 
# 计算平均绝对误差(MAE)
mae = mean_absolute_error(y_test, y_pred)
print("平均绝对误差(MAE):", mae)
 
# 计算决定系数(R²)
r2 = r2_score(y_test, y_pred)
print("决定系数(R²):", r2)

7:决策树中变量相关性分析:

# 导入必要的库
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt  # 绘图库
# 解决画图中文字体显示的问题
plt.rcParams['font.sans-serif'] = ['SimSun', 'Times New Roman']  # 汉字字体集
plt.rcParams['font.size'] = 10  # 字体大小
plt.rcParams['axes.unicode_minus'] = False
# 忽略警告
import warnings
warnings.filterwarnings('ignore')
 
# 读取数据集
data = pd.read_csv('D:\lwjdeli/data.csv', encoding='gbk')
# Split data into features and target
X = data.drop('label', axis=1)
y = data['label']
# 定义一个随机森林回归模型
RF = RandomForestRegressor(n_jobs=-1)
# 训练模型
RF.fit(X, y)
# 获取特征重要性得分
feature_importances = RF.feature_importances_
# 创建特征名列表
feature_names = list(X.columns)
# 创建一个DataFrame,包含特征名和其重要性得分
feature_importances_df = pd.DataFrame({'feature': feature_names, 'importance': feature_importances})
# 对特征重要性得分进行排序
feature_importances_df = feature_importances_df.sort_values('importance', ascending=False)
 
# 颜色映射
colors = plt.cm.viridis(np.linspace(0, 1, len(feature_names)))
 
# 可视化特征重要性
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(feature_importances_df['feature'], feature_importances_df['importance'], color=colors)
ax.invert_yaxis()  # 翻转y轴,使得最大的特征在最上面
ax.set_xlabel('特征重要性', fontsize=12)  # 图形的x标签
ax.set_title('随机森林特征重要性可视化',fontsize=16)
for i, v in enumerate(feature_importances_df['importance']):
    ax.text(v + 0.01, i, str(round(v, 3)), va='center', fontname='Times New Roman', fontsize=10)
 
# # 设置图形样式
# plt.style.use('default')
ax.spines['top'].set_visible(False)  # 去掉上边框
ax.spines['right'].set_visible(False)  # 去掉右边框
# ax.spines['left'].set_linewidth(0.5)#左边框粗细
# ax.spines['bottom'].set_linewidth(0.5)#下边框粗细
# ax.tick_params(width=0.5)
# ax.set_facecolor('white')#背景色为白色
# ax.grid(False)#关闭内部网格线
 
# 保存图形
plt.savefig('./特征重要性.jpg', dpi=400, bbox_inches='tight')
plt.show()

整体代码:

# 导入必要的库
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
# 用于保存和提取模型
import joblib
import matplotlib.pyplot as plt  # 绘图库
import warnings
from sklearn.tree import DecisionTreeClassifier, plot_tree  # 这里添加了对plot_tree函数的导入

# 解决画图中文字体显示的问题
plt.rcParams['font.sans-serif'] = ['KaiTi', 'SimHei', 'Times New Roman']  # 汉字字体集
plt.rcParams['font.size'] = 12  # 字体大小
plt.rcParams['axes.unicode_minus'] = False
# 忽略警告
import warnings
warnings.filterwarnings('ignore')
 
# 读取数据集
data = pd.read_csv('D:\lwjdeli/data.csv', encoding='gbk')
 
# 特征
X = data.drop('label', axis=1)
# 目标变量
y = data['label']
 
# 数据集拆分出训练集和验证集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=500)
 

#使用交叉验证来选择最佳参数
from sklearn.model_selection import KFold, cross_val_score
kf = KFold(n_splits=5)
best_n_estimators = 0
best_score = -np.inf
for n_estimators in range(100, 500, 100):
    RF = RandomForestRegressor(n_jobs=-1, n_estimators=n_estimators)
    scores = cross_val_score(RF, X_train, y_train, cv=kf)
    mean_score = np.mean(scores)
    if mean_score > best_score:
        best_score = mean_score
        best_n_estimators = n_estimators
# 定义一个默认随机森林回归模型
RF = RandomForestRegressor(n_jobs=-1,n_estimators=best_n_estimators, max_depth=5)
# 训练模型
RF.fit(X_train, y_train)

# 保存模型
joblib.dump(RF, r'./RF.pkl')

# 获取第一棵决策树
first_tree = RF.estimators_[0]

# 获取目标变量的唯一值作为类别名称(这里假设是分类问题,如果是回归问题可适当调整处理方式)
class_names = y.unique()

# 使用matplotlib的plot_tree函数绘制决策树图形
plt.figure(figsize=(20, 10))
plot_tree(
    first_tree,
    filled=True,
    rounded=True,
    feature_names=X_train.columns,
    class_names=class_names,
    impurity=False,
    fontsize=10
)
plt.title('第一棵决策树树形结构')
plt.show()

# # 保存决策树图形为图片
# graph.write_png('D:\lwjdeli/第一棵决策树树形结构.png')

# 读取模型
RF = joblib.load(r'./RF.pkl')
 
# 模型预测
y_pred = RF.predict(X_test)
 
# 绘制线图
# 前2000条预测结果的可视化
plt.figure(figsize=(20, 6))
y_tesy_t = np.asarray(y_test)
plt.plot(y_tesy_t[:2000], label='True Values')
plt.plot(y_pred[:2000], label='Predicted Values')
plt.xlabel('Index')
plt.ylabel('Value')
plt.legend()
plt.savefig('./前200条预测结果图.jpg', dpi=400, bbox_inches='tight')
plt.show()



import numpy as np
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
 
# 模型评估
# 计算均方误差(MSE)
mse = mean_squared_error(y_test, y_pred)
print("均方误差(MSE):", mse)
 
# 计算均方根误差(RMSE)
rmse = np.sqrt(mse)
print("均方根误差(RMSE):", rmse)
 
# 计算平均绝对误差(MAE)
mae = mean_absolute_error(y_test, y_pred)
print("平均绝对误差(MAE):", mae)
 
# 计算决定系数(R²)
r2 = r2_score(y_test, y_pred)
print("决定系数(R²):", r2)



# 导入必要的库
from sklearn.ensemble import RandomForestRegressor
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt  # 绘图库
# 解决画图中文字体显示的问题
plt.rcParams['font.sans-serif'] = ['SimSun', 'Times New Roman']  # 汉字字体集
plt.rcParams['font.size'] = 10  # 字体大小
plt.rcParams['axes.unicode_minus'] = False
# 忽略警告
import warnings
warnings.filterwarnings('ignore')
 
# 读取数据集
data = pd.read_csv('D:\lwjdeli/data.csv', encoding='gbk')
# Split data into features and target
X = data.drop('label', axis=1)
y = data['label']
# 定义一个随机森林回归模型
RF = RandomForestRegressor(n_jobs=-1)
# 训练模型
RF.fit(X, y)
# 获取特征重要性得分
feature_importances = RF.feature_importances_
# 创建特征名列表
feature_names = list(X.columns)
# 创建一个DataFrame,包含特征名和其重要性得分
feature_importances_df = pd.DataFrame({'feature': feature_names, 'importance': feature_importances})
# 对特征重要性得分进行排序
feature_importances_df = feature_importances_df.sort_values('importance', ascending=False)
 
# 颜色映射
colors = plt.cm.viridis(np.linspace(0, 1, len(feature_names)))
 
# 可视化特征重要性
fig, ax = plt.subplots(figsize=(10, 6))
ax.barh(feature_importances_df['feature'], feature_importances_df['importance'], color=colors)
ax.invert_yaxis()  # 翻转y轴,使得最大的特征在最上面
ax.set_xlabel('特征重要性', fontsize=12)  # 图形的x标签
ax.set_title('随机森林特征重要性可视化',fontsize=16)
for i, v in enumerate(feature_importances_df['importance']):
    ax.text(v + 0.01, i, str(round(v, 3)), va='center', fontname='Times New Roman', fontsize=10)
 
# # 设置图形样式
# plt.style.use('default')
ax.spines['top'].set_visible(False)  # 去掉上边框
ax.spines['right'].set_visible(False)  # 去掉右边框
# ax.spines['left'].set_linewidth(0.5)#左边框粗细
# ax.spines['bottom'].set_linewidth(0.5)#下边框粗细
# ax.tick_params(width=0.5)
# ax.set_facecolor('white')#背景色为白色
# ax.grid(False)#关闭内部网格线
 
# 保存图形
plt.savefig('./特征重要性.jpg', dpi=400, bbox_inches='tight')
plt.show()

总结


以上就是今天要讲的内容,本文详细介绍了如何利用随机森林完成csv数据分析。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值