LIBSVM User Guide

Source: Internet
Author: User

LIBSVM User Guide

This article contains the following sections:

    1. Introduction to support vector machine--SVM
    2. Installation of LIBSVM
    3. Use of LIBSVM
    4. LIBSVM parameter Tuning
    5. Java version LIBSVM library function call

Introduction to SVM

We think you have the basics of data mining when you do the following.

SVM is a powerful data mining tool, which shows very good performance in the practical applications of text classification, handwritten character recognition, image classification, and biological sequence analysis. SVM is a supervised learning algorithm, and samples are provided in the form of attribute vectors, so the input space is a subset of Rn.

1, the goal of SVM is to find two spaces as large as possible boundary plane to separate the sample points to "minimize the generalization error", that is, the new sample points to classify the prediction, the probability of error is minimal. The points falling on the boundary plane are called support vectors. Vapnik proves that if a smaller set of support vectors can be found, it is guaranteed to be well-generalized----that is, the fewer the number of support vectors the better.

Data points are usually linearly non-linear in the input space, and we map it to the higher dimensional feature space, which is linearly divided----the mapping function here is called the kernel function. The hyper-plane of the feature space corresponds to a nonlinear separation surface of the input space and is therefore called a nonlinear separator.

The output of the SVM classifier is U=W*X-BW is the normal vector of the classification plane, x is the input vector, B is the constant, and U represents the classification. That is, the purpose of SVM is to calculate WB. Maximizing the margin (the distance between two classification planes) is equivalent to finding the following two optimization problems:

For nonlinear classifiers It is necessary to map X to the feature space, while considering the existence of errors (that is, some sample points cross the classification boundary), the optimization problem becomes:

The function that is mapped to the feature space from the input space is called the kernel function, and the default kernel function used in LIBSVM is the RBF (radial basis function radial basis functions)

As a result, there are two parameters that need to be specified by the user: Gamma. In fact, in LIBSVM, the user needs to give a gamma interval, LIBSVM uses the cross-validation cross-validation accuracy method to determine the best gamma for the classification effect.

Give an example of what is cross-validation, if the training sample set is split into three groups, and then take train model predict 3 to get the correct rate; Pick up 3 train predict 1, last 1, 3 train predict 2, and finally take the group C with the highest accuracy forecast. and Gamma.

Sometimes the number of samples belonging to different classifications is unbalanced, so it is suggested that the objective function (two optimizations) should be:

Allow user to specify weight value in LIBSVM

The simplest linear classifier is used for text categorization, because the input document vector matrix is highly sparse and can be thought of as no mapping to the feature space and linearly spaced in the input space, so that we do not need to use the kernel function----However, my practice proves that this conclusion is not always correct.

Installation of LIBSVM

    1. Linux Download tar.gz Package
    2. After extracting it, you can use the Java version directly.

However, the computer is required to have more than 1.5 versions of Java, and set the $classpath global variables.

Use of LIBSVM

We only talk about the use of Linux under the Java version, on some VMS, the Java version of the LIBSVM running speed can be approximated to the C + + version of the speed.

Cd/path/to/libsvm-3.1/java

Java-classpath Libsvm.jar Svm_scale <arguments>

Java-classpath Libsvm.jar Svm_train <arguments>

Java-classpath Libsvm.jar svm_predict <arguments>

Java-classpath Libsvm.jar Svm_toy

LIBSVM requires the processing of file data to meet the following format:

Rlabel1 index1:value1 index2:value2 ...

Rlabel2 index1:value1 index2:value2 ...

The following script is for the file format I used to convert to LIBSVM requirements, make a backup:

