引言
Matplotlib 是 Python 中一个功能强大的绘图库,它能够帮助我们轻松地将数据可视化。在机器学习中,随机森林是一种常用的集成学习方法,能够有效地处理各种复杂数据。本文将介绍如何使用 Matplotlib 绘制随机森林的图形,以便更好地理解数据分布和模型性能。
Matplotlib 简介
Matplotlib 是一个基于 NumPy 的 Python 2D 绘图库,它可以生成高质量的图形。它提供了一系列的绘图工具,包括直方图、散点图、条形图、饼图等。Matplotlib 适用于各种科学计算和数据分析任务。
随机森林简介
随机森林(Random Forest)是一种基于决策树的集成学习方法。它由多个决策树组成,每个决策树都是独立训练的。在预测时,随机森林通过投票或多数表决的方式得到最终结果。
绘制随机森林图形
准备数据
首先,我们需要准备一些数据。以下是一个简单的示例数据集,包含年龄、收入和职业三个特征,以及是否购买保险的目标变量。
import numpy as np
import pandas as pd
# 创建数据集
data = {
'Age': np.random.randint(18, 70, 100),
'Income': np.random.randint(20000, 100000, 100),
'Occupation': np.random.choice(['Teacher', 'Engineer', 'Doctor', 'Artist'], 100),
'Insurance': np.random.choice([0, 1], 100)
}
df = pd.DataFrame(data)
# 将职业转换为数值型
df['Occupation'] = pd.get_dummies(df['Occupation']).sum(axis=1)
训练随机森林模型
接下来,我们使用 scikit-learn 库中的 RandomForestClassifier 来训练随机森林模型。
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
# 划分特征和目标变量
X = df.drop('Insurance', axis=1)
y = df['Insurance']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 训练随机森林模型
rf = RandomForestClassifier(n_estimators=100, random_state=42)
rf.fit(X_train, y_train)
绘制随机森林图形
1. 随机森林特征重要性
我们可以使用 feature_importances_
属性来获取每个特征的重要性。
import matplotlib.pyplot as plt
# 获取特征重要性
importances = rf.feature_importances_
# 创建条形图
plt.bar(range(len(importances)), importances)
plt.xlabel('Features')
plt.ylabel('Importance')
plt.title('Feature Importance in Random Forest')
plt.show()
2. 随机森林决策树数量
我们可以通过调整 n_estimators
参数来控制随机森林中决策树的数量。
# 调整决策树数量
rf2 = RandomForestClassifier(n_estimators=200, random_state=42)
rf2.fit(X_train, y_train)
# 绘制学习曲线
plt.plot(range(1, 201), rf2.feature_importances_)
plt.xlabel('Number of Trees')
plt.ylabel('Importance')
plt.title('Feature Importance vs Number of Trees')
plt.show()
3. 随机森林预测结果
我们可以使用 predict
方法来预测测试集的结果,并使用 Matplotlib 绘制混淆矩阵。
from sklearn.metrics import confusion_matrix
import seaborn as sns
# 预测测试集结果
y_pred = rf.predict(X_test)
# 绘制混淆矩阵
cm = confusion_matrix(y_test, y_pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel('Predicted')
plt.ylabel('True')
plt.title('Confusion Matrix')
plt.show()
总结
本文介绍了如何使用 Matplotlib 绘制随机森林的图形。通过可视化特征重要性、决策树数量和预测结果,我们可以更好地理解数据分布和模型性能。Matplotlib 是一个功能强大的绘图库,可以帮助我们轻松地将数据可视化,从而更好地进行数据分析。