0

Is there a way that I can run grid.py (from the LIBSVM ) in Matlab? Iam doing svm classification and I am required to perform grid search for the parameters C and g. In LIBSVM the file grid.py finds the best parameteres. However it is a python script and I have no idea how to run it in Matlab. Is there an other way of predicting the best value for the parameteres? Thank you in advance.

Danai Tri
  • 119
  • 3
  • 13
  • 1
    Well, you just said in your question what needs to be done: "perform grid search for the parameters C and g". You can just do that in Matlab: iterate over all the (C,g) pairs and train your model for each one and optimize the accuracy on the [validation dataset](http://stats.stackexchange.com/questions/19048/what-is-the-difference-between-test-set-and-validation-set). You can also target other optimization criteria by using [this](http://www.csie.ntu.edu.tw/~cjlin/libsvmtools/eval/index.html) libsvm extension. Read the grid.py code to see what interval values to use for these parameters. – Mihai Todor Dec 18 '14 at 13:31

1 Answers1

1

It is possible to run python code in MATLAB though I have never done it myself. I looked into it for the same reason as yourself and found, as @Mihia Todor said, it would be easier to write your own version of grid.py. Here is the basic code I wrote to do a grid-search and cross validation using LIBSVM in MATLAB:

gamma=1;
cost=1;
J=10;
K=12;
kernal=2; %RBF 

besterr=[];
bestc=[];
bestg=[];
for j=1:J;
    gamma=2^(2*(j-round(J/3))); %Calculates a nice spread of search numbers centred above zero
    for k=1:K;
        cost=2^(2*(k-round(K/3)));
        err=svmtrain(y,x,sprintf('-s 4 -t %g -v 5 -c %g -g %g -q', kernal, cost, gamma)); %Nu-SVR change -s if you want SVC
        if isempty(besterr)|err<besterr;
            besterr=err;
            bestc=cost;
            bestg=gamma;
        end
    end
end
besterr=sqrt(besterr) %Prints the average RMSD of the 5-fold cross-validation
bestg %Prints best gamma
bestc %Prints best cost

model=svmtrain(y,x,sprintf('-s 4 -t %g -c %g -g %g -q', kernal, bestc, bestg)); %Retrain using new c and g

Assuming you have scaled, sparse x-data this should work out-the-box.

If you do wish to carry on with grid.py and have 2014b this might be a useful place to start looking: Call Python Libraries.

If you do not have 2014b or newer then Call Python function from MATLAB.

Should you get either of these two methods working do write your own answer to your question. I'd love to see them working and I'm sure others would find it very useful!

Community
  • 1
  • 1
Little Bobby Tables
  • 4,466
  • 4
  • 29
  • 46