工作中要实际用起来随机森林,所以还是从决策树开始熟悉一下原理吧。
一,代码
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import numpy as np
from sympy.abc import alpha
from matplotlib.font_manager import FontProperties
# 设置字体为SimHei,如果你的系统中没有这个字体,可能需要更换为其他支持中文的字体
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['axes.unicode_minus'] = False # 正确显示负号
# 生成系统风格的数据, 确保所有特征值为正数
X, y = make_classification(n_samples=200, n_features=2, n_redundant=0, n_informative=2,
n_clusters_per_class=1, random_state=42)
X += np.abs(X.min()) # 平移数据确保为正
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建决策树模型,并设置最大深度为3
dt = DecisionTreeClassifier(max_depth=3)
# 训练模型
dt.fit(X_train, y_train)
# 绘制数据点和决策边界
def plot_decision_boundary(model, X, y):
# 设置最大值和最小值,以及增量
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.01),
np.arange(y_min, y_max, 0.01))
# 预测整个网络的值
Z = model.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
# 绘制决策边界
plt.contourf(xx, yy, Z, alpha=0.4)
# 绘制不同类别的样本点
plt.scatter(X[y==0][:, 0], X[y==0][:, 1], c='red', marker='x', label='普通人物')
plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], c='blue', marker='o', label='特殊人物')
plt.xlabel('外表')
plt.ylabel('心灵')
plt.title('人物分类图')
# 绘制决策边界和数据点
plot_decision_boundary(dt, X, y)
plt.savefig('aa.png')
二,输出
输出直接输出要报一个错,不能直接用plt.legent()显示,就用savefig暂时看看效果,生成一个图片文件。

aa.png