trainset = zeros(112*92,200); % image size is : 112*92
testset = zeros(112*92,200); % image size is : 112*92
train_label=zeros(200,1);
test_label=zeros(200,1);
averagerate=zeros(120,1);
sumrate=zeros(120,1);
errorrate=zeros(120,1);
errorRate=zeros(120,5);
% number of samples
n = 35; %size of the block
for iterator=1:5 %循环操作5次
randomset=randperm(10);
for a = 1:40 %读取训练集数据
for i = 1 : 5
img = imread(strcat('s',int2str(a),'/',int2str(randomset(i)), '.pgm'));
img = double(img);
trainset(:,i+a*5-5) = img(:);
train_label(i+a*5-5,1)=a; %增加训练集标签
end
end
for c= 1:40
for i = 6 : 10
img = imread(strcat('s',int2str(c),'/',int2str(randomset(i)), '.pgm'));
img = double(img);
a=randi([1,77],1);
b=randi([1,57],1); %随机确定遮挡块的位置
for j=a:a+n
for k=b:b+n
img(j,k)=0;
end
end
testset(:,i+c*5-10) = img(:);
test_label(i+c*5-10,1)=c; %增加测试集标签
end
end
for dimension=1:120
[W,H]=nnmf(trainset,dimension); %对训练集做nmf分解
train_trans=H';
test_trans=(pinv(W)*testset)';
mdl = fitcknn(train_trans,train_label); %KNN分类器
[label] = predict(mdl,test_trans);
count = 0;
error=test_label-label; %计算错误率
for i=1:200
if error(i,1)==0
count=count+1;
end
end
errorrate(dimension,1)=1-count/200; %计算每一次错误率
end
errorRate(:,iterator)=errorrate(:,1);
sumrate=sumrate+errorrate; %5次错误率相加
end
averagerate=sumrate/5; %计算平均错误率