Python实现鸢尾花数据集分类问题——基于skearn的SVM
代码如下:
# !/usr/bin/env python
# encoding: utf-8
__author__ = 'Xiaolin Shen'
from sklearn import svm
import numpy as np
from sklearn import model_selection
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import colors
# 当使用numpy中的loadtxt函数导入该数据集时,假设数据类型dtype为浮点型,但是很明显数据集的第五列的数据类型是字符串并不是浮点型。
# 因此需要额外做一个工作,即通过loadtxt()函数中的converters参数将第五列通过转换函数映射成浮点类型的数据。
# 首先,我们要写出一个转换函数:
# 定义一个函数,将不同类别标签与数字相对应
def iris_type(s):
class_label={b'Iris-setosa':0,b'Iris-versicolor':1,b'Iris-virginica':2}
return class_label[s]
#(1)使用numpy中的loadtxt读入数据文件
filepath='IRIS_dataset.txt' # 数据文件路径
data=np.loadtxt(filepath,dtype=float,delimiter=',',converters={4:iris_type})
#以上4个参数中分别表示:
#filepath :文件路径。eg:C:/Dataset/iris.txt。
#dtype=float :数据类型。eg:float、str等。
#delimiter=',' :数据以什么分割符号分割。eg:‘,’。
#converters={4:iris_type} :对某一列数据(第四列)进行某种类型的转换,将数据列与转换函数进行映射的字典。eg:{1:fun},含义是将第2列对应转换函数进行转换。
# converters={4: iris_type}中“4”指的是第5列。
# print(data)
#读入结果示例为:
# [[ 5.1 3.5 1.4 0.2 0. ]
# [ 4.9 3. 1.4 0.2 0. ]
# [ 4.7 3.2 1.3 0.2 0. ]
# [ 4.6 3.1 1.5 0.2 0. ]
# [ 5. 3.6 1.4 0.2 0. ]]
#(2)将原始数据集划分成训练集和测试集
X ,y=np.split(data,(4,),axis=1) #np.split 按照列(axis=1)进行分割,从第四列开始往后的作为y 数据,之前的作为X 数据。函数 split(数据,分割位置,轴=1(水平分割) or 0(垂直分割))。
x=X[:,0:2] #在 X中取前两列作为特征(为了后期的可视化画图更加直观,故只取前两列特征值向量进行训练)
x_train,x_test,y_train,y_test=model_selection.train_test_split(x,y,random_state=1,test_size=0.3)
# 用train_test_split将数据随机分为训练集和