使用随机森林对鸢尾花进行分类

本文整理自《Python机器学习》

随机森林

随机森林可视为多棵决策树的集成,其算法可概括为四个简单的步骤:
1)使用bootstrap抽样方法随机选择n个样本进行训练(从训练集中随机可重复地选择n个样本);
2)使用第1)步选定的样本构造一棵决策树,节点划分规则如下:
(1)不重复地随机选择 d d d个特征;
(2)根据目标函数的要求,如最大化信息增益,使用选定的特征对节点进行划分。
3)重复上述过程1~2000次。
4)汇总每颗决策树的类标进行多数投票。
步骤2)与单棵决策树相比在对节点的最优划分的判定时,并未使用所有的特征,而是随机选择了一个子集。
随机森林并不具备决策树那样良好的可解释性,但其优势在于不用关心超参数,通常不需要对其进行剪枝。通常决策树的数量越多,随机森林整体的分类表现就越好。

使用sklearn中的随机森林对鸢尾花进行分类

在sklearn中一般 d = m d=\sqrt{m} d=m m m m是训练集中的特征总量。
代码如下:

from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
import numpy as np
from sklearn.ensemble import RandomForestClassifier


iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.3,random_state=0)

sc = StandardScaler()
sc.fit(X_train)
X_train_std = sc.transform(X_train)
X_test_std: object = sc.transform(X_test)


def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
    markers = ('s', 'x', 'o', '^', 'v')
    colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
    cmap = ListedColormap(colors[:len(np.unique(y))])
    x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
    x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
    xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
                           np.arange(x2_min, x2_max, resolution))
    Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
    Z = Z.reshape(xx1.shape)
    plt.contourf(xx1, xx2, Z, alpha=0.4, cmap=cmap)
    plt.xlim(xx1.min(), xx1.max())
    plt.ylim = (xx2.min(), xx2.max())
    X_test, y_test = X[test_idx, :], y[test_idx]
    for idx, cl in enumerate(np.unique(y)):
        plt.scatter(x=X[y == cl, 0], y=X[y == cl, 1], alpha=0.8, c=cmap(idx), marker=markers[idx], label=cl)
    if test_idx:
        X_test, y_test = X[test_idx, :], y[test_idx]
        plt.scatter(X_test[:, 0], X_test[:, 1], c='black', alpha=0.8, linewidths=1, marker='o', s=10, label='test set')

X_combined_std = np.vstack((X_train_std, X_test_std))
y_combined = np.hstack((y_train, y_test))
forest = RandomForestClassifier(criterion='entropy', n_estimators=10, random_state=1, n_jobs=2)
forest.fit(X_train_std, y_train)
plot_decision_regions(X_combined_std, y_combined, classifier=forest, test_idx=range(105,150))
plt.xlabel('petal length')
plt.ylabel('petal width')
plt.legend(loc='upper left')
plt.show()

分类结果如下:
使用随机森林对鸢尾花进行分类_第1张图片

你可能感兴趣的:(python机器学习,随机森林,分类,python)