SVM線性分類MATLAB實現


 

數據集需要自行處理,這里針對的是Cancer數據集

clear
tic
load('C:\Users\Administrator\Desktop\Cancer.mat')
mu=Cancer(1:444,:);zi=Cancer(445:end,:); %整理數據,第一列(1,2)作為標簽
cycle_N=1; %進行cycle_N次交叉驗證
N=10; %N=10十折
c=100;
[N1,col]=size(mu);
[N2,col]=size(zi);
q1=floor(N1/N);q2=floor(N2/N);
%ACC=zeros(1,10);MCC=zeros(1,10);F1=zeros(1,10);

for kk=1:cycle_N %進行NN次交叉訓練
for k=1:N %每次交叉訓練為N折
if k==1
pos_train=mu(q1+1:end,:);pos_test=mu(1:q1,:);
non_train=zi(q2+1:end,:);non_test=zi(1:q2,:);
elseif k==N
pos_train=mu(1:q1*(k-1),:);pos_test=mu(q1*(k-1)+1:end,:);
non_train=zi(1:q2*(k-1),:);non_test=zi(q2*(k-1)+1:end,:);
else
pos_train=[mu(1:q1*(k-1),:);mu(q1*k:end,:)];
non_train=[zi(1:q2*(k-1),:);zi(q2*k:end,:)];
pos_test=mu(q1*(k-1)+1:q1*k-1,:);
non_test=zi(q2*(k-1)+1:q2*k-1,:);
end
pos_train_r=size(pos_train,1);non_train_r=size(non_train,1); %計算正類負類訓練集的行數
train=[pos_train;non_train]; %合並得到訓練集
train_num=pos_train_r+non_train_r; %訓練集的數據點數
y1=[ones(pos_train_r,1);-ones(non_train_r,1)];%訓練點的標簽

pos_test_r=size(pos_test,1);non_test_r=size(non_test,1);
test=[pos_test;non_test]; %合並得到測試集
test_num=pos_test_r+non_test_r; %測試集的數據點數
y2=[ones(pos_test_r,1);-ones(non_test_r,1)];%測試點的標簽

Q=diag(y1)*train*train'*diag(y1);
f=-ones(train_num,1);
Aeq=y1'; %給一系列輸入值賦值
beq=0;
vlb=zeros(train_num,1);vub=c*ones(train_num,1);
alpha=quadprog(Q,f,[],[],Aeq,beq,vlb,vub); %二次規划求解結束

w=alpha'*diag(y1)*train; %把標簽寫成對角陣
temp_index=find(alpha>0 & alpha<c);temp=temp_index(1);
b=y1(temp)-train(temp,:)*w';%b是一個數

%測試
count=0;%TP=0;TN=0;FP=0;FN=0;
pre_Y=sign(test*w'+b*ones(test_num,1));%預測標簽
for i=1:test_num
if pre_Y(i)==y2(i)
count=count+1;
% if y2(i)==1
% TP=TP+1;
% else
% TN=TN+1;
% end
% else
% if y2(i)==1
% FP=FP+1;
% else
% FN=FN+1;
% end
end
end
%ACC(k)=(TP+TN)/(TP+TN+FN+FP);
%MCC(k)=(TP*TN-FP*FN)/sqrt((TP+FP)*(TP+FN)*(TN+FP)*(TN+FN));
%F1(k)=2*TP/(2*TP+FP+FN);
pre_right(k)=count/test_num;
disp(pre_right(k));
end
P=mean(pre_right);
end
disp('十折交叉的平均正確率為:');
disp(P);
%plot(ACC,MCC,'r->');


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM