这道题由于需要安装libsvm,而在matlab上安装libsvm的过程相当麻烦,所以,网上没有提供它的matlab代码的答案,只有Python的代码,下面是我参考Python代码做的matlab代码☺️
matlab代码如下:
clear all; clc; [y,x] = libsvmread('train.txt'); [y1,x1] = libsvmread('test.txt'); model1 = svmtrain(y,x,'-t 0'); model2 = svmtrain(y,x,'-t 2');
[label1, acc1, val1] = svmpredict(y1,x1,model1); [label2, acc2, val2] = svmpredict(y1,x1,model2);
将题目中的西瓜数据分为测试数据和训练数据,分别保存为test.txt和train.txt的文件中(两个文件中的数据可以自行随机选择)
#test.txt
1 1:0.774 2:0.376 1 1:0.608 2:0.318 1 1:0.556 2:0.215 1 1:0.481 2:0.149 -1 1:0.666 2:0.091 -1 1:0.245 2:0.057 -1 1:0.639 2:0.161 -1 1:0.36 2:0.37 -1 1:0.719 2:0.103
#train.txt
1 1:0.697 2:0.46 1 1:0.634 2:0.264 1 1:0.403 2:0.237 1 1:0.437 2:0.211 -1 1:0.243 2:0.267 -1 1:0.343 2:0.099 -1 1:0.657 2:0.198 -1 1:0.593 2:0.042
运行结果:
* optimization finished, #iter = 4 nu = 1.000000 obj = -7.783710, rho = 0.332397 nSV = 8, nBSV = 8 Total nSV = 8 * optimization finished, #iter = 4 nu = 1.000000 obj = -7.795628, rho = 0.057934 nSV = 8, nBSV = 8 Total nSV = 8 Accuracy = 77.7778% (7/9) (classification)
Accuracy = 77.7778% (7/9) (classification)
从运行结果来看,用线性核和高斯核做出来的效果完全一样,没有差别