集成学习(二)—— 随机森林

随机森林

简介

随机森林就是 决策树+bagging+随机属性。

就是说在决策树的基础上,使用bagging搞了多个模型最后投票决定分类。另外不同数据集之间的属性也可能是不一样的,因为不仅是样本随机选,属性也是随机选的,可能在这个数据集里样本有abc三个属性,到了另一个数据集里就是def三个属性了。

大概就是这样吧,也没啥好说的。

sklearn实现随机森林

import numpy as np
import matplotlib.pyplot as plt
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

# 载入数据
data = np.genfromtxt('../data/LR-testSet2.txt',delimiter=',')
xdata = data[:,:-1]
ydata = data[:,-1]

# 切分训练集测试集
xtrain,xtest,ytrain,ytest = train_test_split(xdata,ydata,test_size=0.5)

# 画图函数
def plot(model):
    xmin,xmax = xdata[:,0].min()-1,xdata[:,0].max()+1
    ymin,ymax = xdata[:,1].min()-1,xdata[:,1].max()+1
    xx,yy = np.meshgrid(np.arange(xmin,xmax,0.02),
                        np.arange(ymin,ymax,0.02))
    z = model.predict(np.c_[xx.ravel(),yy.ravel()])
    z = z.reshape(xx.shape)
    cs = plt.contourf(xx,yy,z)
    plt.scatter(xtest[:,0],xtest[:,1],c=ytest)
    plt.show()
    
RF = RandomForestClassifier(n_estimators=50)
RF.fit(xtrain,ytrain)
plot(RF)

rf

发布了77 篇原创文章 · 获赞 1 · 访问量 2082

猜你喜欢

转载自blog.csdn.net/Paul_1i/article/details/104349196
今日推荐