#!/usr/bin/perl$file ="/home/orisun/libsvm/testvec"; $file 2="/home/orisun/libsvm/testvec_svmfmt";#$file = "/home/orisun/libsvm/trainvec";#$file 2= "/home/orisun/libsvm/trainvec_svmfmt";Open Vfile,"$file"; open Ffile,"> $file 2"; while(<VFILE>) {chomp;my @cont=split; $no=$cont [0];my $rlable;#$rlable =int ($no%1000);if($no eq"C39") {$rlable=0;} elsif ($no eq"C31") {$rlable=1;} elsif ($no eq"C32") {$rlable=2;} elsif ($no eq"C38") {$rlable=3;} elsif ($no eq"C34") {$rlable=4;} elsif ($no eq"C19") {$rlable=5;}PrintFfile"$rlable \ t"; for($i =1; $i < @cont; $i + +){if($cont [$i]!=0) {PrintFfile"$i: $cont [$i]\t";}}PrintFfile"\ n";}

LIBSVM The default is float instead of double when storing data in storage. This is really a problem when your raw data accuracy requirements are high.

Rlabel represents the classification, as a number. Index starts incrementing, indicating the ordinal of the input vector, and value is the values on the corresponding dimension of the input vector, if value is not written. Here is an example file:

3.2 31.6

1.5 24.2 30.5

5.1 21.6 32.0

5.4

The Svm_scale is used to normalize (or scale) the input vectors by column.

Usage:svm-scale [Options] Data_filename

Options

-L lower:x Scaling lower limit (default-1)

-U upper:x Scaling Upper Limit (default + 1)

-Y Y_lower y_upper:y scaling limits (default:no y scaling)

-S Save_filename:save scaling parameters to Save_filename

-R restore_filename:restore Scaling parameters from Restore_filename

For example, I run: Java svm_scale-l 0-u 1-s range train > Train.scale the input file is train, the output file is Train.scale, the columns of the input vector are scaled to the range, the range file The relevant zoom information is saved in the

Train the original contents of the file:

1 1:0 2:0

1 1:3 2:4

1 1:5 2:9

1 1:12 2:1

1 1:8 2:7

0 1:9 2:8

0 1:6 2:12

0 1:10 2:8

0 1:8 2:5

0 1:14 2:8

The range file is automatically generated:

0.000000000000000 1.000000000000000

1 0.000000000000000 14.00000000000000

2 0.000000000000000 12.00000000000000

Train.scale files are automatically generated:

1.0

1.0 1:0.21428571428571427 2:0.3333333333333333

1.0 1:0.35714285714285715 2:0.75

1.0 1:0.8571428571428571 2:0.08333333333333333

1.0 1:0.5714285714285714 2:0.5833333333333334

0.0 1:0.6428571428571429 2:0.6666666666666666

0.0 1:0.42857142857142855 2:1

0.0 1:0.7142857142857143 2:0.6666666666666666

0.0 1:0.5714285714285714 2:0.4166666666666667

0.0 1:1 2:0.6666666666666666

Then I run: Java svm_scale-r range test > Test.scale means that reading the scaling information from the range file applies to the test file and outputs the Test.scale file.

After vector normalization we train the training samples to generate support vectors.

Run: Java svm_train-s 0-c 5-t 2-g 0.5-e 0.01 Train.scale

For text classification Svm_train, there are several options to use:

-S Svm_type:set type of SVM (default 0)

0--C-svc

-T kernel_type:set type of kernel function (default 2)

0--Linear:u ' *v

2--Radial basis function:exp (-gamma*|u-v|^2)

-G Gamma:set Gamma in kernel function (default 1/num_features) Num_features is the number of input vectors

-C Cost:set The parameter C of C-svc, Epsilon-svr, and Nu-svr (default 1)

-m Cachesize:set cache memory size in MB (default 100) How much RAM is used

-e Epsilon:set tolerance of termination criterion (default 0.001)

-H Shrinking:whether to use the shrinking heuristics, 0 or 1 (default 1)

-wi Weight:set The parameter C of Class I to weight*c, for c-svc (default 1) specifies for each class when the number of classes is unbalanced

-V N:n-fold Cross validation mode crossover verification is divided into how many groups

