Using libsvm - part[1]

Purpose

libsvm is a tool collection for SVM (Support Vector Machines) related topics created by Chih-Jen Lin, NTU.

Currently, version 3.22 provides multiple interfaces for Matlab/octave/python and more. I will try to introduce the usage of this powerful toolbox in a pratical way.

SVM - Support Vector Machnes

  • It is very hard to explain this concept without massive math or numerical procedures, refer to Original paper of libsvm by Chih-Jen Lin if you want to know more then how to use.

  • The idea behind SVMs is to make the original problem linearly separable by applying an non-linear mapping function. The SVM then automatically discovers the optimal separating hyperplane, which indicates we can predict future data sets by comparing with this hyperplane. So, SVM is a tool for CLASSIFICATION and PREDICTION under the hood whose accuracy is determined by the selection of the mapping method.

  • Basic steps for a SVM procedure:

      1. Select a training set of instance-label pairs: P[i]=(x[i],y[i]) where x[i] holds quantitive properties of P[i] and y[i] is a binary label for P[i] which indicates y[i] can only be 1 or 0;
      1. Select a mapping function framework for target SVM, then its parameters will be given by solving an equivalent optimization problem;
      1. Select the hyperplane in mapped space to represent the margin of two values of y;
      1. Classify y[j] for P[j] from test set by applying mapping function to P[j] and comparing relative position with the selected hyperplane in step 3.

Using libsvm package to solve problem

Install libsvm package

    1. Download libsvm package from Download SECTION on its homepage;
    1. Untar/unzip the tarball/zip file to obtain the source code;
    1. Check all Makefiles inside the packages, if you are not familiar with make, treat the Makefiles as the method lists for converting the source code into binary;
    1. Make it directly if you just need to use these tools in command line or make it inside subdirs to support other methods like python;
    • 4.1. If you are blocked by "make: g++: Command not found", just install "gcc-c++" package (Fedora) or other C++ compilers.
        # An installation example on FC rawhide
        [chunwang@localhost matlab]$ uname -r 
        4.11.0-0.rc7.git3.1.fc27.x86_64
    
        # Download packages
        [chunwang@localhost libsvm]$ export LIBSVM_URL="http://www.csie.ntu.edu.tw/~cjlin/cgi-bin/libsvm.cgi?+http://www.csie.ntu.edu.tw/~cjlin/libsvm+tar.gz"
        [chunwang@localhost libsvm]$ wget $LIBSVM_URL -O libsvm.tar.gz 2>&1 &>/dev/null; echo $?
        0
    
        # Untar to obtain source code
        [chunwang@localhost libsvm]$ (tar -xvf ./libsvm.tar.gz && rm -f libsvm.tar.gz) 2>&1 &>/dev/null; echo $?
        0
    
        # Check and Make
        [chunwang@localhost libsvm]$ cd libsvm-3.22/
        [chunwang@localhost libsvm-3.22]$ find . -name Makefile
        ./java/Makefile
        ./svm-toy/qt/Makefile
        ./svm-toy/gtk/Makefile
        ./python/Makefile
        ./matlab/Makefile
        ./Makefile
        [chunwang@localhost libsvm-3.22]$ cat ./Makefile|grep all:
        all: svm-train svm-predict svm-scale
        [chunwang@localhost libsvm-3.22]$ rpm -q gcc-c++ || sudo yum install -y gcc-c++
        gcc-c++-7.0.1-0.16.fc27.x86_64
    
        #- Make binary directly
        [chunwang@localhost libsvm-3.22]$ make all &>/dev/null; echo $?
        0
        #- Make for python
        [chunwang@localhost libsvm-3.22]$ cd python/; make &>/dev/null; echo $?; cd ~-
        0
        #- Make for octave
        [chunwang@localhost libsvm-3.22]$ cd matlab/
        [chunwang@localhost matlab]$ octave --eval "make octave" &>/dev/null; echo $?; cd ~-
        0
    

