其他分享
首页 > 其他分享> > 1

1

作者:互联网

clear     %清除工作空间所有变量
close all %关闭所有figure窗口
clc       %清除命令窗口的内容,对工作环境中的全部变量无任何影响
%PCA_SVM包含求标签和PCA过程
%% %1 数据加载
load('data.mat');
%% %2 求标签H
samples = 5120;  % 明文数
D = textin(1:samples,1);
clear textin byte_to_attack
K = keylist(1:samples);
H1 = HW(s(bitxor(D',K)+1)+1);
H=H1';
%% %3 数据PCA
[coeff, score, latent, tsquared, explained, mu]=pca(traces);
a=cumsum(latent)./sum(latent);
idx=find(a>0.9);  
k=idx(1);
pcaData=score(:,1:k);%143
%% %4 SVM模型训练
H=H(1:5000);
label=double(H);
traces1= pcaData((1:5000),:);
% 1. 随机产生训练集和测试集
n = randperm(size(traces1,1));
% 2. 训练集——4500个样本
train_matrix = traces1(n(1:4500),:);
train_label = label(n(1:4500),:);
% 3. 测试集——500个样本
test_matrix = traces1(n(4501:end),:);
test_label = label(n(4501:end),:);
%SVM创建/训练(RBF核函数)
% 1. 寻找最佳c/g参数——交叉验证方法
% [c,g] = meshgrid(0:0.2:10,-10:0.2:10);
% [m,n] = size(c);
% cg = zeros(m,n);
% eps = 10^(-4);
% v = 3;
% bestc = 1;
% bestg = 0.1;
% bestacc = 0;
% for i = 1:m
%     for j = 1:n
%         cmd = ['-v ',num2str(v),' -t 0',' -c ',num2str(2^c(i,j)),' -g ',num2str(2^g(i,j))];
%         cg(i,j) = svmtrain(train_label,train_matrix,cmd);     
%         if cg(i,j) > bestacc
%             bestacc = cg(i,j);
%             bestc = 2^c(i,j);
%             bestg = 2^g(i,j);
%         end        
%         if abs( cg(i,j)-bestacc )<=eps && bestc > 2^c(i,j) 
%             bestacc = cg(i,j);
%             bestc = 2^c(i,j);
%             bestg = 2^g(i,j);
%         end               
%     end
% end
%cmd = [' -t 2',' -c ',num2str(bestc),' -g ',num2str(bestg)];
cmd = [' -t 2',' -c ',num2str(100),' -g ',num2str(0.3),'-v',num2str(3)];
% 2. 创建/训练SVM模型
model = svmtrain(train_label,train_matrix,cmd);

%% 5 SVM仿真测试
[predict_label_1,accuracy_1,prob_estimates] = svmpredict(train_label,train_matrix,model);
[predict_label_2,accuracy_2,prob_estimates2] = svmpredict(test_label,test_matrix,model);
result_1 = [train_label predict_label_1];
result_2 = [test_label predict_label_2];
%% 绘图
figure
plot(1:length(test_label),test_label,'r-*')
hold on
plot(1:length(test_label),predict_label_2,'b:o')
grid on
legend('真实类别','预测类别')
xlabel('测试集样本编号')
ylabel('测试集样本类别')
string = {'测试集SVM预测结果对比(RBF核函数)';
          ['accuracy = ' num2str(accuracy_2(1)) '%']};
title(string)

  

标签:,SVM,%%,label,train,num2str,test
来源: https://www.cnblogs.com/chacaxx/p/16205091.html