-q:quiet mode (no outputs)

The Train.scale.model file will be generated with the following content:

Svm_type c_svc

Kernel_type RBF

Gamma 0.5

Nr_class 2

TOTAL_SV 9

rho-0.5061570424019811

Label 1 0

NR_SV 4 5

2.7686973549711875 1:0.21428571428571427 2:0.3333333333333333

5.0 1:0.35714285714285715 2:0.75

5.0 1:0.8571428571428571 2:0.08333333333333333

5.0 1:0.5714285714285714 2:0.5833333333333334

-5.0 1:0.6428571428571429 2:0.6666666666666666

-2.4351637665059895 1:0.42857142857142855 2:1

-5.0 1:0.7142857142857143 2:0.6666666666666666

-5.0 1:0.5714285714285714 2:0.4166666666666667

-0.3335335884651968 1:1 2:0.6666666666666666

Nr_class represents several classes of training sample set, Rho is the constant term of the decision function NR_SV is the number of vectors falling on the boundary in each class, the following enumerates all the support vectors, each supporting vector preceded by a number, which represents what I am not clear now.

When train C-SVM, there will be output similar to the following:

Optimization finished, #iter = 219

Nu = 0.431030

obj = -100.877286, rho = 0.424632

NSV = NBSV = 107

Total NSV = 132

obj is the value of the optimization objective function for the SSVM problem. Rho is a constant item B in a decision function. NSV is the number of support vectors, NBSV is the number of bounding support vectors (i.e., alpha_i = C).

If the number of free support vectors is many, it is probably because of overfitting. If the attribute of the input data is distributed within a large range, it is best to scale.

Using the default kernel function RBF is better, if RBF is used with model selection, then there is no need to consider the linear kernel.

If the accuracy of the forecast is too low, how to improve it? Use the grid.py in the Python directory for model selection to find the better parameters.

grid.py is a parameter selection program for the C-SVM classification of RBF kernel functions . The user only needs to give a range of parameters, and grid.py uses a cross-validation method to calculate the accuracy of each parameter combination to find the best parameters.

Usage:grid.py [-log2c begin,end,step] [-log2g begin,end,step] [-V fold]

[-svmtrain Pathname] [-gnuplot Pathname] [-out Pathname] [-png Pathname]

[Additional parameters for Svm-train] DataSet

The program conducts v-fold cross validation using parameter C (and gamma) = 2^begin, 2^ (Begin+step), ..., 2^end.

First sudo apt-get install gnuplot

Then compile the C + + version of LIBSVM and generate the Svm-train binary executable file.

cd/path/to/libsvm-3.1

Make

For example, we all understand: Python grid.py-log2c-5,5,1-log2g-4,0,1-v 5-svmtrain/home/orisun/develop/libsvm-3.1/svm-train-m train Cev_svmfmt_part1

-M 500 is a parameter that can be used when using Svm_train.

Final output Two files: Dataset.png outlines the cross-validation accuracy, dataset.out the CV-precision values for each group of LOG2 (c) and log2 (gamma).

If the training time is too long, you may need to:

1. Specify a larger cache size. (-M)

2. Use a looser stopping tolerance. (-E)

When using a very big-e, you may need to check the-H 0 (no shrinking) Or-h 1 (shrinking) which is faster.

3. If the method above does not work, you need to crop the training set. Use the subset.py in the tools directory to randomly get a subset of the training set.

Usage:subset.py [Options] DataSet number [OUTPUT1] [Output2]

This script selects a subset of the given data set.

Options

-S Method:method of selection (default 0)

0--Stratified selection (classification only)

1--Random selection

Output1:the subset (optional)

Output2:the Rest of data (optional)

If OUTPUT1 is omitted, the subset would be a printed on the screen.

It is helpful to use shrinking when the number of iterations is high, and when a large-e is used, the number of iterations is reduced and it is better to turn shrinking off.

