美文网首页机器学习
随机森林-Python

随机森林-Python

作者: 灵妍 | 来源:发表于2018-03-22 21:27 被阅读7次

这里随机森林分类器的预测可视化与决策树差不多,因为随机森林就是决策树投票得到的结果。
代码:

# Random Forest Classification

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

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

# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)

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

# Fitting Random Forest to the Training set
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0 )
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

# Visualising the Training set results
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(('orange', 'blue'))(i), label = j, s=15)
plt.title('Random Forest (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
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(('orange', 'blue'))(i), label = j, s=15)
plt.title('Random Forest (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

关键代码:
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
c = ListedColormap(('orange', 'blue'))(i), label = j, s=15)
这里的s参数是为了调节点的大小
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 10, criterion = 'entropy', random_state = 0 )
classifier.fit(X_train, y_train)
这里的第一个参数是为了确定随机森林中决策树的个数,划分标准选的是熵,也就是衡量结构是否规则的一个量。
运行结果:


混淆矩阵RF.PNG 测试集RF.PNG 训练集RF.PNG

在结果中可以看出过拟合还是很明显。

相关文章

  • 随机森林-Python

    这里随机森林分类器的预测可视化与决策树差不多,因为随机森林就是决策树投票得到的结果。代码: 关键代码:plt.sc...

  • 何为决策树和随机森林?

    随机森林 定义:随机森林或随机决策森林是用于分类、回归和其他任务的集成学习方法。 名字由来:随机森林就是使用随机的...

  • python实现随机森林算法

    用决策树实现一个根据用户的信息判断用户是否逾期的分类算法代码实现。 首先,我们对数据进行预处理,填充缺失值,数据集...

  • 随机森林算法入门(python)

    翻译自:http://blog.yhat.com/posts/python-random-forest.html ...

  • 集成学习之Bagging和RF

    一、什么是随机森林 二、随机森林的两个随机 三、随机森林算法过程 四、为什么如此受欢迎 五、随机森林算法的优缺点 ...

  • (十四、)极限森林

    一、极限森林 特征随机参数随机分裂随机因为分裂是随机的,所以就不需要样本是随机的了 随机森林和极限森林不同之处:随...

  • 2020-04-24

    达达算法面试:1、随机森林2、boosting和bagging区别3、衡量模型好坏的方法4、python yiel...

  • Python机器学习之随机森林

    引言  随机森林的原理网上有一大堆,作为入门小白,下面来根据教材敲两个随机森林的代码。随机森林有两个比较重要的参数...

  • 实战:用Python实现随机森林!

    因为有 Scikit-Learn 这样的库,现在用Python实现任何机器学习算法都非常容易。实际上,我们现在不需...

  • 实战:用Python实现随机森林

    摘要: 随机森林如何实现?为什么要用随机森林?看这篇足够了! 因为有Scikit-Learn这样的库,现在用Pyt...

网友评论

    本文标题:随机森林-Python

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