PCA for Machine Learning: Project 2D Data onto Principal Components by Hand
Follow one complete PCA calculation from four raw points to centred data, principal-component scores, explained variance, and one-component reconstruction error.
KnowledgeGate Team
Exam prep & CS education

PCA turns centred features into orthogonal directions ordered by variance, but a one-call library hides how the mean, covariance matrix, eigenvectors, scores and reconstruction error connect. For A=(5,6), B=(1,2), C=(4,3) and D=(2,5), centring and eigendecomposition produce both principal-component axes and every projected score. PC1 points along (1,1)/sqrt(2), retains 80% of the sample variance, and leaves a total one-component reconstruction squared error of 4.
1. PCA finds orthogonal directions of maximum variance
Principal component analysis is an unsupervised linear transformation of centred features and does not use target labels. PC1 is the unit direction of greatest projected variance. PC2 is the greatest-variance unit direction orthogonal to PC1.
Keep three objects separate. A loading u_j is a direction in feature space. A score z_ij locates observation i along it. An eigenvalue lambda_j is that score column's sample variance. PCA retains score columns, rather than deleting original features independently.
The calculation chain is:
Centre the data:
X_c = X - 1 mu^T.Calculate sample covariance:
S = X_c^T X_c/(n-1).Solve
S u_j = lambda_j u_jand sort eigenpairs by decreasing eigenvalue.Project onto the first
kaxes:Z_k = X_c U_k.
The Skill Development Courses catalogue groups wider applied AI and machine-learning study paths.
2. Centre the four points and build the covariance matrix
The feature means are mu_x=(5+1+4+2)/4=3 and mu_y=(6+2+3+5)/4=4, so mu=(3,4).
Point | Original (x,y) | Centred (x-mu_x, y-mu_y) | x_c^2 | x_c y_c | y_c^2 |
|---|---|---|---|---|---|
A | (5,6) | (2,2) | 4 | 4 | 4 |
B | (1,2) | (-2,-2) | 4 | 4 | 4 |
C | (4,3) | (1,-1) | 1 | -1 | 1 |
D | (2,5) | (-1,1) | 1 | -1 | 1 |
The centred columns pass a quick audit: 2-2+1-1=0 and 2-2-1+1=0. Skipping centring would measure spread around the origin, not around the data mean.
The product columns sum to sum x_c^2=10, sum x_c y_c=6 and sum y_c^2=10. Therefore
X_c^T X_c=[[10,6],[6,10]]
and, because n-1=3,
S=(1/3)[[10,6],[6,10]]=[[10/3,2],[2,10/3]].
The diagonal entries are the two feature variances. The off-diagonal value 2 is their positive covariance. The earlier Covariance and Correlation for Machine Learning guide owns pairwise relationship interpretation, units and scatter-plot judgement. Here the covariance matrix feeds eigendecomposition, projection and reconstruction.

3. Solve the covariance eigenpairs and rank the components
Start with the determinant:
det(S-lambda I)=(10/3-lambda)^2-4=0.
Thus 10/3-lambda=+2 or -2, giving eigenvalues 4/3 and 16/3. PCA orders them by variance, so lambda1=16/3 and lambda2=4/3.
For lambda1=16/3, solving (S-lambda1 I)u=0 gives equal coordinates. Normalisation gives u1=(1,1)/sqrt(2). For lambda2=4/3, the coordinates are opposite, giving u2=(1,-1)/sqrt(2). Check that u1^T u2=(1-1)/2=0 and u1^T u1=u2^T u2=1. The Linear Algebra for GATE CS guide develops the wider eigenvalue foundation behind this step.
Total variance is lambda1+lambda2=20/3. PC1 explains (16/3)/(20/3)=16/20=0.80, while PC2 explains (4/3)/(20/3)=4/20=0.20. Software may return -u1 or -u2. Negating an eigenvector negates its scores, but distances, variance ratios and reconstructed points stay unchanged.
4. Project every observation onto PC1 and PC2
Each score is a dot product: z_i1=x_ci^T u1 and z_i2=x_ci^T u2. For A,
(2,2) dot (1,1)/sqrt(2)=4/sqrt(2)=2sqrt(2),
while (2,2) dot (1,-1)/sqrt(2)=0. For a second sign check, C gives (1,-1) dot u2=2/sqrt(2)=sqrt(2).
Point | PC1 score z1 | PC2 score z2 |
|---|---|---|
A |
|
|
B |
|
|
C |
|
|
D |
|
|
Keeping only PC1 produces the one-column reduced matrix Z_1=[2sqrt(2), -2sqrt(2), 0, 0]^T. A and B remain separated along the high-variance direction. C and D collapse to the same retained score 0 because their entire difference lies along the discarded PC2 direction.
5. Reconstruct the 2D points and measure exactly what PCA loses
One-component reconstruction uses x_hat_i = mu + z_i1 u1.
Point | PC1 score | One-PC reconstruction | Squared error |
|---|---|---|---|
A |
| (5,6) | 0 |
B |
| (1,2) | 0 |
C |
| (3,4) | 2 |
D |
| (3,4) | 2 |
C has retained score 0, so it reconstructs to the mean (3,4). Its error relative to (4,3) is (1,-1), with squared length 1^2+(-1)^2=2. D has error (-1,1) and the same squared length. Total reconstruction squared error is 0+0+2+2=4.
The geometric and variance views agree. Discarded sample variance is lambda2=4/3; multiplying by n-1=3 gives discarded sum of squares (n-1)lambda2=4. Keeping both components reconstructs every point exactly because U=[u1,u2] is an orthonormal basis. Retaining 80% of feature variance does not promise 80% predictive accuracy or 80% of task-relevant information.

