Advertisement
makispaiktis

ML - SVMs in Matlab

Oct 31st, 2022 (edited)
1,273
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.47 KB | None | 0 0
  1. clear all
  2. close all
  3. clc
  4.  
  5. %% Generate Data
  6. p = 2;
  7. n = 200;
  8. prob = 0.5;
  9. n1 = floor(n * prob);
  10. n2 = n - n1;
  11.  
  12. X1 = [1 1] + 0.15 * randn(n1, 2);
  13. y1 = ones(n1, 1);
  14. X2 = [2 2] + 0.15 * randn(n2, 2);
  15. y2 = -ones(n2, 1);
  16.  
  17. X = [X1; X2];
  18. y = [y1; y2];
  19.  
  20. f1 = figure(1);
  21. clf(f1);                        % Using SVMs
  22. plot(X1(:, 1), X1(:, 2), 'bx', 'Linewidth', 2);
  23. hold on
  24. plot(X2(:, 1), X2(:, 2), 'rx', 'Linewidth', 2);
  25. xlims = [0.5 2.5];
  26. ylims = [0.5 2.5];
  27. xlim(xlims);
  28. ylim(ylims);
  29.  
  30.  
  31. %% Lambdas
  32. P = zeros(n, n);
  33. q = ones(n, 1);
  34. for ii = 1 : n
  35.     for jj = 1 : n
  36.         P(ii, jj) = X(ii, :) * X(jj, :)' * y(ii) * y(jj);
  37.     end
  38. end
  39.  
  40. lb = zeros(n, 1);
  41. ub = 100 * ones(n, 1);
  42. lambda = quadprog(P, -q, [], [], y', 0, lb, ub)
  43.  
  44. lambda1 = lambda(1:n1);
  45. k1 = find(lambda1 == max(lambda1));
  46. lambda2 = lambda(n1+1:end);
  47. k2 = find(lambda2 == max(lambda2));
  48.  
  49.  
  50. %% SVM Implementation
  51. beta = zeros(1, p);
  52. b = 0;
  53. for k = 1 : n
  54.     beta = beta + lambda(k) * X(k, :) * y(k);
  55. end
  56. for k = 1 : n
  57.     b = b + (1/n) * (y(k) - beta*X(k, :)');
  58. end
  59.  
  60.  
  61. %% Optimal Hyperplane (Maximum Margin Hyperplane)
  62. xAxis = linspace(xlims(1), xlims(2), 1000);
  63. yk = [];
  64. for x = xAxis
  65.     yk = [yk (-beta(2)*x-b) / beta(1)];               % beta' * x + b = 0
  66. end
  67. plot(xAxis, yk);
  68. hold on
  69. plot(X1(k1, 1), X1(k1, 2), 'bx', 'Linewidth', 3, 'Markersize', 15);
  70. hold on
  71. plot(X2(k2, 1), X2(k2, 2), 'rx', 'Linewidth', 3, 'Markersize', 15);
  72. title("SVMs classification");
  73. xlabel("x");
  74. ylabel("y");
  75.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement