热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

决策树分类鸢尾花数据demo

code:importnumpyasnpimportpandasaspdimportmatplotlib.pyplotaspltimportmatplotlib

code:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import pydotplus

if __name__ == "__main__":
   
	iris_feature_E = "sepal lenght", "sepal width", "petal length", "petal width"
	iris_feature = "the length of sepal", "the width of sepal", "the length of petal", "the width of petal"
	iris_class = "Iris-setosa", "Iris-versicolor", "Iris-virginica"
	
	data = pd.read_csv("iris.data", header=None)
	iris_types = data[4].unique()
	for i, type in enumerate(iris_types):
		data.set_value(data[4] == type, 4, i)
	x, y = np.split(data.values, (4,), axis=1)
	x_train, x_test, y_train, y_test = train_test_split(x, y, train_size=0.7, random_state=1)
	print(y_test)

	model = DecisionTreeClassifier(criterion='entropy', max_depth=6)
	model = model.fit(x_train, y_train)
	y_test_hat = model.predict(x_test)
	with open('iris.dot', 'w') as f:
		tree.export_graphviz(model, out_file=f)
	dot_data = tree.export_graphviz(model, out_file=None, feature_names=iris_feature_E, class_names=iris_class,
		filled=True, rounded=True, special_characters=True)
	graph = pydotplus.graph_from_dot_data(dot_data)
	graph.write_pdf('iris.pdf')
	f = open('iris.png', 'wb')
	f.write(graph.create_png())
	f.close()

	# 画图
	# 横纵各采样多少个值
	N, M = 50, 50
	# 第0列的范围
	x1_min, x1_max = x[:, 0].min(), x[:, 0].max()
	# 第1列的范围
	x2_min, x2_max = x[:, 1].min(), x[:, 1].max()
	t1 = np.linspace(x1_min, x1_max, N)
	t2 = np.linspace(x2_min, x2_max, M)
	# 生成网格采样点
	x1, x2 = np.meshgrid(t1, t2)
    # # 无意义,只是为了凑另外两个维度
    # # 打开该注释前,确保注释掉x = x[:, :2]
	x3 = np.ones(x1.size) * np.average(x[:, 2])
	x4 = np.ones(x1.size) * np.average(x[:, 3])
	# 测试点
	x_show = np.stack((x1.flat, x2.flat, x3, x4), axis=1)
	print("x_show_shape:\n", x_show.shape)

	cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF'])
	cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
	# 预测值
	y_show_hat = model.predict(x_show)
	print(y_show_hat.shape)
	print(y_show_hat)
	# 使之与输入的形状相同
	y_show_hat = y_show_hat.reshape(x1.shape)
	print(y_show_hat)
	plt.figure(figsize=(15, 15), facecolor='w')
	# 预测值的显示
	plt.pcolormesh(x1, x2, y_show_hat, cmap=cm_light)
	print(y_test)
	print(y_test.ravel())
	# 测试数据
	plt.scatter(x_test[:, 0], x_test[:, 1], c=np.squeeze(y_test), edgecolors='k', s=120, cmap=cm_dark, marker='*')
	# 全部数据
	plt.scatter(x[:, 0], x[:, 1], c=np.squeeze(y), edgecolors='k', s=40, cmap=cm_dark)
	plt.xlabel(iris_feature[0], fOntsize=15)
	plt.ylabel(iris_feature[1], fOntsize=15)
	plt.xlim(x1_min, x1_max)
	plt.ylim(x2_min, x2_max)
	plt.grid(True)
	plt.title('yuanwei flowers regressiong with DecisionTree', fOntsize=17)
	plt.show()

	# 训练集上的预测结果
	y_test = y_test.reshape(-1)
	print(y_test_hat)
	print(y_test)
	# True则预测正确,False则预测错误
	result = (y_test_hat == y_test)
	acc = np.mean(result)
	print('accuracy: %.2f%%' % (100 * acc))

    # 过拟合:错误率
	depth = np.arange(1, 15)
	err_list = []
	for d in depth:
		clf = DecisionTreeClassifier(criterion='entropy', max_depth=d)
		clf = clf.fit(x_train, y_train)
		# 测试数据
		y_test_hat = clf.predict(x_test)
		# True则预测正确,False则预测错误
		result = (y_test_hat == y_test)
		err = 1 - np.mean(result)
		err_list.append(err)
		print(d, 'error ratio: %.2f%%' % (100 * err))
	plt.figure(figsize=(15, 15), facecolor='w')
	plt.plot(depth, err_list, 'ro-', lw=2)
	plt.xlabel('DecisionTree Depth', fOntsize=15)
	plt.ylabel('error ratio', fOntsize=15)
	plt.title('DecisionTree Depth and Overfit', fOntsize=17)
	plt.grid(True)
	plt.show()

生成的图文件:



鸢尾花的数据特征一共有四种:花萼长度、花萼宽度,花瓣长度,花瓣宽度。然后再使用决策树两两特征进行分类:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from sklearn import tree
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
import pydotplus

if __name__ == "__main__":
   
	iris_feature_E = "sepal lenght", "sepal width", "petal length", "petal width"
	iris_feature = "the length of sepal", "the width of sepal", "the length of petal", "the width of petal"
	iris_class = "Iris-setosa", "Iris-versicolor", "Iris-virginica"
	
	data = pd.read_csv("iris.data", header=None)
	iris_types = data[4].unique()
	for i, type in enumerate(iris_types):
		data.set_value(data[4] == type, 4, i)
	x_train, y = np.split(data.values, (4,), axis=1)

	feature_pairs = [(0, 1), (0, 2), (0, 3), (1, 2), (1, 3), (2, 3)]
	plt.figure(figsize=(15, 15), facecolor='w')
	for i, pair in enumerate(feature_pairs):
		# 准备数据
		x = x_train[:, pair]
		# 决策树进行学习
		clf = DecisionTreeClassifier(criterion='entropy', min_samples_leaf=3)
		dt_clf = clf.fit(x, y)
		# 开始画图
		N, M = 500, 500
		# 第0列的范围
		x1_min, x1_max = x[:, 0].min(), x[:, 0].max()   
    	# 第1列的范围
		x2_min, x2_max = x[:, 1].min(), x[:, 1].max()   
		t1 = np.linspace(x1_min, x1_max, N)
		t2 = np.linspace(x2_min, x2_max, M)
    	# 生成网格采样点
		x1, x2 = np.meshgrid(t1, t2)           
    	# 测试点         
		x_test = np.stack((x1.flat, x2.flat), axis=1)
		# 在训练集上预测结果
		y_hat = dt_clf.predict(x)
		y = y.reshape(-1)
		# 统计预测正确的个数
		c = np.count_nonzero(y_hat == y)
		print("y_hat:\n", y_hat)
		print("y:\n", y)
		'''
		set1 = set(y_hat)
		set2 = set(y)
		print(list(set1 & set2))
		if y_hat.any() != y.any():
			print('predict:%.3f   real:%.3f' %(y_hat.all(), y.all()))
		'''
		# 打印相关信息
		print('features:\t', iris_feature[pair[0]], ' + ', iris_feature[pair[1]])
		print('the number of true prediction:', c)
		print('acc:%.2f%%' %(100 * float(c) / float(len(y))))

		# 画图显示
		cm_light = mpl.colors.ListedColormap(['#77E0A0', '#FF8080', '#A0A0FF'])
		cm_dark = mpl.colors.ListedColormap(['g', 'r', 'b'])
		# 预测值
		y_test_hat = dt_clf.predict(x_test)
		# reshape到和输入的x1相同格式
		y_test_hat = y_test_hat.reshape(x1.shape)
		plt.subplot(2, 3, i+1)
		plt.pcolormesh(x1, x2, y_test_hat, cmap=cm_light)
		plt.scatter(x[:, 0], x[:, 1], c=y, edgecolors='k', cmap=cm_dark)
		plt.xlabel(iris_feature[pair[0]], fOntsize=14)
		plt.ylabel(iris_feature[pair[1]], fOntsize=14)
		plt.xlim(x1_min, x1_max)
		plt.ylim(x2_min, x2_max)
		plt.grid()
	plt.suptitle('the result of yuanwei flowers in each two features with dcisiontree', fOntsize=20)
	plt.tight_layout(2)
	plt.subplots_adjust(top=0.92)
	plt.show()


显然第二种组合效果还可以的。

接着我们使用随机森林算法来分类看看效果:

只需要在上面的代码中修改:

# 决策树进行学习
clf = DecisionTreeRegressor(n_estimators=200, criterion='entropy', max_depth=6)

为:

# 决策树进行学习
clf = RandomForestClassifier(n_estimators=200, criterion='entropy', max_depth=6)

效果:


看得出来随机森林的分类要比决策树好,随机森林因为是根据多个决策树弱分类器联合成一个强分类器,所以其边界出呈现很多的锯齿,分类的准确度也提高很多,150个数据,最后只有一个分错。


