西瓜书6.2 使用libsvm

试使用LIBSVM,在西瓜数据集上分别用线性核和高斯核训练svm,并比较支持向量的差别

  1. 导入依赖
<dependencies>
        <dependency>
            <groupId>tw.edu.ntu.csie</groupId>
            <artifactId>libsvm</artifactId>
            <version>3.17</version>
        </dependency>
</dependencies>
  1. 将svm_predict,svm_train放入工程中

image-20201217105521534

  1. 调用代码

    package com.fly.svm;
    
    import java.io.IOException;
    import java.net.URL;
    
    
    
    public class Main {
        public static void main(String[] args) throws IOException {
            URL resource = Main.class.getClassLoader().getResource("");
            String url = resource.toString().substring(5);
            String testFile=url+"test.txt";
            String trainFile=url+"train.txt";
            String linerModel=url+"liner_model.txt";
            String gaussModel=url+"gauss_model.txt";
            String lineOut=url+"line_out.txt";
            String gaussOut=url+"gauss_out.txt";
            String[] arg1 = { "-t","0","-c","10000",trainFile,linerModel };
            String[] arg2={"-t","2","-c","10000",trainFile,gaussModel};
            String[] parg1 = { testFile, linerModel, lineOut};
            String[] parg2 = { testFile, gaussModel, gaussOut};
            // 创建训练对象
            svm_train t = new svm_train();
            svm_train t2=new svm_train();
            // 创建预测对象
            svm_predict p = new svm_predict();
            svm_predict p2=new svm_predict();
            //调用
            //线性核
            System.out.println("线性核");
            t.main(arg1);
            p.main(parg1);
    
            //高斯核
            System.out.println("高斯核");
            t2.main(arg2);
            p2.main(parg2);
    
        }
    }
    
    

    其中test.txt

    1 1:.774 2:.376
    1 1:.608 2:.318
    1 1:.403 2:.237
    1 1:.437 2:.211
    -1 1:.243 2:.267
    -1 1:.343 2:.099
    -1 1:.657 2:.198
    -1 1:.593 2:.042
    1 1:.697 2:.46
    1 1:.634 2:.264
    1 1:.556 2:.215
    1 1:.481 2:.149
    -1 1:.666 2:.091
    -1 1:.245 2:.057
    -1 1:.639 2:.161
    -1 1:.36 2:.37
    -1 1:.719 2:.103
    

    train.txt

    1 1:.774 2:.376
    1 1:.608 2:.318
    1 1:.403 2:.237
    1 1:.437 2:.211
    -1 1:.243 2:.267
    -1 1:.343 2:.099
    -1 1:.657 2:.198
    -1 1:.593 2:.042
    1 1:.697 2:.46
    1 1:.634 2:.264
    1 1:.556 2:.215
    1 1:.481 2:.149
    -1 1:.666 2:.091
    -1 1:.245 2:.057
    -1 1:.639 2:.161
    -1 1:.36 2:.37
    -1 1:.719 2:.103
    
  2. 结果分析

    惩罚系数C较低时高斯核与线性核准确率一致,当惩罚系数较高时高斯核明显优于线性核

    C=1时

    img

    C=100时

    img

    C=10000时

    img

posted on 2020-12-17 11:02  计网好难  阅读(449)  评论(0)    收藏  举报