6. Fit PCA safely inside a machine-learning pipeline
Split observations into training, validation and test sets first. Fit any imputer and scaler only on training data, then fit PCA only on the transformed training features. Apply those learned transformations unchanged to validation, test and future observations. Fitting a mean, scale or principal axis on all data leaks evaluation information.
For a new point E=(5,3), use the fixed training mean and loading. Centring gives (2,-1), so z_E1=(2-1)/sqrt(2)=1/sqrt(2) approx 0.707. Its one-PC reconstruction is (3,4)+(1/sqrt(2))(1,1)/sqrt(2)=(3,4)+(0.5,0.5)=(3.5,4.5). Do not recompute the mean or axes with E.
Scaling is a modelling decision. Covariance-based PCA is sensitive to units, so a numerically large scale can dominate. Standardising training features asks PCA about variance after unit scaling, which is a different question. Preserve raw scale when its variance is meaningful. Standardise when unlike units would make comparison misleading. Use domain meaning and downstream validation to decide.
Choose k by examining cumulative explained variance, reconstruction error and downstream validation performance, not a universal cutoff. Here k=1 gives 80% cumulative explained variance and total squared reconstruction error 4; k=2 gives 100% and zero error.
7. PCA traps and assessment-style checks
Wrong move | What goes wrong | Correct move |
|---|---|---|
Skip centring | Origin replaces the mean | Subtract the training mean |
Mix | Eigenvalues become inconsistent | State the convention |
Sort smallest first | PC1 is wrong | Sort descending |
Use unnormalised eigenvectors | Scores have arbitrary scale | Normalise each loading |
Reject a sign flip | An equivalent solution looks wrong | Flip its scores too |
Read | Variance is confused with prediction | Validate the model |
Fit before splitting | Evaluation data leaks | Fit on training data |
Standardise blindly, or never | Units or meaningful scale are ignored | Use meaning and validation |
Four checks make the arithmetic durable:
A: Population covariance
X_c^T X_c/ngives eigenvalues4and1;u1,u2and the80/20ratio stay unchanged.B: PC2 alone gives
[0,0,sqrt(2),-sqrt(2)]and retains20%of variance.C: Both components give C as
mu+0u1+sqrt(2)u2=(3,4)+(1,-1)=(4,3).D: With
-u1, A's score is-2sqrt(2), but their product reconstructs the same point.
The steps worth rehearsing are centring, the covariance convention, the maximum-variance eigenvector, the scores, cumulative explained variance, reconstruction, leakage, scaling, and the gap between feature variance and supervised performance. Probability for GATE CS covers the distributions and expectation work that sits beside this variance arithmetic.
8. PCA short version and the next step
Centre the training features.
Calculate the covariance matrix under a declared convention.
Find orthonormal eigenvectors.
Sort them by descending eigenvalue.
Project onto the first
k.Validate what the discarded components cost.
Here u1=(1,1)/sqrt(2), scores are [2sqrt(2),-2sqrt(2),0,0], 80% of variance remains, and reconstruction squared error is 4. Now hide the tables, recover mu=(3,4) and X_c^T X_c=[[10,6],[6,10]], then explain why C and D share one PC1 score. Reproduce the four scores by hand, then implement the same fit-on-training and transform-only workflow in code. The Artificial Intelligence (AI) course is the taught route through this wider applied machine-learning ground.
Keep learning
Probability Distributions for Machine Learning: Match Bernoulli, Binomial, Normal and Poisson to Data
Learn a reusable way to match binary outcomes, grouped successes, event counts and continuous residuals to a defensible probability model.
Hypothesis Testing for Machine Learning: Separate Signal from Sampling Noise in Model Comparisons
Learn one complete paired-model comparison, from a 2 by 2 prediction table and exact p-value to effect size, confidence interval, test choice, and leakage checks.
Covariance and Correlation for Machine Learning: Read Feature Relationships Correctly
Calculate covariance and Pearson correlation by hand, then see how units, influential points and nonlinear patterns change what the numbers mean.
Conditional Probability for Machine Learning: Bayes' Rule with a Worked Classifier Example
Follow one hypothetical classifier from conditional probability to Bayes' posterior. Verify the answer with natural frequencies, compare precision with recall, and see exactly what a stricter threshold changes.





