Clear Filters
Clear Filters

How do I get the distance between the point and the hyperplane using libsvm?

5 views (last 30 days)
I am using libsvm. I need to know, which observations are farest away from the hyperplane. libsvm returns me the "decision_value" but how can I use it to get the distance from the hyperplane? Taking the largest positive and smallest negative values or do I have to compute it manually and if yes, how?

Accepted Answer

Rishabh Gupta
Rishabh Gupta on 2 Aug 2018
Hey Stef
You can find the distance of a point i from hyperplane as follows:
distance_i = |decision_value|_i / |w|-b
where,
w = (alpha * support_vectors)
|w| = sqrt(sum(w^2))
alphas, support_vectors and b is generated from SVM model
  5 Comments
Stef
Stef on 2 Aug 2018
SV_indices contrains the index of the Support vectors in the original matrix. The problem is that I want to find the 5% of observations which are most likely in the -1 category. Therefore I take the x observations which are furthest away from the hyperplane in one direction and the rest (5%-x) which are closest to the hyperplane but in class 1.
Stef
Stef on 2 Aug 2018
Edited: Stef on 2 Aug 2018
See here an example for the fisher Iris. Is there a possibility to find the on which side of the hyperplane the observations are?
load 'fisheriris'
% create X and y
X = meas([1:100],[3:4]);
y = grp2idx(species);
% recode 2 to -1 that lables are 1 and -1
y(y==2) = -1;
%create training and testing sample
rand = randperm(100);
y_train = y(rand([1:80]),:);
X_train = X(rand([1:80]),:);
y_test = y(rand([81:100]),:);
X_test = X(rand([81:100]),:);
% SVM
options =[ '-s 0 -t 0']
[model] = svmtrain(y_train, X_train, options)
[predict_label, accuracy, decision_values] = svmpredict(y_test, X_test, model);
% find distance
w = model.sv_coef' * model.SVs;
w_abs = sqrt(sum(w.^2));
bias = model.rho;
distance = abs(decision_values) ./ (w_abs-bias);

Sign in to comment.

More Answers (0)

Categories

Find more on Statistics and Machine Learning Toolbox in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!