《深入浅出Python机器学习》——随机森林

决策树很容易实现过拟合,随机森林(一种集合算法)可解决这个问题

jupyter实现

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
# 导入随机森林模型
from sklearn.ensemble import RandomForestClassifier
# 载入红酒数据集
from sklearn import datasets
# 导入数据集拆分工具
from sklearn.model_selection import train_test_split

wine = datasets.load_wine()

# 只选取数据集的前两个特征
X = wine.data[:,:2]
y = wine.target

# 将数据集拆分为训练集和测试集
X_train, X_test,y_train,y_test = train_test_split(X,y)

forest = RandomForestClassifier(n_estimators=6,random_state=3)
# 用模型拟合数据集
forest.fit(X_train,y_train)

# 定义图像中分区的颜色和散点的颜色
cmap_light = ListedColormap(['#FFAAAA','#AAFFAA','#AAAAFF'])
cmap_bold = ListedColormap(['#FF0000','#00FF00','#0000FF'])

# 分别用样本的两个特征值构建图像的横轴和纵轴
x_min, x_max = X_train[:,0].min()-1,X_train[:,0].max()+1
y_min, y_max = X_train[:,1].min()-1,X_train[:,1].max()+1

xx,yy = np.meshgrid(np.arange(x_min,x_max,.02),np.arange(y_min,y_max,.02))
Z = forest.predict(np.c_[xx.ravel(),yy.ravel()])

# 给每个分类中的样本分配不同的颜色
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx,yy,Z,cmap=cmap_light)

# 用散点把样本表示出来
plt.scatter(X[:,0],X[:,1],c=y,cmap=cmap_bold,edgecolor='k',s=20)
plt.xlim(xx.min(),xx.max())
plt.ylim(yy.min(),yy.max())
plt.title("Classifier:RandomForest")
plt.show()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值