美文网首页随机森林
Random Forests|python

Random Forests|python

作者: 何同尘 | 来源:发表于2018-12-27 19:08 被阅读10次

随机森林算法是一个监督算法用来分类和做回归。

原理

随机森林通过建立多颗决策树,合并他们的结果来得到一个更精确更稳定的预测值。
随机森林算法是一个集成算法。
集成学习模型聚合多个机器学习模型,从而实现整体更好的性能。

这背后的逻辑是,所使用的每个模型在自己使用时都很弱,但在集合中使用时很强。在随机森林的情况下,使用大量作为“弱”因子的决策树,并且它们的输出被聚合,结果表示“强”集合。

怎样使用

随机森林算法有两个步骤:
第一步是创建随机森林
第二步是通过第一步创建的森林进行回归和分类预测。

创建:

每个棵树都是这样产生的:
1.如果训练集中的样本数为N,则从原始数据中随机抽样N个案例但需要替换。此样本将是用于生成树的训练集。
2.如果有M个输入变量,则指定一个数字,使得在每个节点处,从M中随机选择m个变量,并且使用该m的最佳分割来分割节点

预测:

预测需要以下步骤:
1.获取测试特征并使用每个随机创建的决策树的规则来预测结果并存储预测结果(目标)
2.计算每个预测目标的投票
3.将高投票预测目标视为随机森林算法的最终预测
分类

实施

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values
y = dataset.iloc[:, 4].values

from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

from sklearn.preprocessing import StandardScaler
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0)
classifier.fit(X_train, y_train)

y_pred = classifier.predict(X_test)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

from matplotlib.colors import ListedColormap
X_set, y_set = X_train, y_train
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Random Forest Classification (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

from matplotlib.colors import ListedColormap
X_set, y_set = X_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('red', 'green'))(i), label = j)
plt.title('Random Forest Classification (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()
训练结果 预测结果

相关文章

  • Random Forests|python

    随机森林算法是一个监督算法用来分类和做回归。 原理 随机森林通过建立多颗决策树,合并他们的结果来得到一个更精确更稳...

  • 6. Random Forest 随机森林

    Random forests,又叫random decision forests,它是一个包含多个决策树的分类器,...

  • Kaggle|Exercise4:Random Forests

    来自kaggle官网的标准化机器学习流程。 Recap Here's the code you've writte...

  • 随机数

    random python自带random模块,用于生成随机数。Python标准库中的[random模块],可以生...

  • python random模块

    一、python标准库中的random模块常用的方法 random.random random.random()用...

  • random

    python模块之random 1、random python中的random模块用于生成随机数。下面介绍常用的一...

  • Python-生成随机数的方法

    一、Python自带的random模块 1.1 生成随机整数、浮点数 random.random random.u...

  • Python常见面试题(二)

    python生成随机函数 random模块 random.random()随机生成0-1之间的数字 random....

  • Python 随机数

    要入Python门,先读廖雪峰。 ▍random.random() random.random()用于生成一个0到...

  • python随手记(5)random模块常用函数

    Python中的random模块主要函数分析 1、 浮点数相关random random.random()几乎所有...

网友评论

    本文标题:Random Forests|python

    本文链接:https://www.haomeiwen.com/subject/gkydlqtx.html