原文自:http://www.csie.ntu.edu.tw/~cjlin/libsvm/faq.html#faq101
起因是不知道SVC和nu-SVC的区别,原本想瞎猜,幸好瞎猜之前搜了一下,找到了这个。
LIBSVMFAQ
last modified : Sun, 7 Apr 2013 07:16:13 GMTQ: Some courses which have used libsvm as atool
[GoTop]
Q: Some applications/tools which have usedlibsvm
(and maybe liblinear).
[GoTop]
Q: Where can I find documents/videos of libsvm?
[GoTop]
Q: Where are change log and earlierversions?
See thechange log.
You can download earlier versions here.
[GoTop]
Q: How to cite LIBSVM?
Please cite the following paper:
Chih-Chung Chang and Chih-Jen Lin, LIBSVM : a library forsupport vector machines. ACM Transactions on Intelligent Systemsand Technology, 2:27:1--27:27, 2011. Software available athttp://www.csie.ntu.edu.tw/~cjlin/libsvm
The bibtex format is
@article{CC01a, author = {Chang, Chih-Chung and Lin, Chih-Jen}, title = {{LIBSVM}: A library for support vector machines}, journal = {ACM Transactions on Intelligent Systems and Technology}, volume = {2}, issue = {3}, year = {2011}, pages = {27:1--27:27}, note = {Software available at url{http://www.csie.ntu.edu.tw/~cjlin/libsvm}}}
[GoTop]
Q: I would like to use libsvm in my software.Is there any license problem?
The libsvm license ("the modified BSD license") is compatiblewith many free software licenses such as GPL. Hence, it is veryeasy to use libsvm in your software. Please check the COPYRIGHTfile in detail. Basically you need to
- Clearly indicate that LIBSVM is used.
- Retain the LIBSVM COPYRIGHT file in your software.
[GoTop]
Q: Is there a repository of additional toolsbased on libsvm?
Yes, see libsvmtools
[GoTop]
Q: On unix machines, I got "error in loadingshared libraries" or "cannot open shared object file." Whathappened ?
This usually happens if you compile the code on one machine andrun it on another which has incompatible libraries. Try torecompile the program on that machine or use static linking.
[GoTop]
Q: I have modified the source and would like tobuild the graphic interface "svm-toy" on MS windows. How should Ido it ?
Build it as a project by choosing "Win32 Project." On the otherhand, for "svm-train" and "svm-predict" you want to choose "Win32Console Project." After libsvm 2.5, you can also use the fileMakefile.win. See details in README.
If you are not using Makefile.win and see the following linkerror
LIBCMTD.lib(wwincrt0.obj) : error LNK2001: unresolved external symbol_wWinMain@16you may have selected a wrong project type.
[GoTop]
Q: I am an MS windows user but why only one(svm-toy) of those precompiled .exe actually runs ?
You need to open a command window and type svmtrain.exe to seeall options. Some examples are in README file.
[GoTop]
Q: What is the difference between "." and "*"outputed during training?
"." means every 1,000 iterations (or every #data iterations isyour #data is less than 1,000). "*" means that after iterations ofusing a smaller shrunk problem, we reset to use the whole set. Seethe implementationdocument for details.
[GoTop]
Q: Why occasionally the program (includingMATLAB or other interfaces) crashes and gives a segmentationfault?
Very likely the program consumes too much memory than what theoperating system can provide. Try a smaller data and see if theprogram still crashes.
[GoTop]
Q: How to build a dynamic library (.dll file)on MS windows?
The easiest way is to use Makefile.win. See details in README.Alternatively, you can use Visual C++. Here is the example usingVisual Studio .Net 2008:
- Create a Win32 empty DLL project and set (inProject->$Project_Name Properties...->Configuration) to"Release." About how to create a new dynamic link library, pleaserefer to http://msdn2.microsoft.com/en-us/library/ms235636(VS.80).aspx
- Add svm.cpp, svm.h to your project.
- Add __WIN32__ and _CRT_SECURE_NO_DEPRECATE to Preprocessordefinitions (in Project->$Project_NameProperties...->C/C++->Preprocessor)
- Set Create/Use Precompiled Header to Not Using PrecompiledHeaders (in Project->$Project_NameProperties...->C/C++->Precompiled Headers)
- Set the path for the Modulation Definition File svm.def (inProject->$Project_Name Properties...->Linker->input
- Build the DLL.
- Rename the dll file to libsvm.dll and move it to the correctpath.
[GoTop]
Q: On some systems (e.g., Ubuntu), compilingLIBSVM gives many warning messages. Is this a problem and how todisable the warning message?
The warning message is like
svm.cpp:2730: warning: ignoring return value of int fscanf(FILE*, const char*, ...), declared with attribute warn_unused_resultThis is not a problem; see thispage for more details of ubuntu systems. In the future we maymodify the code so that these messages do not appear. At thismoment, to disable the warning message you can replace
CFLAGS = -Wall -Wconversion -O3 -fPICwith
CFLAGS = -Wall -Wconversion -O3 -fPIC -U_FORTIFY_SOURCEin Makefile.
[GoTop]
Q: In LIBSVM, why you don't use certain C/C++library functions to make the code shorter?
For portability, we use only features defined in ISO C89. Notethat features in ISO C99 may not be available everywhere. Even thenewest gcc lacks some features in C99 (see http://gcc.gnu.org/c99status.htmlfor details). If the situation changes in the future, we mightconsider using these newer features.
[GoTop]
Q:Why sometimes not all attributes of a data appear in thetraining/model files ?
libsvm uses the so called "sparse" format where zero values donot need to be stored. Hence a data with attributes
1 0 2 0is represented as
1:1 3:2
[GoTop]
Q:What if my data are non-numerical ?
Currently libsvm supports only numerical data. You may have tochange non-numerical data to numerical. For example, you can useseveral binary attributes to represent a categorical attribute.
[GoTop]
Q:Why do you consider sparse format ? Will the training of dense databe much slower ?
This is a controversial issue. The kernel evaluation (i.e. innerproduct) of sparse vectors is slower so the total training time canbe at least twice or three times of that using the dense format.However, we cannot support only dense format as then we CANNOThandle extremely sparse cases. Simplicity of the code is anotherconcern. Right now we decide to support the sparse format only.
[GoTop]
Q:Why sometimes the last line of my data is not read bysvm-train?
We assume that you have 'n' in the end of each line. So pleasepress enter in the end of your last line.
[GoTop]
Q:Is there a program to check if my data are in the correctformat?
The svm-train program in libsvm conducts only a simple check ofthe input data. To do a detailed check, after libsvm 2.85, you canuse the python script tools/checkdata.py. See tools/README fordetails.
[GoTop]
Q:May I put comments in data files?
We don't officially support this. But, currently LIBSVM is ableto process data in the following format:
1 1:2 2:1 # your commentsNote that the character ":" should not appear in your comments.
[GoTop]
Q:How to convert other data formats to LIBSVM format?
It depends on your data format. A simple way is to uselibsvmwrite in the libsvm matlab/octave interface. Take a CSV(comma-separated values) file in UCI machine learning repository asan example. We download SPECTF.train. Labels are in the first column. The followingsteps produce a file in the libsvm format.
matlab> SPECTF = csvread('SPECTF.train'); % read a csv filematlab> labels = SPECTF(:, 1); % labels from the 1st columnmatlab> features = SPECTF(:, 2:end); matlab> features_sparse = sparse(features); % features must be in a sparse matrixmatlab> libsvmwrite('SPECTFlibsvm.train', labels, features_sparse);The tranformed data are stored in SPECTFlibsvm.train.
Alternatively, you can use convert.cto convert CSV format to libsvm format.
[GoTop]
Q: The output of training C-SVM is like the following.What do they mean?
optimization finished, #iter = 219
nu = 0.431030
obj = -100.877286, rho = 0.424632
nSV = 132, nBSV = 107
Total nSV = 132
obj is the optimal objective value of the dual SVM problem. rhois the bias term in the decision function sgn(w^Tx - rho). nSV andnBSV are number of support vectors and bounded support vectors(i.e., alpha_i = C). nu-svm is a somewhat equivalent form of C-SVMwhere C is replaced by nu. nu simply shows the correspondingparameter. More details are in libsvmdocument.
[GoTop]
Q: Can you explain more about the modelfile?
In the model file, after parameters and other informations suchas labels , each line represents a support vector. Support vectorsare listed in the order of "labels" shown earlier. (i.e., thosefrom the first class in the "labels" list are grouped first, and soon.) If k is the total number of classes, in front of a supportvector in class j, there are k-1 coefficients y*alpha where alphaare dual solution of the following two class problems:
1 vs j, 2 vs j, ..., j-1 vs j, j vs j+1, j vs j+2, ..., j vsk
and y=1 in first j-1 coefficients, y=-1 in the remaining k-jcoefficients. For example, if there are 4 classes, the file lookslike:
+-+-+-+--------------------+|1|1|1| ||v|v|v| SVs from class 1 ||2|3|4| |+-+-+-+--------------------+|1|2|2| ||v|v|v| SVs from class 2 ||2|3|4| |+-+-+-+--------------------+|1|2|3| ||v|v|v| SVs from class 3 ||3|3|4| |+-+-+-+--------------------+|1|2|3| ||v|v|v| SVs from class 4 ||4|4|4| |+-+-+-+--------------------+See also anillustration using MATLAB/OCTAVE.
[GoTop]
Q: Should I use float or double to store numbers in thecache ?
We have float as the default as you can store more numbers inthe cache. In general this is good enough but for few difficultcases (e.g. C very very large) where solutions are huge numbers, itmight be possible that the numerical precision is not enough usingonly float.
[GoTop]
Q: How do I choose the kernel?
In general we suggest you to try the RBF kernel first. A recentresult by Keerthi and Lin ( download paperhere) shows that if RBF is used with model selection, thenthere is no need to consider the linear kernel. The kernel matrixusing sigmoid may not be positive definite and in general it'saccuracy is not better than RBF. (see the paper by Lin and Lin (download paperhere). Polynomial kernels are ok but if a high degree is used,numerical difficulties tend to happen (thinking about dth power of(<1) goes to 0 and (>1) goes to infinity).
[GoTop]
Q: Does libsvm have special treatments for linearSVM?
No, libsvm solves linear/nonlinear SVMs by the same way. Sometricks may save training/testing time if the linear kernel is used,so libsvm is NOT particularly efficient for linear SVM,especially when C is large and the number of data is much largerthan the number of attributes. You can either
Please also see our SVMguide on the discussion of using RBF and linear kernels.
[GoTop]
Q: The number of free support vectors is large. Whatshould I do?
This usually happens when the data are overfitted. If attributesof your data are in large ranges, try to scale them. Then theregion of appropriate parameters may be larger. Note that there isa scale program in libsvm.
[GoTop]
Q: Should I scale training and testing data in a similarway?
Yes, you can do the following:
> svm-scale -s scaling_parameters train_data > scaled_train_data> svm-scale -r scaling_parameters test_data > scaled_test_data
[GoTop]
Q: Does it make a big difference if I scale eachattribute to [0,1] instead of [-1,1]?
For the linear scaling method, if the RBF kernel is used andparameter selection is conducted, there is no difference. Assume Miand mi are respectively the maximal and minimal values of the ithattribute. Scaling to [0,1] means
x'=(x-mi)/(Mi-mi)For [-1,1],
x''=2(x-mi)/(Mi-mi)-1.In the RBF kernel,
x'-y'=(x-y)/(Mi-mi), x''-y''=2(x-y)/(Mi-mi).Hence, using (C,g) on the [0,1]-scaled data is the same as (C,g/2)on the [-1,1]-scaled data.
Though the performance is the same, the computational time maybe different. For data with many zero entries, [0,1]-scaling keepsthe sparsity of input data and hence may save the time.
[GoTop]
Q: The prediction rate is low. How could I improveit?
Try to use the model selection tool grid.py in the pythondirectory find out good parameters. To see the importance of modelselection, please see my talk: A practicalguide to support vector classification
[GoTop]
Q: My data are unbalanced. Could libsvm handle suchproblems?
Yes, there is a -wi options. For example, if you use
> svm-train -s 0 -c 10 -w1 1 -w-1 5 data_file
the penalty for class "-1" is larger. Note that this -w optionis for C-SVC only.
[GoTop]
Q: What is the difference between nu-SVC andC-SVC?
Basically they are the same thing but with different parameters.The range of C is from zero to infinity but nu is always between[0,1]. A nice property of nu is that it is related to the ratio ofsupport vectors and the ratio of the training error.
[GoTop]
Q: The program keeps running (without showing anyoutput). What should I do?
You may want to check your data. Each training/testing data mustbe in one line. It cannot be separated. In addition, you have toremove empty lines.
[GoTop]
Q: The program keeps running (with output, i.e. manydots). What should I do?
In theory libsvm guarantees to converge. Therefore, this meansyou are handling ill-conditioned situations (e.g. too large/smallparameters) so numerical difficulties occur.
You may get better numerical stability by replacing
typedef float Qfloat;in svm.cpp with
typedef double Qfloat;That is, elements in the kernel cache are stored in double insteadof single. However, this means fewer elements can be put in thekernel cache.
[GoTop]
Q: The training time is too long. What should Ido?
For large problems, please specify enough cache size (i.e., -m).Slow convergence may happen for some difficult cases (e.g. -c islarge). You can try to use a looser stopping tolerance with -e. Ifthat still doesn't work, you may train only a subset of the data.You can use the program subset.py in the directory "tools" toobtain a random subset.
If you have extremely large data and face this difficulty,please contact us. We will be happy to discuss possiblesolutions.
When using large -e, you may want to check if -h 0 (noshrinking) or -h 1 (shrinking) is faster. See a related questionbelow.
[GoTop]
Q: Does shrinking always help?
If the number of iterations is high, then shrinking often helps.However, if the number of iterations is small (e.g., you specify alarge -e), then probably using -h 0 (no shrinking) is better. Seethe implementationdocument for details.
[GoTop]
Q: How do I get the decision value(s)?
We print out decision values for regression. For classification,we solve several binary SVMs for multi-class cases. You can obtainvalues by easily calling the subroutine svm_predict_values. Theircorresponding labels can be obtained from svm_get_labels. Detailsare in README of libsvm package.
If you are using MATLAB/OCTAVE interface, svmpredict candirectly give you decision values. Please see matlab/README fordetails.
We do not recommend the following. But if you would like to getvalues for TWO-class classification with labels +1 and -1 (note: +1and -1 but not things like 5 and 10) in the easiest way, simplyadd
printf("%fn", dec_values[0]*model->label[0]);after the line
svm_predict_values(model, x, dec_values);of the file svm.cpp. Positive (negative) decision values correspondto data predicted as +1 (-1).
[GoTop]
Q: How do I get the distance between a point and thehyperplane?
The distance is |decision_value| / |w|. We have |w|^2 = w^Tw =alpha^T Q alpha = 2*(dual_obj + sum alpha_i). Thus in svm.cppplease find the place where we calculate the dual objective value(i.e., the subroutine Solve()) and add a statement to printw^Tw.
[GoTop]
Q: On 32-bit machines, if I use a large cache (i.e. large-m) on a linux machine, why sometimes I get "segmentation fault?"
On 32-bit machines, the maximum addressable memory is 4GB. TheLinux kernel uses 3:1 split which means user space is 3G and kernelspace is 1G. Although there are 3G user space, the maximum dynamicallocation memory is 2G. So, if you specify -m near 2G, the memorywill be exhausted. And svm-train will fail when it asks morememory. For more details, please read this article.
The easiest solution is to switch to a 64-bit machine.Otherwise, there are two ways to solve this. If your machinesupports Intel's PAE (Physical Address Extension), you can turn onthe option HIGHMEM64G in Linux kernel which uses 4G:4G split forkernel and user space. If you don't, you can try a software `tub'which can eliminate the 2G boundary for dynamic allocated memory.The `tub' is available at http://www.bitwagon.com/tub.html.
[GoTop]
Q: How do I disable screen output ofsvm-train?
For commend-line users, use the -q option:
> ./svm-train -q heart_scale
For library users, set the global variable
extern void (*svm_print_string) (const char *);to specify the output format. You can disable the output by thefollowing steps:
- Declare a function to output nothing:
void print_null(const char *s) {}
- Assign the output function of libsvm by
svm_print_string = &print_null;
#if 1void info(const char *fmt,...)to
#if 0void info(const char *fmt,...)
[GoTop]
Q: I would like to use my own kernel. Any example? Insvm.cpp, there are two subroutines for kernel evaluations:k_function() and kernel_function(). Which one should I modify?
An example is "LIBSVM for string data" in LIBSVM Tools.
The reason why we have two functions is as follows. For the RBFkernel exp(-g |xi - xj|^2), if we calculate xi - xj first and thenthe norm square, there are 3n operations. Thus we consider exp(-g(|xi|^2 - 2dot(xi,xj) +|xj|^2)) and by calculating all |xi|^2 inthe beginning, the number of operations is reduced to 2n. This isfor the training. For prediction we cannot do this so a regularsubroutine using that 3n operations is needed. The easiest way tohave your own kernel is to put the same code in these twosubroutines by replacing any kernel.
[GoTop]
Q: What method does libsvm use for multi-class SVM ? Whydon't you use the "1-against-the rest" method?
It is one-against-one. We chose it after doing the followingcomparison: C.-W. Hsu and C.-J. Lin. Acomparison of methods for multi-class support vector machines ,IEEE Transactions on Neural Networks, 13(2002), 415-425.
"1-against-the rest" is a good method whose performance iscomparable to "1-against-1." We do the latter simply because itstraining time is shorter.
[GoTop]
Q: How does LIBSVM perform parameter selection formulti-class problems?
LIBSVM implements "one-against-one" multi-class method, so thereare k(k-1)/2 binary models, where k is the number of classes.
We can consider two ways to conduct parameter selection.
- For any two classes of data, a parameter selection procedure isconducted. Finally, each decision function has its own optimalparameters.
- The same parameters are used for all k(k-1)/2 binaryclassification problems. We select parameters that achieve thehighest overall performance.
Chen, Lin, and Schölkopf, Atutorial on nu-support vector machines. Applied StochasticModels in Business and Industry, 21(2005), 111-136,
they have experimentally shown that the two methods give similarperformance. Therefore, currently the parameter selection in LIBSVMtakes the second approach by considering the same parameters forall k(k-1)/2 models.
[GoTop]
Q: After doing cross validation, why there is no modelfile outputted ?
Cross validation is used for selecting good parameters. Afterfinding them, you want to re-train the whole data without the -voption.
[GoTop]
Q: Why my cross-validation results are different fromthose in the Practical Guide?
Due to random partitions of the data, on different systems CVaccuracy values may be different.
[GoTop]
Q: On some systems CV accuracy is the same in severalruns. How could I use different data partitions? In other words,how do I set random seed in LIBSVM?
If you use GNU C library, the default seed 1 is considered. Thusyou always get the same result of running svm-train -v. To havedifferent seeds, you can add the following code in svm-train.c:
#includeand in the beginning of main(),
srand(time(0));Alternatively, if you are not using GNU C library and would like touse a fixed seed, you can have
srand(1);
For Java, the random number generator is initialized using thetime information. So results of two CV runs are different. To fixthe seed, after version 3.1 (released in mid 2011), you can add
svm.rand.setSeed(0);in the main() function of svm_train.java.
If you use CV to select parameters, it is recommended to useidentical folds under different parameters. In this case, you canconsider fixing the seed.
[GoTop]
Q: I would like to solve L2-loss SVM (i.e., error term isquadratic). How should I modify the code ?
It is extremely easy. Taking c-svc for example, to solve
min_w w^Tw/2 + C sum max(0, 1- (y_i w^Tx_i+b))^2,
only two places of svm.cpp have to be changed. First, modify thefollowing line of solve_c_svc from
s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y, alpha, Cp, Cn, param->eps, si, param->shrinking);to
s.Solve(l, SVC_Q(*prob,*param,y), minus_ones, y, alpha, INF, INF, param->eps, si, param->shrinking);Second, in the class of SVC_Q, declare C as a private variable:
double C;In the constructor replace
for(int i=0;i*kernel_function)(i,i);with
this->C = param.C; for(int i=0;i*kernel_function)(i,i)+0.5/C;Then in the subroutine get_Q, after the for loop, add
if(i >= start && i < len) data[i] += 0.5/C;
For one-class svm, the modification is exactly the same. ForSVR, you don't need an if statement like the above. Instead, youonly need a simple assignment:
data[real_i] += 0.5/C;
For large linear L2-loss SVM, please use LIBLINEAR.
[GoTop]
Q: How do I choose parameters for one-class svm astraining data are in only one class?
You have pre-specified true positive rate in mind and thensearch for parameters which achieve similar cross-validationaccuracy.
[GoTop]
Q: Why the code gives NaN (not a number)results?
This rarely happens, but few users reported the problem. Itseems that their computers for training libsvm have the VPN clientrunning. The VPN software has some bugs and causes this problem.Please try to close or disconnect the VPN client.
[GoTop]
Q: Why on windows sometimes grid.py fails?
This problem shouldn't happen after version 2.85. If you areusing earlier versions, please download the latest one.
[GoTop]
Q: Why grid.py/easy.py sometimes generates the followingwarning message?
Warning: empty z range [62.5:62.5], adjusting to [61.875:63.125]Notice: cannot contour non grid data!
Nothing is wrong and please disregard the message. It is fromgnuplot when drawing the contour.
[GoTop]
Q: Why the sign of predicted labels and decision valuesare sometimes reversed?
This situation may occur before version 3.17. Nothing iswrong. Very likely you have two labels +1/-1 and the first instancein your data has -1. We give the following explanation.
Internally class labels are ordered by their first occurrence inthe training set. For a k-class data, internally labels are 0, ...,k-1, and each two-class SVM considers pair (i, j) with i < j.Then class i is treated as positive (+1) and j as negative (-1).For example, if the data set has labels +5/+10 and +10 appearsfirst, then internally the +5 versus +10 SVM problem has +10 aspositive (+1) and +5 as negative (-1).
By this setting, if you have labels +1 and -1, it's possiblethat internally they correspond to -1 and +1, respectively. Somenew users have been confused about this, so after version3.17, if the data set has only two labels +1 and -1, internallywe ensure +1 to be before -1. Then class +1 is always treated aspositive in the SVM problem. Note that this is for two-classdata only.
[GoTop]
Q: I don't know class labels of test data. What should Iput in the first column of the test file?
Any value is ok. In this situation, what you will use is theoutput file of svm-predict, which gives predicted class labels.
[GoTop]
Q: How can I use OpenMP to parallelize LIBSVM on amulticore/shared-memory computer?
It is very easy if you are using GCC 4.2 or after.
In Makefile, add -fopenmp to CFLAGS.
In class SVC_Q of svm.cpp, modify the for loop of get_Q to:
#pragma omp parallel for private(j) for(j=start;j
In the subroutine svm_predict_values of svm.cpp, add one line tothe for loop:
#pragma omp parallel for private(i) for(i=0;iSV[i],model->param);For regression, you need to modify class SVR_Q instead. The loop insvm_predict_values is also different because you need a reductionclause for the variable sum:
#pragma omp parallel for private(i) reduction(+:sum) for(i=0;il;i++) sum += sv_coef[i] * Kernel::k_function(x,model->SV[i],model->param);
Then rebuild the package. Kernel evaluations in training/testingwill be parallelized. An example of running this modification on an8-core machine using the data set ijcnn1:
8 cores:
%setenv OMP_NUM_THREADS 8%time svm-train -c 16 -g 4 -m 400 ijcnn127.1sec1 core:
%setenv OMP_NUM_THREADS 1%time svm-train -c 16 -g 4 -m 400 ijcnn179.8secFor this data, kernel evaluations take 80% of training time. In theabove example, we assume you use csh. For bash, use
export OMP_NUM_THREADS=8instead.
For Python interface, you need to add the -lgomp linkoption:
$(CXX) -lgomp -shared -dynamiclib svm.o -o libsvm.so.$(SHVER)
For MS Windows, you need to add /openmp in CFLAGS ofMakefile.win
[GoTop]
Q: How could I know which training instances are supportvectors?
It's very simple. Since version 3.13, you can use thefunction
void svm_get_sv_indices(const struct svm_model *model, int *sv_indices)to get indices of support vectors. For example, in svm-train.c,after
model = svm_train(&prob, ¶m);you can add
int nr_sv = svm_get_nr_sv(model); int *sv_indices = Malloc(int, nr_sv); svm_get_sv_indices(model, sv_indices); for (int i=0; i
If you use matlab interface, you can directly check
model.sv_indices
[GoTop]
Q: Why sv_indices (indices of support vectors) are notstored in the saved model file?
Although sv_indices is a member of the model structure toindicate support vectors in the training set, we do not store itscontents in the model file. The model file is mainly used in thefuture for prediction, so it is basically independent fromtraining data. Thus storing sv_indices is not necessary. Usersshould find support vectors right after the training process. Seethe previous FAQ.
[GoTop]
Q: Why training a probability model (i.e., -b 1) takes alonger time?
To construct this probability model, we internally conduct across validation, which is more time consuming than a regulartraining. Hence, in general you do parameter selection firstwithout -b 1. You only use -b 1 when good parameters have beenselected. In other words, you avoid using -b 1 and -v together.
[GoTop]
Q: Why using the -b option does not give me betteraccuracy?
There is absolutely no reason the probability outputs guaranteeyou better accuracy. The main purpose of this option is to provideyou the probability estimates, but not to boost predictionaccuracy. From our experience, after proper parameter selections,in general with and without -b have similar accuracy. Occasionallythere are some differences. It is not recommended to compare thetwo under just a fixed parameter set as more differences will beobserved.
[GoTop]
Q: Why using svm-predict -b 0 and -b 1 gives differentaccuracy values?
Let's just consider two-class classification here. Afterprobability information is obtained in training, we do not have
prob > = 0.5 if and only if decision value >= 0.
So predictions may be different with -b 0 and 1.
[GoTop]
Q:How can I save images drawn by svm-toy?
For Microsoft windows, first press the "print screen" key on thekeyboard. Open "Microsoft Paint" (included in Windows) and press"ctrl-v." Then you can clip the part of picture which you want. ForX windows, you can use the program "xv" or "import" to grab thepicture of the svm-toy window.
[GoTop]
Q:I press the "load" button to load data points but why svm-toy doesnot draw them ?
The program svm-toy assumes both attributes (i.e. x-axis andy-axis values) are in (0,1). Hence you want to scale your data tobetween a small positive number and a number less than but veryclose to 1. Moreover, class labels must be 1, 2, or 3 (not 1.0, 2.0or anything else).
[GoTop]
Q:I would like svm-toy to handle more than three classes of data,what should I do ?
Taking windows/svm-toy.cpp as an example, you need to modify itand the difference from the original file is as the following: (forfive classes of data)
30,32c30< RGB(200,0,200),< RGB(0,160,0),< RGB(160,0,0)---> RGB(200,0,200)39c37< HBRUSH brush1, brush2, brush3, brush4, brush5;---> HBRUSH brush1, brush2, brush3;113,114d110< brush4 = CreateSolidBrush(colors[7]);< brush5 = CreateSolidBrush(colors[8]);155,157c151< else if(v==3) return brush3;< else if(v==4) return brush4;< else return brush5;---> else return brush3;325d318< int colornum = 5;327c320< svm_node *x_space = new svm_node[colornum * prob.l];---> svm_node *x_space = new svm_node[3 * prob.l];333,338c326,331< x_space[colornum * i].index = 1;< x_space[colornum * i].value = q->x;< x_space[colornum * i + 1].index = 2;< x_space[colornum * i + 1].value = q->y;< x_space[colornum * i + 2].index = -1;< prob.x[i] = &x_space[colornum * i];---> x_space[3 * i].index = 1;> x_space[3 * i].value = q->x;> x_space[3 * i + 1].index = 2;> x_space[3 * i + 1].value = q->y;> x_space[3 * i + 2].index = -1;> prob.x[i] = &x_space[3 * i];397c390< if(current_value > 5) current_value = 1;---> if(current_value > 3) current_value = 1;
[GoTop]
Q: What is the difference between Java version and C++version of libsvm?
They are the same thing. We just rewrote the C++ code inJava.
[GoTop]
Q: Is the Java version significantly slower than the C++version?
This depends on the VM you used. We have seen good VM whichleads the Java version to be quite competitive with the C++ code.(though still slower)
[GoTop]
Q: While training I get the following error message:java.lang.OutOfMemoryError. What is wrong?
You should try to increase the maximum Java heap size. Forexample,
java -Xmx2048m -classpath libsvm.jar svm_train ...sets the maximum heap size to 2048M.
[GoTop]
Q: Why you have the main source file svm.m4 and thentransform it to svm.java?
Unlike C, Java does not have a preprocessor built-in. However,we need some macros (see first 3 lines of svm.m4).
[GoTop]
Q:Except the python-C++ interface provided, could I use Jython tocall libsvm ?
Yes, here are some examples:
$ export CLASSPATH=$CLASSPATH:~/libsvm-2.91/java/libsvm.jar$ ./jythonJython 2.1a3 on java1.3.0 (JIT: jitc)Type "copyright", "credits" or "license" for more information.>>> from libsvm import *>>> dir()['__doc__', '__name__', 'svm', 'svm_model', 'svm_node', 'svm_parameter','svm_problem']>>> x1 = [svm_node(index=1,value=1)]>>> x2 = [svm_node(index=1,value=-1)]>>> param = svm_parameter(svm_type=0,kernel_type=2,gamma=1,cache_size=40,eps=0.001,C=1,nr_weight=0,shrinking=1)>>> prob = svm_problem(l=2,y=[1,-1],x=[x1,x2])>>> model = svm.svm_train(prob,param)*optimization finished, #iter = 1nu = 1.0obj = -1.018315639346838, rho = 0.0nSV = 2, nBSV = 2Total nSV = 2>>> svm.svm_predict(model,x1)1.0>>> svm.svm_predict(model,x2)-1.0>>> svm.svm_save_model("test.model",model)
[GoTop]
Q:I compile the MATLAB interface without problem, but why errorsoccur while running it?
Your compiler version may not be supported/compatible forMATLAB. Please check thisMATLAB page first and then specify the version number. Forexample, if g++ X.Y is supported, replace
CXX = g++in the Makefile with
CXX = g++-X.Y
[GoTop]
Q: On 64bit Windows I compile the MATLAB interfacewithout problem, but why errors occur while runningit?
Please make sure that you use the -largeArrayDims option inmake.m. For example,
mex -largeArrayDims -O -c svm.cppMoreover, if you use Microsoft Visual Studio, probabally it is notproperly installed. See the explanation here.
[GoTop]
Q:Does the MATLAB interface provide a function to doscaling?
It is extremely easy to do scaling under MATLAB. The followingone-line code scale each feature to the range of [0,1]:
(data - repmat(min(data,[],1),size(data,1),1))*spdiags(1./(max(data,[],1)-min(data,[],1))',0,size(data,2),size(data,2))
[GoTop]
Q:How could I use MATLAB interface for parameterselection?
One can do this by a simple loop. See the following example:
bestcv = 0;for log2c = -1:3, for log2g = -4:1, cmd = ['-v 5 -c ', num2str(2^log2c), ' -g ', num2str(2^log2g)]; cv = svmtrain(heart_scale_label, heart_scale_inst, cmd); if (cv >= bestcv), bestcv = cv; bestc = 2^log2c; bestg = 2^log2g; end fprintf('%g %g %g (best c=%g, g=%g, rate=%g)n', log2c, log2g, cv, bestc, bestg, bestcv); endendYou may adjust the parameter range in the above loops.
[GoTop]
Q: I use MATLAB parallel programming toolbox on amulti-core environment for parameter selection. Why the program iseven slower?
Fabrizio Lacalandra of University of Pisa reported this issue.It seems the problem is caused by the screen output. If you disablethe info function using
#if 0,then the problem may be solved.
[GoTop]
Q: How do I use LIBSVM with OpenMP underMATLAB?
In Makefile, you need to add -fopenmp to CFLAGS and -lgomp toMEX_OPTION. For Octave, you need the same modification.
However, a minor problem is that the number of threads cannot bespecified in MATLAB. We tried Version 7.12 (R2011a) andgcc-4.6.1.
% export OMP_NUM_THREADS=4; matlab>> setenv('OMP_NUM_THREADS', '1');Then OMP_NUM_THREADS is still 4 while running the program. Pleasecontact us if you see how to solve this problem. You can, however,specify the number in the source code (thanks to comments fromRicardo Santiago-mozos):
#pragma omp parallel for private(i) num_threads(4)
[GoTop]
Q:How could I generate the primal variable w of linearSVM?
Let's start from the binary class and assume you have two labels-1 and +1. After obtaining the model from calling svmtrain, do thefollowing to have w and b:
w = model.SVs' * model.sv_coef;b = -model.rho;if model.Label(1) == -1 w = -w; b = -b;endIf you do regression or one-class SVM, then the if statement is notneeded.
For multi-class SVM, we illustrate the setting in the followingexample of running the iris data, which have 3 classes
> [y, x] = libsvmread('../../htdocs/libsvmtools/datasets/multiclass/iris.scale');> m = svmtrain(y, x, '-t 0')m = Parameters: [5x1 double] nr_class: 3 totalSV: 42 rho: [3x1 double] Label: [3x1 double] ProbA: [] ProbB: [] nSV: [3x1 double] sv_coef: [42x2 double] SVs: [42x4 double]sv_coef is like:
+-+-+--------------------+|1|1| ||v|v| SVs from class 1 ||2|3| |+-+-+--------------------+|1|2| ||v|v| SVs from class 2 ||2|3| |+-+-+--------------------+|1|2| ||v|v| SVs from class 3 ||3|3| |+-+-+--------------------+so we need to see nSV of each classes.
> m.nSVans = 3 21 18Suppose the goal is to find the vector w of classes 1 vs 3. Theny_i alpha_i of training 1 vs 3 are
> coef = [m.sv_coef(1:3,2); m.sv_coef(25:42,1)];and SVs are:
> SVs = [m.SVs(1:3,:); m.SVs(25:42,:)];Hence, w is
> w = SVs'*coef;For rho,
> m.rhoans = 1.1465 0.3682 -1.9969> b = -m.rho(2);because rho is arranged by 1vs2 1vs3 2vs3.
[GoTop]
Q:Is there an OCTAVE interface for libsvm?
Yes, after libsvm 2.86, the matlab interface works on OCTAVE aswell. Please use make.m by typing
>> makeunder OCTAVE.
[GoTop]
Q:How to handle the name conflict between svmtrain in the libsvmmatlab interface and that in MATLAB bioinformaticstoolbox?
The easiest way is to rename the svmtrain binary file (e.g.,svmtrain.mexw32 on 32-bit windows) to a different name (e.g.,svmtrain2.mexw32).
[GoTop]
Q:On Windows I got an error message "Invalid MEX-file: Specificmodule not found" when running the pre-built MATLAB interface inthe windows sub-directory. What should I do?
The error usually happens when there are missing runtimecomponents such as MSVCR100.dll on your Windows platform. You canuse tools such as Dependency Walker to findmissing library files.
For example, if the pre-built MEX files are compiled by VisualC++ 2010, you must have installed Microsoft Visual C++Redistributable Package 2010 (vcredist_x86.exe). You can easilyfind the freely available file from Microsoft's web site.
For 64bit Windows, the situation is similar. If the pre-builtfiles are by Visual C++ 2008, then you must have Microsoft VisualC++ Redistributable Package 2008 (vcredist_x64.exe).
[GoTop]
Q:LIBSVM supports 1-vs-1 multi-class classification. If instead Iwould like to use 1-vs-rest, how to implement it using MATLABinterface?
Please use code in the following directory.The following example shows how to train and test the problem dna(trainingand testing).
Load, train and predict data:
[trainY trainX] = libsvmread('./dna.scale');[testY testX] = libsvmread('./dna.scale.t');model = ovrtrain(trainY, trainX, '-c 8 -g 4');[pred ac decv] = ovrpredict(testY, testX, model);fprintf('Accuracy = %g%%n', ac * 100);Conduct CV on a grid of parameters
bestcv = 0;for log2c = -1:2:3, for log2g = -4:2:1, cmd = ['-q -c ', num2str(2^log2c), ' -g ', num2str(2^log2g)]; cv = get_cv_ac(trainY, trainX, cmd, 3); if (cv >= bestcv), bestcv = cv; bestc = 2^log2c; bestg = 2^log2g; end fprintf('%g %g %g (best c=%g, g=%g, rate=%g)n', log2c, log2g, cv, bestc, bestg, bestcv); endend