实验八:随机森林算法实现与测试

一、实验目的

深入理解随机森林的算法原理,进而理解集成学习的意义,能够使用Python语言实现随机森林算法的训练与测试,并且使用五折交叉验证算法进行模型训练与评估。

二、实验内容

(1)从scikit-learn 库中加载 iris 数据集,使用留出法留出 1/3 的样本作为测试集(注意同分布取样);

(2)使用训练集训练随机森林分类算法;

(3)使用五折交叉验证对模型性能(准确度、精度、召回率和 F1 值)进行评估和选择;

(4)使用测试集,测试模型的性能,对测试结果进行分析,完成实验报告中实验八的部分。

三、算法步骤、代码、及结果

  1. 算法伪代码

(1)加载数据

(2)划分训练集和测试集

(3)训练随机森林分类器

(4)五折交叉验证

(5)测试集评估

  1. 算法主要代码

完整源代码\调用库方法(函数参数说明)

完整源码:

import numpy as np

from sklearn.model_selection import train_test_split, cross_val_score, KFold

from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score

from sklearn.datasets import load_iris

from sklearn.ensemble import RandomForestClassifier

 

iris = load_iris()

X = iris.data

y = iris.target

 

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42, stratify=y)

 

rf = RandomForestClassifier(n_estimators=100, random_state=42)

rf.fit(X_train, y_train)

 

kf = KFold(n_splits=5, shuffle=True, random_state=42)

 

accuracy_scores = []

precision_scores = []

recall_scores = []

f1_scores = []

 

for train_index, val_index in kf.split(X_train):

    X_fold_train, X_fold_val = X_train[train_index], X_train[val_index]

    y_fold_train, y_fold_val = y_train[train_index], y_train[val_index]

   

    rf_fold = RandomForestClassifier(n_estimators=100, random_state=42)

    rf_fold.fit(X_fold_train, y_fold_train)

    y_val_pred = rf_fold.predict(X_fold_val)

 

    accuracy_scores.append(accuracy_score(y_fold_val, y_val_pred))

    precision_scores.append(precision_score(y_fold_val, y_val_pred, average='weighted'))

    recall_scores.append(recall_score(y_fold_val, y_val_pred, average='weighted'))

    f1_scores.append(f1_score(y_fold_val, y_val_pred, average='weighted'))

 

print("五折交叉验证结果:")

print(f"准确率: {np.mean(accuracy_scores):.4f}")

print(f"精度: {np.mean(precision_scores):.4f}")

print(f"召回率: {np.mean(recall_scores):.4f}")

print(f"F1 值: {np.mean(f1_scores):.4f}")

 

y_test_pred = rf.predict(X_test)

 

test_accuracy = accuracy_score(y_test, y_test_pred)

test_precision = precision_score(y_test, y_test_pred, average='weighted')

test_recall = recall_score(y_test, y_test_pred, average='weighted')

test_f1 = f1_score(y_test, y_test_pred, average='weighted')

 

print("\n测试集结果:")

print(f"准确率: {test_accuracy:.4f}")

print(f"精度: {test_precision:.4f}")

print(f"召回率: {test_recall:.4f}")

print(f"F1 值: {test_f1:.4f}")

参数说明:

(1)train_test_split(X, y, test_size, random_state, stratify)

X: 特征数据,二维数组。

y: 标签数据,一维数组。

test_size: 测试集比例,取值范围为 (0,1)。默认值为 0.25。

random_state: 随机种子,确保每次运行划分结果一致。

stratify: 保持类分布一致,通常为 y。

作用: 划分训练集和测试集。

(2)RandomForestClassifier(n_estimators, random_state, max_depth)

n_estimators: 决策树数量,默认值为 100。

random_state: 随机种子。

max_depth: 每棵树的最大深度,默认值为 None,即允许树完全生长。

作用: 创建随机森林分类器。

(3)KFold(n_splits, shuffle, random_state)

n_splits: 数据划分的折数,默认为 5。

shuffle: 是否在划分前打乱数据,默认为 False。

random_state: 随机种子,配合 shuffle=True 使用。

作用: 将数据划分为 n_splits 个子集。

(4)accuracy_score, precision_score, recall_score, f1_score

y_true: 真实标签。

y_pred: 预测标签。

average: 对多类分类问题,weighted 表示加权平均,micro 表示全局计算。

作用: 评估分类器性能。

  1. 训练结果截图(包括:准确率、精度(查准率)、召回率(查全率)、F1)

四、实验结果分析

  1. 测试结果截图(包括:准确率、精度(查准率)、召回率(查全率)、F1)
  2. 对比分析

(1)五折交叉验证结果

准确率、精度、召回率和 F1 值均在 95% 左右,表明随机森林模型在训练数据的不同子集上具有稳定的表现。精度高于召回率,说明模型在预测时假阳性较少,但对正类样本的完全覆盖稍有不足。

(2)测试集结果

测试集上的性能指标略低于交叉验证结果,表明模型在训练数据上的表现稍好,可能存在一定的过拟合。测试集准确率和召回率为 90%,与交叉验证结果相差 5%,但仍在可接受范围内,说明模型具有较强的泛化能力。

(3)精度和召回率的差异

在五折交叉验证中,精度(96.51%)高于召回率(95.00%),表明模型更关注预测的准确性。测试集的精度(90.77%)和召回率(90.00%)相差不大,表明模型的分类策略较为均衡。

(4)模型泛化能力

随机森林的集成学习特性使其在训练集上表现优异,但测试集性能稍有下降,可能由于测试集样本分布与训练集存在差异。

总体来说,模型的性能指标均较高,证明随机森林适合用于多类分类问题,并具有较好的泛化能力。



posted on 2024-12-15 11:53  leapss  阅读(38)  评论(0)    收藏  举报