西瓜书《机器学习》课后答案——Chapter6_6.3

6.3 选择两个UCI数据集,分别用线性核和高斯核训练一个SVM,并与BP神经网络和C4.5决策树进行实验比较。
解答:
(1) 准备libsvm的训练数据与测试数据

从UCI网站上选择了Iris数据集,这个数据集总共分为3类,每类50个样本,每个实例有四个属性。数据保存在bezdekIris.txt文件中,举一个样本为例:

5.1,3.5,1.4,0.2,Iris-setosa

书中也没有介绍解决多分类问题的SVM,所以这里还是训练两分类SVM。我们取Iris数据集中的任意两类作为实验数据。其中每类各取40个组成训练集,剩下10个组成测试集。用下面的程序生成libsvm的格式化数据:

#-*- coding:gbk -*-
""" Author: Victoria Created on 2017.9.30 17:30 """
pos_train_num = 0
neg_train_num = 0
f1 = open("../../数据/bezdekIris.txt", "r")
f2 = open("iris_train.txt", "w")
f3 = open("iris_test.txt", "w")
for line in f1:
    x1, x2, x3, x4, cate = line.strip().split(",")
    if cate=="Iris-setosa":
        if neg_train_num<40:
            f2.write("{} 1:{} 2:{} 3:{} 4:{}\n".format(0, x1, x2, x3, x4))
            neg_train_num += 1
        else:
            f3.write("{} 1:{} 2:{} 3:{} 4:{}\n".format(0, x1, x2, x3, x4))
    if cate=="Iris-versicolor":
        if pos_train_num<40:
            f2.write("{} 1:{} 2:{} 3:{} 4:{}\n".format(1, x1, x2, x3, x4))
            pos_train_num += 1
        else:
            f3.write("{} 1:{} 2:{} 3:{} 4:{}\n".format(1, x1, x2, x3, x4))
f1.close()
f2.close()
f3.close()

生成iris_train.txt文件和iris_test.txt文件。每行格式如下:

0 1:5.1 2:3.5 3:1.4 4:0.2

(2) 线性核和高斯核训练SVM

  • 线性核
svm-train.exe -t 0 iris_train.txt

生成的模型文件iris_train.txt.model,内容为:

svm_type c_svc
kernel_type linear
nr_class 2
total_sv 3
rho -0.773825
label 0 1
nr_sv 2 1
SV
0.2183036649206431 1:5.1 2:3.3 3:1.7 4:0.5 
0.3411559349730912 1:4.8 2:3.4 3:1.9 4:0.2 
-0.5594595998937343 1:4.9 2:2.4 3:3.3 4:1 

用此模型预测测试样本:

svm-predict.exe iris_test.txt iris_train.txt.model iris_linear_output.txt

控制台输出:
这里写图片描述

预测结果文件iris_linear_output.txt中内容:

0
0
0
0
0
0
0
0
0
0
1
1
1
1
1
1
1
1
1
1
  • 高斯核
svm-train.exe -t 2 iris_train.txt

生成的模型文件iris_train.txt.model,内容为:

svm_type c_svc
kernel_type rbf
gamma 0.25
nr_class 2
total_sv 10
rho 0.0997241
label 0 1
nr_sv 4 6
SV
0.6743034684404644 1:4.4 2:2.9 3:1.4 4:0.2 
0.6100423642018977 1:5.7 2:4.4 3:1.5 4:0.4 
0.2228094943249861 1:5.1 2:3.3 3:1.7 4:0.5 
0.4350796021024235 1:4.8 2:3.4 3:1.9 4:0.2 
-0.5683231084316726 1:7 2:3.2 3:4.7 4:1.4 
-1 1:4.9 2:2.4 3:3.3 4:1 
-0.06214334604292869 1:5 2:2 3:3.5 4:1 
-0.09317591741687863 1:6.7 2:3 3:5 4:1.7 
-0.1391054651891705 1:5.7 2:2.6 3:3.5 4:1 
-0.07948709198912128 1:6 2:2.7 3:5.1 4:1.6 

高斯核训练的SVM有十个支持向量。

用此模型预测测试样例:

svm-predict.exe iris_test.txt iris_train.txt.model iris_rbf_output.txt

控制台输出准确率为:100%。

你可能感兴趣的:(机器学习)