Как лучше изменить процент обучения и тестирования во время процесса разделения? - PullRequest
1 голос
/ 10 апреля 2020

Используя метод PCA и базу данных Yale , я пытаюсь работать с распознаванием лиц в Matlab путем случайного разделения процесса обучения на 20% и процесса тестирования на 80%. Он получает

Индекс в позиции 2 превышает границы массива (не должен превышать 29)

ошибка. Ниже приведен код, в надежде получить помощь:

dataset = load('yale_FaceDataset.mat');

trainSz = round(dataset.samples*0.2);
testSz = round(dataset.samples*0.8);

trainSetCell = cell(1,trainSz*dataset.classes);
testSetCell = cell(1,testSz*dataset.classes);

j = 1;
k = 1;
m = 1;
for i = 1:dataset.classes
    % training set
    trainSetCell(k:k+trainSz-1) = dataset.images(j:j+trainSz-1);
    trainLabels(k:k+trainSz-1) = dataset.labels(j:j+trainSz-1);
    k = k+trainSz;
    % test set
    testSetCell(m:m+testSz-1) = dataset.images(j+trainSz:j+dataset.samples-1);
    testLabels(m:m+testSz-1) = dataset.labels(j+trainSz:j+dataset.samples-1);
    m = m+testSz;
    j = j+dataset.samples;
end
% convert the data from a cell into a matrix format
numImgs = length(trainSetCell);
trainSet = zeros(numImgs,numel(trainSetCell{1}));
for i = 1:numImgs
    trainSet(i,:) = reshape(trainSetCell{i},[],1);
end
numImgs = length(testSetCell);

testSet = zeros(numImgs,numel(testSetCell{1}));
for i = 1:numImgs
    testSet(i,:) = reshape(testSetCell{i},[],1);
end


%% applying PCA
% compute the mean face
mu = mean(trainSet)';

% centre the training data
trainSet = trainSet - (repmat(mu,1,size(trainSet,1)))';

% generate the eigenfaces(features of the training set)
eigenfaces = pca(trainSet);

% set the number of principal components
Ncomponents = 100;

% Out of the generated components, we keep "Ncomponents"
eigenfaces = eigenfaces(:,1:Ncomponents);

% generate training features
trainFeatures = eigenfaces' * trainSet';

% Subspace projection
% centre features
testSet = testSet - (repmat(mu,1,size(testSet,1)))';

% subspace projection
testFeatures = inv(eigenfaces'*eigenfaces) * eigenfaces' * testSet';

mdl = fitcdiscr(trainFeatures',trainLabels);
labels = predict(mdl,testFeatures');


% find the images that were recognised and their respect. labels
correctRec = find(testLabels == labels');
correctLabels = labels(correctRec);

% find the images that were NOT recognised and their respect. labels
falseRec = find(testLabels ~= labels');
falseLabels = labels(falseRec);


% compute and display the recognition rate
result = length(correctRec)/length(testLabels)*100;
fprintf('The recognition rate is: %0.3f \n',result);

% divide the images into : recognised and unrecognised
correctTest = testSetCell(correctRec);
falseTest = testSetCell(falseRec);

% display some recognised samples and their respective labels
imgshow(correctTest(1:8),correctLabels(1:8));

% display all unrecognised samples and their respective labels
imgshow(falseTest(1:length(falseTest)), falseLabels(1:length(falseTest)));

1 Ответ

1 голос
/ 10 апреля 2020

было бы неплохо, если бы вы указали также номер строки и полное сообщение об ошибке, и если бы вы разделили свой код до необходимого. Я думаю, PCA-вещи здесь не нужны, так как ошибка возникает, вероятно, в вашем l oop. Это потому, что вы увеличиваете j на j = j+dataset.samples; и берете это в следующем наборе l oop для индексации j:j+trainSz-1, которое теперь должно превышать dataset.samples ...

Тем не менее, есть нет случайности в индексации. Проще всего использовать встроенную функцию cvpartition:

% split data 
cvp = cvpartition(Lbl,'HoldOut',.2);
lgTrn = cvp.training;
lgTst = cvp.test;

В качестве первого ввода вы можете указать количество классов (в данном случае Lbl) или фактический вектор класса, позволяющий cvpartition выбирать случайные подмножества, отражающие исходное распределение отдельных классов.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...