Using libsvm to analysis

    1. Convert data into libsvm input data form;
    • By reading example file integrated into libsvm package, the form is very easy to parse:
        [chunwang@localhost libsvm-3.22]$ cat ./heart_scale | head -1 
        +1 1:0.708333 2:1 3:1 4:-0.320755 5:-0.105023 6:-1 7:1 8:-0.419847 9:-1 10:-0.225806 12:1 13:-1
    
        # Line[i] == "y[i] j:x[i][j] ..." where y[i] is +1/-1 and j is a static int
        # An convert example using AWK
        [chunwang@localhost libsvm-3.22]$ echo 32,-2,+1 | awk -F"," '{print $NF" 1:"$1" 2:"$2}'
        +1 1:32 2:-2
    
    1. Train a model using processed data input file and obtain result (Using heart_scale as an example, select first 200 lines as training set).
    • Refer to Graphic Interface Section of libsvm homepage to obtain more information for the parameters of svm-train
    • A very simple example using default model (Using binary directly):
        # Turn original data file into 2 target sets
        [chunwang@localhost libsvm-3.22]$ head -200 ./heart_scale > ./heart_scale_train
        [chunwang@localhost libsvm-3.22]$ tail -70 ./heart_scale > ./heart_scale_test
    
        # Train the model by optimization
        [chunwang@localhost libsvm-3.22]$ ./svm-train heart_scale_train 
        *
        optimization finished, #iter = 147
        nu = 0.453249
        obj = -75.742327, rho = 0.439634
        nSV = 105, nBSV = 78
        Total nSV = 105
    
        # Predict and store result into target output file
        [chunwang@localhost libsvm-3.22]$ ./svm-predict heart_scale_test heart_scale_train.model heart_scale_test_output
        Accuracy = 81.4286% (57/70) (classification)
    
        # All test results will be stored in this output file, each line represents the result y[i] for Line[i] == "y[i] j:x[i][j] in test set
        [chunwang@localhost libsvm-3.22]$ cat ./heart_scale_test_output | sort | uniq
        1
        -1
    
        # Some Concepts in svm-train output:
        iter     : Iterations times
        nu       : Kernel function parameter
        obj      : Optimal objective value of the target SVM problem
        nSV      : Number of support vectors
        nBSV     : Number of bounded support vectors
        Accuracy = Correctly predicted data / Ttotal testing data × 100%
    
    • Equivalent processes with python or octave
       # python
    
       [chunwang@localhost python]$ cat ./test.py
       from svmutil import *
    
       y, x = svm_read_problem('../heart_scale')
       model = svm_train(y[:200], x[:200])
       p_label, p_acc, p_val = svm_predict(y[200:], x[200:], model)
    
       --------------------------------------------------------------
    
       # octave
    
       # Matlab or Octave change the input format of the x[i] and y[i] into matrix, so the input procedure is different
       >> [label, data] = libsvmread("../heart_scale")    # Read from data file using libsvmread
       >> model = svmtrain(label(1:200,:), data(1:200,:)) # Generate target SVM model
    
       >> svmpredict(label(201:270,:), data(201:270,:), model)     # Predict with test set and SVM model
       Accuracy = 81.4286% (57/70) (classification)
       ans =
    
          1
       ...
    

Useful materials

  • [Google Scholar] Chih-Jen Lin - Link
  • [Quora] How to use libsvm in Matlab? - Link
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,233评论 6 495
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,357评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,831评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,313评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,417评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,470评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,482评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,265评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,708评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,997评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,176评论 1 342
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,827评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,503评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,150评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,391评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,034评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,063评论 2 352

推荐阅读更多精彩内容

  • 王铎者,明未清初著名书法家,精擅草书。然而作为一代宗师,在临怀素帖尾却留下了这样一句话:怀素独此帖可观,他书...
    惠明坊阅读 601评论 0 2
  • 一步上路,十方相助,万籁合心,如何相度? 原创作品 (Original Article)
    一诗一境界阅读 110评论 0 0
  • 无欲不是一种训诫,而是一种完美自足的呈现状态。独立于世间纯粹的体验,无欲的作为即是无为。因为本就是完美,未曾不足。...
    氵汝阅读 474评论 0 0
  • 在永无止境的黑夜里 有人脚上套着金色铃铛 清脆魅惑的声音 是灰暗世界的乐曲 那在风里摇曳的身姿 迈着缓慢而又轻佻的...
    尘致迢迢阅读 571评论 1 4