資源簡(jiǎn)介
用matlab編程實(shí)現(xiàn)支持向量機(jī)分類,核函數(shù)選取,超平面建立等
代碼片段和文件信息
%主函數(shù)
clear?all;
close?all;
C?=?10;
kertype?=?‘linear‘;
%訓(xùn)練樣本
n?=?50;
randn(‘state‘6);
x1?=?randn(2n);????%2行N列矩陣
y1?=?ones(1n);???????%1*N個(gè)1
x2?=?5+randn(2n);???%2*N矩陣
y2?=?-ones(1n);??????%1*N個(gè)-1
?
figure;
plot(x1(1:)x1(2:)‘bx‘x2(1:)x2(2:)‘k.‘);?
axis([-3?8?-3?8]);
hold?on;
?
X?=?[x1x2];????????%訓(xùn)練樣本d*n矩陣,n為樣本個(gè)數(shù),d為特征向量個(gè)數(shù)
Y?=?[y1y2];????????%訓(xùn)練目標(biāo)1*n矩陣,n為樣本個(gè)數(shù),值為+1或-1
svm?=?svmtrain(XYkertypeC);
plot(svm.Xsv(1:)svm.Xsv(2:)‘ro‘);
%測(cè)試
[x1x2]?=?meshgrid(-2:0.05:7-2:0.05:7);??%x1和x2都是181*181的矩陣
[rowscols]?=?size(x1);??
nt?=?rows*cols;??????????????????
Xt?=?[reshape(x11nt);reshape(x21nt)];
Yt?=?ones(1nt);
result?=?svmtest(svm?Xt?Yt?kertype);
Yd?=?reshape(resultYrowscols);
contour(x1x2Yd‘m‘);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function?svm?=?svmtrain(XYkertypeC)
options?=?optimset;????%?Options是用來控制算法的選項(xiàng)參數(shù)的向量
options.LargeScale?=?‘off‘;
options.Display?=?‘off‘;
n?=?length(Y);
H?=?(Y‘*Y).*kernel(XXkertype);
f?=?-ones(n1);?%f為1*n個(gè)-1f相當(dāng)于Quadprog函數(shù)中的c
A?=?[];
b?=?[];
Aeq?=?Y;?%相當(dāng)于Quadprog函數(shù)中的A1b
評(píng)論
共有 條評(píng)論