codecamp

AI人工智能 随机森林分类器

随机森林是集成学习算法,由多个决策树组成,通过平均多个决策树的结果,在保留预测能力的同时降低过拟合风险。本文使用乳腺癌数据集实现。

1. 实现步骤

步骤1:导入库

from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
import matplotlib.pyplot as plt
import numpy as np

步骤2:加载数据集并划分

## 加载乳腺癌数据集
cancer = load_breast_cancer()
## 划分训练集与测试集
X_train, X_test, y_train, y_test = train_test_split(
    cancer.data, cancer.target, random_state=0
)

步骤3:构建并训练随机森林

## 初始化随机森林(n_estimators=决策树数量,random_state=随机种子)
forest = RandomForestClassifier(n_estimators=50, random_state=0)
## 训练模型
forest.fit(X_train, y_train)

步骤4:模型准确率评估

## 计算训练集准确率
print('训练集准确率:{:.3f}'.format(forest.score(X_train, y_train)))  # 输出:1.000(全对)
## 计算测试集准确率
print('测试集准确率:{:.3f}'.format(forest.score(X_test, y_test)))    # 输出:0.965(约96.5%)

说明:增加决策树数量(n_estimators)通常可提升测试集准确率。

步骤5:特征重要性可视化

随机森林可输出每个特征对预测的贡献度,帮助识别关键特征:

## 特征数量
n_features = cancer.data.shape[1]
## 绘制水平条形图
plt.barh(range(n_features), forest.feature_importances_, align='center')
## 设置y轴标签(特征名)
plt.yticks(np.arange(n_features), cancer.feature_names)
## 设置坐标轴标题
plt.xlabel('Feature Importance(特征重要性)')
plt.ylabel('Feature(特征)')
plt.show()

可视化结果:最差半径(worst radius)、最差面积(worst area)、最差分形维数(worst fractal dimension)等特征的重要性最高。

AI人工智能 决策树分类器
AI人工智能 分类器的性能评估
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

AI人工智能监督学习(回归)

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }