Clear Filters
Clear Filters

SAMPLE and TRAINING must have the same number of columns. after using pca

2 views (last 30 days)
load featurs_T
load featurs_S
load Group_Train
load Group_Test
%{
cv_x=cov(Feat1);
[V,D] = eig(cv_x);
d=diag(D);
d=d(end:-1:1);
sm_d=cumsum(d) /sum(d);
idx=find(sm_d>0.99);
T=[V(:,end:-1:idx(1))]';
new_feat1=T*Feat1';
%TrainingSet= new_feat1';
new_feat2=T*Feat2';
%TestSet= new_feat2';
TrainingSet = new_feat1';
TestSet = new_feat2';
%}
Feat1= Feat1';
Feat2= Feat2';
Group_Train1 = Group_Train1';
Group_Test1 = Group_Test1';
%}
Feat1 = pca(Feat1);
Feat2 = pca (Feat2);
%------------------------
%}
% result1= multisvm(TrainingSet,Group_Train1,TestSet,Group_Test1);
result= classify(Feat2,Feat1,Group_Train1,'diaglinear');
%testresult = result1;
Accuracy = mean(Group_Test1==result) * 100;
fprintf('Accuracy = %.2f\n', Accuracy);
fprintf('error rate = %.2f\n ', mean(result ~= Group_Test1 ) * 100);
Error using classify (line 153)
SAMPLE and TRAINING must have the same number of columns.
Error in HOG2 (line 32)
result= classify(Feat2,Feat1,Group_Train1,'diaglinear');
After using pca the matrix dimensions change
Feat1= 1032*1032
Feat2 =109*109
result = 1032*1

Answers (1)

Ayush Aniket
Ayush Aniket on 28 Aug 2024
The error you are encountering indicates a mismatch in the number of columns between your SAMPLE (test data) and TRAINING (training data) matrices when using the classify function. This is because after applying PCA, Feat1 and Feat2 no longer have the same number of features (columns).
You need to apply the same PCA transformation to both your training and test datasets to ensure they have the same feature dimensions. When you perform PCA, you should retain the same number of principal components for both datasets. This can be done by applying the PCA transformation derived from the training set to the test set as shown below:
% Perform PCA on the training data
[coeff, score, ~, ~, explained] = pca(Feat1);
% Determine the number of components to retain based on explained variance
explainedVarianceThreshold = 0.99;
cumulativeVariance = cumsum(explained) / sum(explained);
numComponents = find(cumulativeVariance >= explainedVarianceThreshold, 1);
% Reduce dimensionality of training data
TrainingSet = score(:, 1:numComponents);
% Apply the same PCA transformation to the test data
TestSet = (Feat2 - mean(Feat1)) * coeff(:, 1:numComponents);
% Perform classification
result = classify(TestSet, TrainingSet, Group_Train1, 'diaglinear');
This approach ensures that your training and test datasets are compatible for classification after dimensionality reduction with PCA.

Categories

Find more on Dimensionality Reduction and Feature Extraction in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!