svmPredict.m 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. function pred = svmPredict(model, X)
  2. %SVMPREDICT returns a vector of predictions using a trained SVM model
  3. %(svmTrain).
  4. % pred = SVMPREDICT(model, X) returns a vector of predictions using a
  5. % trained SVM model (svmTrain). X is a mxn matrix where there each
  6. % example is a row. model is a svm model returned from svmTrain.
  7. % predictions pred is a m x 1 column of predictions of {0, 1} values.
  8. %
  9. % Check if we are getting a column vector, if so, then assume that we only
  10. % need to do prediction for a single example
  11. if (size(X, 2) == 1)
  12. % Examples should be in rows
  13. X = X';
  14. end
  15. % Dataset
  16. m = size(X, 1);
  17. p = zeros(m, 1);
  18. pred = zeros(m, 1);
  19. if strcmp(func2str(model.kernelFunction), 'linearKernel')
  20. % We can use the weights and bias directly if working with the
  21. % linear kernel
  22. p = X * model.w + model.b;
  23. elseif strfind(func2str(model.kernelFunction), 'gaussianKernel')
  24. % Vectorized RBF Kernel
  25. % This is equivalent to computing the kernel on every pair of examples
  26. X1 = sum(X.^2, 2);
  27. X2 = sum(model.X.^2, 2)';
  28. K = bsxfun(@plus, X1, bsxfun(@plus, X2, - 2 * X * model.X'));
  29. K = model.kernelFunction(1, 0) .^ K;
  30. K = bsxfun(@times, model.y', K);
  31. K = bsxfun(@times, model.alphas', K);
  32. p = sum(K, 2);
  33. else
  34. % Other Non-linear kernel
  35. for i = 1:m
  36. prediction = 0;
  37. for j = 1:size(model.X, 1)
  38. prediction = prediction + ...
  39. model.alphas(j) * model.y(j) * ...
  40. model.kernelFunction(X(i,:)', model.X(j,:)');
  41. end
  42. p(i) = prediction + model.b;
  43. end
  44. end
  45. % Convert predictions into 0 / 1
  46. pred(p >= 0) = 1;
  47. pred(p < 0) = 0;
  48. end