When a large-m is specified, Linux will report a "segment error", most likely a memory overflow. The maximum addressable memory for a 32-bit machine is 4G. At the same time the Linux system divides the user space according to 3:1: The kernel space, so the user space only has the maximum 3g, but can dynamically allocate the memory maximum only 2 G. When you use a-m close to 2G, the memory is exhausted.

Workaround:

1. Replace the 64-bit machine.

2. If your machine supports Intel's PAE (physical Address Extension), you can turn on the HIGHMEM64G option in the Linux kernel so that the partition of the kernel space and user space is 4g:4g.

3. Install "tub" software, it can eliminate dynamic allocation of memory only 2G limit. Tub can get http://www.bitwagon.com/tub.html here.

You can use the-q option if you do not want to see intermediate output during the Svm_train process.

If you are using the LIBSVM library in your programming code, you can:

1. Declare an empty output function: void print_null (const char *s) {}

2. Assign it to the output function in the LIBSVM library: svm_print_string = &print_null;

When dealing with a multi-class classification problem, LIBSVM uses one-against-one instead of one-against-the rest, which in fact performs better and uses the former only because it is fast.

Cross-validation is to select better parameters and after cross-validation does not output the model file, you need to re-train the whole data without the-v option.

If you have a multi-core/shared memory computer, LIBSVM also allows you to use OpenMP for parallel programming.

It takes longer to turn on-b when predicting, and there is no absolute relationship between opening B and improving the accuracy of the predictions.

Finally, you can predict the classification, run: Java svm_predict test.scale Train.scale.model result

Test.scale is a file to be predicted, Train.scale.model is a model file generated using the training text set, resulting in a result file, which reads as follows:

1.0

1.0

0.0

1.0

0.0

0.0

0.0

0.0

1.0

0.0

Because I have marked the correct rlable in Test.scale, Svm_predict will also report the correct rate accuracy = 70.0% (7/10). In the actual classification problem, of course, we can not know in advance the Rlabel in the classification file, you could tag a number arbitrarily, this time will also give accuracy, but it is meaningless.

Only 3 colors are supported when using Svm_toy, and the maximum number of clusters is 3. If you want to have more classifications, you need to modify the original code svm-toy.cpp. If the load data is directly from the file, the request vector is 2-dimensional, and each dimension is in (0,1), while the Rlabel can only be 1, 2, 3 (not even 1.0, 2.0, 3.0).

Here is one using Svn_toy:

LIBSVM the call of the library function

The library function is in the "LIBSVM" package.

In the Java version, the following functions can be called:

public class SVM {

public static final int libsvm_version=310;

public static Svm_model Svm_train (Svm_problem prob, svm_parameter param);

public static void Svm_cross_validation (Svm_problem prob, svm_parameter param, int nr_fold, double[] target);

public static int Svm_get_svm_type (Svm_model model);

public static int Svm_get_nr_class (Svm_model model);

public static void Svm_get_labels (Svm_model model, int[] label);

public static double svm_get_svr_probability (Svm_model model);

public static double Svm_predict_values (Svm_model model, svm_node[] x, double[] dec_values);

public static double svm_predict (Svm_model model, svm_node[] x);

public static double svm_predict_probability (Svm_model model, svm_node[] x, double[] prob_estimates);

public static void Svm_save_model (String model_file_name, Svm_model model) throws IOException

public static Svm_model Svm_load_model (String model_file_name) throws IOException

public static String Svm_check_parameter (Svm_problem prob, svm_parameter param);

public static int Svm_check_probability_model (Svm_model model);

public static void Svm_set_print_string_function (Svm_print_interface print_func);

Note The index of the last element of svm_node[] in the Java version is not-1.

Users can customize their own output format by:

Your_print_func = new Svm_print_interface ()

public void print (String s)

Your own format

Svm.svm_set_print_string_function (Your_print_func);

LIBSVM User Guide

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.