
http://www.ma-xy.com
第一章 中级支持向量机 1.5 MATLAB 支持向量机示例
62 f i g u r e ;
63 h ( 1 : 2 ) = g s ca tt e r ( cdata ( : , 1 ) , cdata ( : , 2 ) , grp , ’ rg ’ , ’+*’ ) ;
64 hold on
65 h(3) = p l ot ( cdata ( SVM_oneclass . IsSupportVector , 1 ) , . . .
66 cdata ( SVM_oneclass . IsSupportVector , 2 ) , ’ ko ’ ) ;
67 contour ( x1Grid , x2Grid , reshape ( s c o r e s ( : , 2 ) , s i z e ( x1Grid ) ) , [ 0 0 ] , ’ k ’ ) ;
68 legend (h ,{ ’−1 ’ , ’+1 ’ , ’ Support Vectors ’ } , ’ Location ’ , ’ Southeast ’ ) ;
69 ax is equal
70 hold o f f
71 % Generate and c l a s s i f y some new data points .
72
73 grnobj = g m d i s t r i b u t i o n ( grnpop , . 2 * eye (2 ) ) ;
74 r edobj = gmdistribution ( redpop , . 2 * eye ( 2 ) ) ;
75
76 newData = random ( grnobj ,1 0 ) ;
77 newData = [ newData ; random( redobj ,1 0 ) ] ;
78 grpData = ones ( 2 0 , 1) ;
79 grpData ( 11 : 20 ) = −1; % red = −1
80
81 v = p re d ic t ( SVM_oneclass , newData ) ;
82
83 g = nan ( 7 , 1 ) ;
84 f i g u r e ;
85 h ( 1 : 2 ) = g s ca tt e r ( cdata ( : , 1 ) , cdata ( : , 2 ) , grp , ’ rg ’ , ’+*’ ) ;
86 hold on
87 h ( 3 : 4 ) = g s ca tt e r ( newData ( : , 1 ) ,newData ( : , 2 ) ,v , ’mc ’ , ’ ** ’ ) ;
88 h(5) = p l ot ( cdata ( SVM_oneclass . IsSupportVector , 1 ) , . . .
89 cdata ( SVM_oneclass . IsSupportVector , 2 ) , ’ ko ’ ) ;
90 contour ( x1Grid , x2Grid , reshape ( s c o r e s ( : , 2 ) , s i z e ( x1Grid ) ) , [ 0 0 ] , ’ k ’ ) ;
91 legend (h ( 1 : 5 ) ,{ ’−1 ( t ra i n i n g ) ’ , ’+1 ( t r a i n i n g ) ’ , ’−1 ( c l a s s i f i e d ) ’ , . . .
92 ’+1 ( c l a s s i f i e d ) ’ , ’ Support Vectors ’ } , ’ Location ’ , ’ Southeast ’ ) ;
93 ax is equal
94 hold o f f
95 % See which new data points are c o r r e c t l y c l a s s i f i e d . C i r c l e the c o r r e c t l y c l a s s i f i e d
poin t s in red , and the i n c o r r e c t l y c l a s s i f i e d p o i nts i n black .
96
97 mydiff = ( v == grpData ) ; % C l a s s i f i e d c o r r e c t l y
98 f i g u r e ;
99 h ( 1 : 2 ) = g s ca tt e r ( cdata ( : , 1 ) , cdata ( : , 2 ) , grp , ’ rg ’ , ’+*’ ) ;
100 hold on
101 h ( 3 : 4 ) = g s ca tt e r ( newData ( : , 1 ) ,newData ( : , 2 ) ,v , ’mc ’ , ’ ** ’ ) ;
102 h(5) = p l ot ( cdata ( SVM_oneclass . IsSupportVector , 1 ) , . . .
103 cdata ( SVM_oneclass . IsSupportVector , 2 ) , ’ ko ’ ) ;
104 contour ( x1Grid , x2Grid , reshape ( s c o r e s ( : , 2 ) , s i z e ( x1Grid ) ) , [ 0 0 ] , ’ k ’ ) ;
105
106 f o r i i = mydiff % Plot red squares around c o r re ct pts
107 h (6) = p l ot ( newData ( i i , 1 ) , newData ( i i , 2 ) , ’ r s ’ , ’ MarkerSize ’ ,1 2 ) ;
108 end
109
110 f o r i i = not ( mydiff ) % Plot black squa r es around in c o r r e c t pts
111 h (7) = p l ot ( newData ( i i , 1 ) , newData ( i i , 2 ) , ’ ks ’ , ’ MarkerSize ’ ,1 2 ) ;
112 end
113 legend (h ,{ ’−1 ( t ra i n i n g ) ’ , ’+1 ( t r a i n i n g ) ’ , ’−1 ( c l a s s i f i e d ) ’ , . . .
http://www.ma-xy.com 21 http://www.ma-xy.com