推荐阅读
  • 开源Keras Faster RCNN模型介绍及代码结构解析
    本文介绍了开源Keras Faster RCNN模型的环境需求和代码结构,包括FasterRCNN源码解析、RPN与classifier定义、data_generators.py文件的功能以及损失计算。同时提供了该模型的开源地址和安装所需的库。 ... [详细]
  • sklearn数据集库中的常用数据集类型介绍
    本文介绍了sklearn数据集库中常用的数据集类型,包括玩具数据集和样本生成器。其中详细介绍了波士顿房价数据集,包含了波士顿506处房屋的13种不同特征以及房屋价格,适用于回归任务。 ... [详细]
  • 我用Tkinter制作了一个图形用户界面,有两个主按钮:“开始”和“停止”。请您就如何使用“停止”按钮终止“开始”按钮为以下代码调用的已运行功能提供建议 ... [详细]
  • 在本教程中,我们将看到如何使用FLASK制作第一个用于机器学习模型的RESTAPI。我们将从创建机器学习模型开始。然后,我们将看到使用Flask创建AP ... [详细]
  • 本文介绍了一个Java猜拳小游戏的代码,通过使用Scanner类获取用户输入的拳的数字,并随机生成计算机的拳,然后判断胜负。该游戏可以选择剪刀、石头、布三种拳,通过比较两者的拳来决定胜负。 ... [详细]
  • 怀疑是每次都在新建文件,具体代码如下 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 本文讨论了clone的fork与pthread_create创建线程的不同之处。进程是一个指令执行流及其执行环境,其执行环境是一个系统资源的集合。在调用系统调用fork创建一个进程时,子进程只是完全复制父进程的资源,这样得到的子进程独立于父进程,具有良好的并发性。但是二者之间的通讯需要通过专门的通讯机制,另外通过fork创建子进程系统开销很大。因此,在某些情况下,使用clone或pthread_create创建线程可能更加高效。 ... [详细]
  • 本文介绍了机器学习手册中关于日期和时区操作的重要性以及其在实际应用中的作用。文章以一个故事为背景,描述了学童们面对老先生的教导时的反应,以及上官如在这个过程中的表现。同时,文章也提到了顾慎为对上官如的恨意以及他们之间的矛盾源于早年的结局。最后,文章强调了日期和时区操作在机器学习中的重要性,并指出了其在实际应用中的作用和意义。 ... [详细]
  • 基于dlib的人脸68特征点提取(眨眼张嘴检测)python版本
    文章目录引言开发环境和库流程设计张嘴和闭眼的检测引言(1)利用Dlib官方训练好的模型“shape_predictor_68_face_landmarks.dat”进行68个点标定 ... [详细]
  • Python操作MySQL(pymysql模块)详解及示例代码
    本文介绍了使用Python操作MySQL数据库的方法,详细讲解了pymysql模块的安装和连接MySQL数据库的步骤,并提供了示例代码。内容涵盖了创建表、插入数据、查询数据等操作,帮助读者快速掌握Python操作MySQL的技巧。 ... [详细]
  • Python使用Pillow包生成验证码图片的方法
    本文介绍了使用Python中的Pillow包生成验证码图片的方法。通过随机生成数字和符号,并添加干扰象素,生成一幅验证码图片。需要配置好Python环境,并安装Pillow库。代码实现包括导入Pillow包和随机模块,定义随机生成字母、数字和字体颜色的函数。 ... [详细]
  • Python已成为全球最受欢迎的编程语言之一,然而Python程序的安全运行存在一定的风险。本文介绍了Python程序安全运行需要满足的三个条件,即系统路径上的每个条目都处于安全的位置、"主脚本"所在的目录始终位于系统路径中、若python命令使用-c和-m选项,调用程序的目录也必须是安全的。同时,文章还提出了一些预防措施,如避免将下载文件夹作为当前工作目录、使用pip所在路径而不是直接使用python命令等。对于初学Python的读者来说,这些内容将有所帮助。 ... [详细]
  • Python教学练习二Python1-12练习二一、判断季节用户输入月份,判断这个月是哪个季节?3,4,5月----春 ... [详细]
  • 本文介绍了协程的概念和意义,以及使用greenlet、yield、asyncio、async/await等技术实现协程编程的方法。同时还介绍了事件循环的作用和使用方法,以及如何使用await关键字和Task对象来实现异步编程。最后还提供了一些快速上手的示例代码。 ... [详细]
author-avatar
黑色鲜花_866
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有