四种方法实现鸢尾花
提示:在下机器学习小白,可能会有很多错误,这主要是老师布置的课堂作业,网上东拼西凑的,建议参考,如有不当,还请斧正,非常感谢。 好了,直接上代码。
1.使用K-Means算法实现鸢尾花分类
'''
date
:2020-10-03
author
:panajie
goal
:使用K
-Means算法实现鸢尾花分类
K
-Means算法:K
-Means算法,对于给定的样本集,
按照样本之间的距离大小,将样本集划分为K个簇。
让簇内的点尽量紧密的连在一起,而让簇间的距离尽量的大。
一般K的值可以自己设定。
'''
# step 1: 导入必要的包
import matplotlib
.pyplot as plt
import numpy as np
from sklearn
.cluster import KMeans
from sklearn import datasets
from sklearn
.cluster import KMeans
# step 2:加载数据集
# 鸢尾花的数据集可以直接从sklearn中获取
iris
= datasets
.load_iris()
X
= iris
.data
[:, :4] # 表示我们取特征空间中的
4个维度
# print(X.shape)
# step 3:K-Means聚类算法
estimator
= KMeans(n_clusters
=3) # 构造聚类器
estimator
.fit(X
) # 聚类
label_pred
= estimator
.labels_ # 获取聚类标签
# step4: 绘制k-means结果
x0
= X
[label_pred
== 0] # Iris
-setosa 山鸢尾花
x1
= X
[label_pred
== 1] # Iris
-versicolor 变色鸢尾
x2
= X
[label_pred
== 2] # Iris
-virginica 维吉尼亚鸢尾
plt
.scatter(x0
[:, 0], x0
[:, 1], c
="blue", marker
='x', label
='label0')
plt
.scatter(x1
[:, 0], x1
[:, 1], c
="green", marker
='*', label
='label1')
plt
.scatter(x2
[:, 0], x2
[:, 1], c
="red", marker
='+', label
='label2')
# 一下两行代码是为了能够在绘图时候能够显示中文
plt
.rcParams
['font.sans-serif']=['SimHei']
plt
.rcParams
['axes.unicode_minus']=False
plt
.title
('K-Means算法实现鸢尾花分类', color
='LimeGreen', fontsize
= 25)
plt
.xlabel('花萼长度', color
='OrangeRed', fontsize
=15)
plt
.ylabel('花萼宽度', color
='Fuchsia', fontsize
=15)
plt
.legend(loc
=2)
# 展示
plt
.show()
2.线性回归实现
'''
date
:2020-10-03
author
:panajie
goal
:使用线性回归方法实现鸢尾花分类
线性回归方法:
'''
# step 1:导入必要的包
from sklearn import datasets
from sklearn import model_selection
from sklearn import svm
from sklearn
.naive_bayes import GaussianNB
from sklearn
.cluster import KMeans
from sklearn
.linear_model import LinearRegression
import matplotlib
.pyplot as plt
# step2:加载数据
iris
= datasets
.load_iris() # 鸢尾花的数据集可以直接从sklearn中获取
# 获取花瓣的长和宽
x
= [n
[0] for n in iris
.data
]
y
= [n
[1] for n in iris
.data
]
import numpy as np #转换成数组
x
= np
.array(x
).reshape(len(x
),1)
y
= np
.array(y
).reshape(len(y
),1)
# step3 :导入Sklearn机器学习扩展包中线性回归模型,然后进行训练和预测
classifier
= LinearRegression()
# 开始训练
classifier
.fit(x
,y
)
# 预测
pre
= classifier
.predict(x
)
# step4 :绘图
plt
.scatter(x
,y
,s
=100)
plt
.plot(x
,pre
,"r-",linewidth
=4)
# 花萼的长宽
# 一下两行代码是为了能够在绘图时候能够显示中文
plt
.rcParams
['font.sans-serif']=['SimHei']
plt
.rcParams
['axes.unicode_minus']=False
plt
.title
('线性回归方法实现鸢尾花分类', color
='LimeGreen', fontsize
= 25)
plt
.xlabel('花萼长度', color
='OrangeRed', fontsize
=15)
plt
.ylabel('花萼宽度', color
='Fuchsia', fontsize
=15)
for idx
, m in
enumerate(x
):
plt
.plot([m
,m
],[y
[idx
],pre
[idx
]], 'g-')
# 展示
plt
.show()
3.SVM支持向量机:
'''
date
:2020-10-03
author
:拷贝于 百度paddlepaddle
goal
:使用支持向量机SVM实现鸢尾花分类
线性回归方法:
'''
# step 1:导入必要的包
import numpy as np
from matplotlib import colors
from sklearn import svm
from sklearn
.svm import SVC
from sklearn import model_selection
import matplotlib
.pyplot as plt
import matplotlib as mpl
# 将字串转为整型,便于数据加载
def
iris_type(s
):
it
= {b
'Iris-setosa':0, b
'Iris-versicolor':1, b
'Iris-virginica':2}
return it
[s
]
#加载数据
data_path
='iris.data' # 数据文件的路径
data
= np
.loadtxt(data_path
, # 数据文件路径
dtype
=float, # 数据类型
delimiter
=',', # 数据分隔符
converters
={4:iris_type
}) # 将第
5列使用函数iris_type进行转换
#print(data) # data为二维数组,data.shape=(150, 5)
#print(data.shape)
#数据分割
x
, y
= np
.split(data
, #要切分的数组
(4,), #沿轴切分的位置,第
5列开始往后为y
axis
=1) #代表纵向分割,按列分割
x
= x
[:, 0:2] #在X中我们取前两列作为特征,为了后面的可视化。x
[:,0:4]代表第一维
(行
)全取,第二维
(列
)取
0~2
#print(x)
x_train
,x_test
,y_train
,y_test
=model_selection
.train_test_split(x
, #所要划分的样本特征集
y
, #所要划分的样本结果
random_state
=1, #随机数种子
test_size
=0.3) #测试样本占比
#
**********************SVM分类器构建
*************************
def
classifier():
#clf = svm.SVC(C=0.8,kernel='rbf', gamma=50,decision_function_shape='ovr')
clf
= svm
.SVC(C
=0.5, #误差项惩罚系数
,默认值是
1
kernel
='linear', #线性核 kenrel
="rbf":高斯核
decision_function_shape
='ovr') #决策函数
return clf
#
2.定义模型:SVM模型定义
clf
= classifier()
#
***********************训练模型
*****************************
def
train(clf
,x_train
,y_train
):
clf
.fit(x_train
, #训练集特征向量
y_train
.ravel()) #训练集目标值
#
***********************训练模型
*****************************
def
train(clf
,x_train
,y_train
):
clf
.fit(x_train
, #训练集特征向量
y_train
.ravel()) #训练集目标值
#
3.训练SVM模型
train(clf
,x_train
,y_train
)
#
**************并判断a b是否相等,计算acc的均值
*************
def
show_accuracy(a
, b
, tip
):
acc
= a
.ravel() == b
.ravel()
print('%s Accuracy:%.3f' %(tip
, np
.mean(acc
)))
def
print_accuracy(clf
,x_train
,y_train
,x_test
,y_test
):
#分别打印训练集和测试集的准确率
score(x_train
,y_train
):表示输出x_train
,y_train在模型上的准确率
print('trianing prediction:%.3f' %(clf
.score(x_train
, y_train
)))
print('test data prediction:%.3f' %(clf
.score(x_test
, y_test
)))
#原始结果与预测结果进行对比
predict()表示对x_train样本进行预测,返回样本类别
show_accuracy(clf
.predict(x_train
), y_train
, 'traing data')
show_accuracy(clf
.predict(x_test
), y_test
, 'testing data')
#计算决策函数的值,表示x到各分割平面的距离
print('decision_function:\n', clf
.decision_function(x_train
))
#
4.模型评估
print_accuracy(clf
,x_train
,y_train
,x_test
,y_test
)
#
5.模型使用
def
draw(clf
, x
):
iris_feature
= 'sepal length', 'sepal width', 'petal lenght', 'petal width'
# 开始画图
x1_min
, x1_max
= x
[:, 0].min(), x
[:, 0].max() #第
0列的范围
x2_min
, x2_max
= x
[:, 1].min(), x
[:, 1].max() #第
1列的范围
x1
, x2
= np
.mgrid
[x1_min
:x1_max
:200j
, x2_min
:x2_max
:200j
] #生成网格采样点
grid_test
= np
.stack((x1
.flat
, x2
.flat
), axis
=1) #
stack():沿着新的轴加入一系列数组
print('grid_test:\n', grid_test
)
# 输出样本到决策面的距离
z
= clf
.decision_function(grid_test
)
print('the distance to decision plane:\n', z
)
grid_hat
= clf
.predict(grid_test
) # 预测分类值 得到【
0,0.。。。
2,2,2】
print('grid_hat:\n', grid_hat
)
grid_hat
= grid_hat
.reshape(x1
.shape
) # reshape grid_hat和x1形状一致
#若
3*3矩阵e,则e
.shape()为
3*3,表示
3行
3列
cm_light
= mpl
.colors
.ListedColormap(['#A0FFA0', '#FFA0A0', '#A0A0FF'])
cm_dark
= mpl
.colors
.ListedColormap(['g', 'b', 'r'])
plt
.pcolormesh(x1
, x2
, grid_hat
, cmap
=cm_light
) #
pcolormesh(x
,y
,z
,cmap
)这里参数代入
# x1,x2,grid_hat,cmap=cm_light绘制的是背景。
plt
.scatter(x
[:, 0], x
[:, 1], c
=np
.squeeze(y
), edgecolor
='k', s
=50, cmap
=cm_dark
) # 样本点
plt
.scatter(x_test
[:, 0], x_test
[:, 1], s
=120, facecolor
='none', zorder
=10) # 测试点
# plt.xlabel(iris_feature[0], fontsize=20)
# plt.ylabel(iris_feature[1], fontsize=20)
plt
.xlim(x1_min
, x1_max
)
plt
.ylim(x2_min
, x2_max
)
# plt.title('svm in iris data classification', fontsize=30)
# 一下两行代码是为了能够在绘图时候能够显示中文
plt
.rcParams
['font.sans-serif']=['SimHei']
plt
.rcParams
['axes.unicode_minus']=False
plt
.title
('SVM支持向量机实现鸢尾花分类', color
='LimeGreen', fontsize
= 25)
plt
.xlabel('花萼长度', color
='OrangeRed', fontsize
=15)
plt
.ylabel('花萼宽度', color
='Fuchsia', fontsize
=15)
plt
.grid()
plt
.show()
#
5.模型使用
draw(clf
,x
)
4.贝叶斯
'''
date
:2020-10-03
author
:来自于网友
goal
:使用贝叶斯算法实现鸢尾花分类
贝叶斯算法:一种分类方法
'''
# step 1: 导入必要的包
from sklearn
.naive_bayes import GaussianNB
import numpy as np
import pandas as pd
from pandas import Series
,DataFrame
import matplotlib
.pyplot as plt
from sklearn
.datasets import load_iris
from matplotlib
.colors import ListedColormap
# step 2:加载数据集
# 导入函数
muNB
= GaussianNB()
# 读取数据
iris
= load_iris()
# 取出数据中的data
data
= iris
.data
# 取出数据中的target
target
= iris
.target
# 取data中所有行前两列为训练数据
samples
= data
[:,:2]
# 训练数据
muNB
.fit(samples
,target
)
# 取出训练数据中第一列中的最大与最小值
xmin
,xmax
= samples
[:,0].min(),samples
[:,0].max()
# 取出训练数据中第二列中的最大与最小值
ymin
,ymax
= samples
[:,1].min(),samples
[:,1].max()
# 在最大与最小值的区间分成
300个数据
x
= np
.linspace(xmin
,xmax
,300)
y
= np
.linspace(ymin
,ymax
,300)
# 然后使这些数据组成一个平面
xx
,yy
= np
.meshgrid(x
,y
)
# 生成
90000个坐标点
X_test
= np
.c_
[xx
.ravel(),yy
.ravel()]
# 预测训练数据
y_
= muNB
.predict(X_test
)
# 导入三种不同的颜色
colormap
= ListedColormap(['#00aaff','#aa00ff','#ffaa00'])
# 生成三个不同颜色的模块,第一列为x轴坐标,第二列为y轴坐标,预测之后,不同的点分成不同的三类
plt
.scatter(X_test
[:,0],X_test
[:,1],c
=y_
)
# 生成训练数据生成的点的分布,c
=target意思是根据target的值,生成不同的颜色的点
plt
.scatter(samples
[:,0],samples
[:,1],c
=target
,cmap
=colormap
)
# 一起调用的话使两张图结合起来(可选择)
plt
.scatter(X_test
[:,0],X_test
[:,1],c
=y_
)
plt
.scatter(samples
[:,0],samples
[:,1],c
=target
,cmap
=colormap
)
# 一下两行代码是为了能够在绘图时候能够显示中文(可选择)
plt
.rcParams
['font.sans-serif']=['SimHei']
plt
.rcParams
['axes.unicode_minus']=False
plt
.title
('贝叶斯算法实现鸢尾花分类', color
='LimeGreen', fontsize
= 25)
plt
.xlabel('花萼长度', color
='OrangeRed', fontsize
=15)
plt
.ylabel('花萼宽度', color
='Fuchsia', fontsize
=15)
plt
.show()
总结:以上的很多东西来源于网络,在此表示对分享自己的学习经历的前辈表示由衷的感谢。很多东西其实自己也不太懂,不过也不妨碍自己可以去动手是实现一下,运行结果看起来还是很有意思的,建议大家在安装了相应的运行环境之后可以跑一下。