Using PCA output coefficients to project test data in the pca space

1 view (last 30 days)
Hello,
I have this code to train a model :
%Classification Knn
%
[u,xp,v]=pca(zscore(Meilleurs_Conc_cas1));
model_knn_cas1=fitcknn(xp,EspAppr_Hypno_cas1);
Meilleurs_Conc_cas1 is my entry data of 110300x456 double
u is 450x450 double
v is 450x1 double
the projected data using pca is called xp.
What Im trying to do is use the outputs of pca to normalize some test data and then project the test data in the pca space using u and v (the outputs).
To normolize : in principal ==>normolizedTestData=(TestData-u)/v thats the formula to do it.
for k=1:size(EspTest_Mat_cas1,1)
for k1=1:size(EspTest_Mat_cas1,2)
EspTest_Mat_cas1_norm(k,:)=[EspTest_Mat_cas1_norm;((EspTest_Mat_cas1(k,:)-u(:,k1)./v(k1,:)))];
end
end
the error im having is "Subscripted assignment dimension mismatch."
First question ==> can someone please show me how the normalization supposed to be done in the loop please ?

Answers (1)

Riya
Riya on 11 Feb 2025
Hi Mohamad,
I understand that you are facing an error while trying to normalize and project your test data into the PCA space.
This error usually arises from incorrect normalization and indexing in your loop. Instead of using loops, you can normalize the data by applying the mean and standard deviation from the training data as follows:
mu = mean(Meilleurs_Conc_cas1, 1);
sigma = std(Meilleurs_Conc_cas1, 0, 1);
EspTest_Mat_cas1_norm = (EspTest_Mat_cas1 - mu) ./ sigma;
xp_test = EspTest_Mat_cas1_norm * u;
This ensures that the test data is standardized before being projected using the PCA coefficients.
Since MATLAB is optimized for matrix operations, it is better to use vectorized computation instead of loops.
For reference, here are the documentation links for mean and standard deviation in MATLAB:
Thanks!

Categories

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

Products


Release

R2017a

Community Treasure Hunt

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

Start Hunting!