PCA (Principal Component Analysis) is a technique that reduces the number of variables in a dataset while keeping most of the information. Instead of 100 columns, you can end up with 10 that summarize the essentials.
How it works
Many variables in a dataset are similar to each other. PCA finds new directions, called principal components, that capture the greatest variation in the data.
The general steps are:
- Normalize the data so all variables are on the same scale.
- Calculate how the variables vary together.
- Find the components, ordered from the one that explains the most variation to the one that explains the least.
- Keep only the first components and discard the rest.
The first component captures the largest part of the variation, the second captures the largest part of what remains, and so on. The new components are combinations of the original variables, so they lose direct interpretability.
Practical example
A company has 50 measures about each customer's behavior in the app. Training a model with that many columns is slow and confusing. With PCA, it can reduce to 8 components that preserve, for example, 90% of the variation.
In Python:
from sklearn.decomposition import PCA
pca = PCA(n_components=0.90)
X_reduzido = pca.fit_transform(X_normalizado)With n_components set to 0.90, the library chooses how many components are needed to keep 90% of the variation.
What it's used for
PCA is used for:
- Speeding up machine learning models with fewer variables.
- Visualizing high dimensional data in a 2D or 3D plot.
- Removing noise and redundancy.
- Preparing data for algorithms that are sensitive to the number of dimensions, such as KNN and K-means.
Limits of PCA
It only captures linear relationships between variables. More complex relationships may require other techniques. In addition, components are harder to explain than the original columns, which can be a problem when you need to justify a model's decision.
Another caution: normalization is mandatory in practice. Without it, variables with large numbers dominate the result.