我看很多博主都是很老的MATLAB版本了,这里用了高版本的函数fitcecoc进行SVM多分类
下载链接https://download.csdn.net/download/qq_45047246/63960845?spm=1001.2014.3001.5503
clc;
clear all;
% load data
x_train=LoadMNISTImages('train-images-idx3-ubyte');
x_test=LoadMNISTImages('t10k-images-idx3-ubyte');
y_train=LoadMNISTLabels('train-labels-idx1-ubyte');
y_test=LoadMNISTLabels('t10k-labels-idx1-ubyte');
% After transposing, each image becomes a number * pixel matrix
x_train=x_train';
x_test=x_test';
%% SVM
t = templateSVM('Standardize',true)
SVMMdl = fitcecoc(x_train,y_train,'Learners',t,...
'ClassNames',{'0','1','2','3','4','5','6','7','8','9'});
predict_label = predict(SVMMdl,x_test);
s=0;
for i=1:length(predict_label)
if str2double(predict_label(i))==y_test(i)
s=s+1;
end
end
acc=s/length(predict_label)
figure
plot(str2double(predict_label),'b*')
hold on;
plot(y_test,'ro')
hold on;
legend('predict_label','real_label')
title('SVM Model')
figure
confusionchart(str2double(predict_label)',y_test')
title('SVM Model Confusion matrix')
参考其他博主的加载数据的函数
function labels = LoadMNISTLabels(filename)
% read label
fp = fopen(filename,'rb');% Read files in binary mode
assert(fp~=-1,['Could not open',filename,'']);
magic = fread(fp,1,'int32',0,'ieee-be');% Read data from binary file
assert(magic==2049,['Bad magic number in',filename,'']);
numlabels = fread(fp,1,'int32',0,'ieee-be');% Number of labels obtained
labels = fread(fp,inf,'unsigned char');
assert(size(labels,1)==numlabels,'Mismatch in label count');
fclose(fp);% Close file
end
function images = LoadMNISTImages(filename)
% Read image data in data
fp = fopen(filename,'rb');% Read files in binary mode
assert(fp~=-1,['Could not open',filename,'']);
% assertFunction to determine whether the conditions are met. If the conditions are not
% met, an error message is reported
magic = fread(fp,1,'int32',0,'ieee-be');% Read data from binary file
assert(magic==2051,['Bad magic number in',filename,'']);
%In MNIST image dataset, if the magic value is 2051, an error will be reported if it is
% not 2051
numimages = fread(fp,1,'int32',0,'ieee-be');% Number of images obtained
numrows = fread(fp,1,'int32',0,'ieee-be');% row
numcols = fread(fp,1,'int32',0,'ieee-be');% column
images = fread(fp,inf,'unsigned char');
% Read all the remaining pixel data with the precision of "unsigned char" and store it in % the column vector images
images = reshape(images,numcols,numrows, numimages);
images = permute(images,[2 1 3]);
% Rearrange the dimensions of the previous three-dimensional array to obtain a three-
% dimensional matrix composed of all image data with 28 * 28 * number of images
fclose(fp);% Close file
images = reshape(images,size(images,1)*size(images,2),size(images,3));
% Convert to two-dimensional vector
images = double(images/255);
% convert to double and rescale to [0,1]
end