决策树与随机森林的sklearn实现(update on going)

本文介绍了如何利用sklearn库实现决策树和随机森林的分类。针对iris数据集,展示了决策树的分类过程,指出其无需数据预处理但可能过拟合的问题,可通过剪枝控制复杂度。接着,解释了随机森林的工作原理,即通过构建多棵树并用多数投票决定最终分类结果。
摘要由CSDN通过智能技术生成

决策树

对iris数据进行决策树分类,采用sklearn库实现。决策树算法不需要对原始数据进行归一化处理,缺点是容易陷入过拟合,此时可以通过剪枝来控制树的深度。

# Author: Daniel Geng
from sklearn import tree
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import numpy as np

X, y = load_iris(return_X_y=True)
sample = y.shape[0]
y = y.reshape(sample, 1)  # 原来y为一个向量,变为150行1列

# random the order and get 120 samples for training
C = np.concatenate((X, y), axis=1)  # 拼接为150行5列
np.random.shuffle(C)

# train
train_sample = 120
X_train = C[:train_sample, :4]
y_train = C[:train_sample, -1]
clf = tree.DecisionTreeClassifier()
clf = clf.fit(X_train, y_train)

# test
X_test = C[train_sample:, :4]
y_test = C[train_sample:, -1]
y_predict = clf.predict(X_test)
error = 0
error_position = []
for i in range(sample - train_sample):
    if y_predict[i] != y_test[i]:
        error += 1
        error_position.append(i)
accuracy = 1 - error / (sample - train_sample)
print('accuracy = ' + '%.2f%%' % (accuracy * 100))
print(error_position)

# plot
tree.plot_tree(clf, filled=True)
plt.show()

在这里插入图片描述

随机森林

随机生成多棵决策树,并随机抽取部分特征作为其中某一棵决策树的特征,最后汇总分类结果作为集成输出的分类结果。

# Author: Daniel Geng
from sklearn import tree
from sklearn import ensemble
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
import numpy as np

X, y = load_iris(return_X_y=True)
sample = y.shape[0]
y = y.reshape(sample, 1)  # 原来y为一个向量,变为150行1列

# random the order and get 120 samples for training
C = np.concatenate((X, y), axis=1)  # 拼接为150行5列
np.random.shuffle(C)

# train
train_sample = 120
X_train = C[:train_sample, :4]
y_train = C[:train_sample, -1]
clf = ensemble.RandomForestClassifier(n_estimators=10)
clf = clf.fit(X_train, y_train)

# test
X_test = C[train_sample:, :4]
y_test = C[train_sample:, -1]
y_predict = clf.predict(X_test)
error = 0A
error_position = []
for i in range(sample - train_sample):
    if y_predict[i] != y_test[i]:
        error += 1
        error_position.append(i)
accuracy = 1 - error / (sample - train_sample)
print('accuracy = ' + '%.2f%%' % (accuracy * 100))
print(error_position)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值