- Learn
- Computer Science & IT
- Data Science & AI
- Machine Learning
- Principal Component Analysis
Principal Component Analysis and Dimensionality Reduction
IntermediateLesson 9 of 9 in Machine Learning Course
What you will learn
- Describe what makes high-dimensional data hard to work with, what dimensionality reduction does about it, and how variance and covariance describe the spread that principal component analysis summarizes.
- Explain why reducing dimensions helpsRecognize high-dimensional data, the practical problems it causes, and the difference between selecting features and building new ones.
- Describe the spread of data with variance and covarianceCenter a data matrix, compute variances, covariances and a covariance matrix, and find the variance of the data along a chosen direction.
- Explain why reducing dimensions helps
- Define principal components as directions of maximum variance, compute them from a covariance or correlation matrix, and read loadings, scores and biplots.
- Describe principal components as directions of maximum varianceDefine a principal component, its loading vector and its scores, and explain the geometry that distinguishes it from a regression line.
- Compute components from the covariance matrixFind loading vectors as eigenvectors and component variances as eigenvalues of the covariance or correlation matrix, and check the results.
- Interpret loadings, scores and biplotsRead what each component measures from its loadings, compute and explain an observation's score, and read a biplot.
- Describe principal components as directions of maximum variance
- Decide when to standardize variables before PCA, explain how the choice changes the result, and recognize the kinds of data and questions where PCA misleads.
- Decide whether to standardize before PCAExplain why variables on different scales dominate unstandardized PCA, show the effect with numbers, and choose between covariance-based and correlation-based PCA.
- Recognize when PCA misleadsIdentify the assumptions behind PCA and the situations where it summarizes data poorly, and choose a sensible response.
- Decide whether to standardize before PCA
- Compute explained variance, use scree plots and selection rules to choose the number of components, and measure what is lost by reconstructing the data.
- Calculate and read explained varianceCompute the proportion and cumulative proportion of variance explained by components, and read them correctly.
- Choose the number of components with scree plots and rulesDraw and read a scree plot and a cumulative plot, apply the elbow, threshold and eigenvalue-greater-than-one rules, and choose the number of components for the purpose at hand.
- Reconstruct data and measure what is lostRebuild observations from a few components, compute the reconstruction error, and relate it to the discarded variance and to compression and noise reduction.
- Calculate and read explained variance
- Run PCA with scikit-learn, plot high-dimensional data in two dimensions, and use PCA as a preprocessing step inside a leak-free modeling workflow.
- Run PCA with scikit-learn and read its outputStandardize and fit PCA in scikit-learn, and read loadings, explained variance and scores from the fitted object.
- Visualize high-dimensional data with component scoresPlot observations on their first two or three principal components, label the axes honestly, and read clusters, outliers and distances with the right caution.
- Use PCA as a preprocessing step without leakagePlace standardization and PCA inside a pipeline, fit them on training data only, tune the number of components, and judge whether PCA helps the model.
- Run PCA with scikit-learn and read its output
- Explain in outline how t-SNE and UMAP build two-dimensional maps of high-dimensional data, read their plots without overinterpreting them, and choose between PCA, t-SNE and UMAP.
- Explain what t-SNE shows and how to read its plotsDescribe the idea behind t-SNE and its perplexity setting, read t-SNE plots with the right cautions, and use it in a sound workflow.
- Explain UMAP and choose a method for the taskDescribe the idea behind UMAP and its main settings, compare it with t-SNE and PCA, and choose a method to fit the purpose.
- Explain what t-SNE shows and how to read its plots
Principal Component Analysis study guide
1Explain why and how data dimensions are reduced
Many data tables contain repeated information across their columns. A smaller set of coordinates can make the patterns easier to see and the data cheaper to use, but useful differences can also disappear. Start by separating feature selection from feature extraction, then measure the spread around the mean with variance and covariance. Those measurements give PCA a precise way to choose which directions to retain.
1.1 Fewer coordinates, useful structure
A data table describes points. Each row is an observation, and each measured feature supplies one coordinate. With 64 pixel values, an image is a point in 64 dimensions, even though the image itself fits on a flat screen.
Why many features become difficult
The dimension is the number of features, , not the number of observations, . An grayscale image has 64 features when every pixel is a column. Adding more images increases the number of rows; it does not change those 64 coordinates.
More coordinates give a model more ways to distinguish observations, but also spread the observations through a larger space. Local neighborhoods can become surprisingly wide. For points spread uniformly through a unit cube, a smaller cube containing 10% of the points needs edge length
This is 0.1 in one dimension, about 0.316 in two, and about 0.794 in ten. In ten dimensions, covering just a tenth of the observations already requires almost 80% of the range of every axis. Distance-based methods such as nearest neighbors can struggle because “nearby” points are no longer very local. This is one aspect of the curse of dimensionality.
What a smaller representation can keep
Dimensionality reduction replaces many coordinates with fewer coordinates. It can make a plot possible, reduce storage and calculation time, combine repeated information, or remove some noise. These purposes need different judgments of success. A useful picture need not be the best input to a predictor.
Suppose adult height and arm span, both in centimeters, are strongly correlated. One score can summarize overall size; another can describe differences in proportion. Keeping only the size score compresses the data, but removes those proportion differences. Whether that loss matters depends on the question.
| Approach | What remains | What a new observation needs |
|---|---|---|
| Feature selection | A subset of named original columns | Those selected measurements |
| Feature extraction | New coordinates built from the original columns | The measurements used to compute those coordinates |
PCA is feature extraction. Its components are weighted sums, normally involving all original features. Keeping two components does not mean that only two original measurements are needed for a new observation.
Linear and nonlinear reductions
PCA uses a flat line, plane, or higher-dimensional subspace through the data's center. The coordinates are projections onto that subspace. Keeping fewer components loses information unless all the data already lie in that smaller flat space.
Curved structure can need a different representation. Points on a known circle can be identified by one angle, but projecting the circle onto a straight line overlaps different points. Nonlinear methods such as t-SNE and UMAP build maps that emphasize nearby points. Their map coordinates have a different interpretation from PCA scores.
In the workflows here, these methods learn from the features without a target label: they are unsupervised. UMAP also has a supervised mode. An unsupervised representation can preserve a great deal of feature variation while discarding the small differences that best predict a target.
Key Takeaways
- Dimension counts features, not observations.
- Feature selection keeps columns; PCA extracts weighted combinations.
- Reduction can help visualization, computation, storage, and noise filtering.
- PCA preserves linear variation, which may differ from predictive information.
1.2 Measure spread around the mean
PCA needs a numerical description of how observations spread out together. Variance measures spread in one column. Covariance measures whether deviations in two columns tend to have the same sign.
Center each column
Write the table as an matrix . Entry is observation 's value for feature . Centering subtracts each column mean, placing the average observation at the origin without changing differences between observations.
For five observations, take and . The means are 10 and 5. Subtract them to get the points . PCA will describe spread around this mean point, not distance from the original coordinate origin.
Build the covariance matrix
The sample variance and covariance use the same denominator:
For the first column, the squared deviations sum to , so its variance is . For the second, they sum to 8, giving variance 2. The cross-products sum to , giving covariance 2.
Place variances on the diagonal and covariances off the diagonal:
The matrix is symmetric because reversing the order of multiplication leaves covariance unchanged. Its diagonal sum, called the trace, is the total variance: . The correlation divides covariance by both standard deviations: . The correlation matrix has 1 on each diagonal entry for nonconstant features.
Measure variance in a new direction
Choose a unit vector and take each centered point's dot product with it. The resulting coordinates have variance . Requiring length 1 makes directions comparable: otherwise multiplying a vector would multiply the spread without changing its direction.
Along , variance is 5. Along the diagonal , it is
Along , it is
The diagonal is better than the horizontal direction, but another direction captures still more spread. PCA finds the maximum.
Keep units in view
Converting meters to centimeters multiplies values by 100, variance by 10,000, and covariance with an unchanged column by 100. Correlation stays unchanged. A covariance matrix therefore records both relationships and measurement scales. The decision to standardize changes which spread PCA treats as large.
Key Takeaways
- Centering subtracts column means before measuring directions.
- Sample variance and covariance divide by the number of observations minus one.
- The covariance matrix is symmetric, with variances on its diagonal.
- Total variance is the diagonal sum.
- Variance along a unit direction is ; units affect its value.
2Find principal components and interpret them
PCA turns variation into new axes. The first axis captures the most spread, and later axes capture what remains along perpendicular directions. A small covariance matrix makes the calculation visible: its eigenvectors give the directions and its eigenvalues give their variances. Loadings, observation scores, and carefully scaled biplots then connect the calculation back to the measured features.
2.1 Find the direction with the most variation
A principal component gives observations a new coordinate. Its direction tells you how the original features are combined; its scores tell you where individual observations fall along that direction.
Define the first component
For centered features, write
The weights are loadings, collected in a loading vector . PCA chooses the unit-length loading vector that makes the variance of this combination as large as possible. The constraint is . Without it, multiplying every weight by 100 would multiply the variance by 10,000, so there would be no largest value.
The score of observation is
Subtract the mean first, then multiply each centered feature by its loading and add. A score is a coordinate of an observation; a loading is a weight attached to a feature.
For the five centered points , use . The first point scores . The remaining scores are about −0.894, 0, 1.789, and 2.683. Their sample variance is 6.
Add new, uncorrelated coordinates
PC2 has the greatest remaining variance with its loading vector perpendicular to PC1. PC3 is perpendicular to both, and the process continues. Orthogonal describes these perpendicular directions. Scores on distinct components have zero covariance, so they are uncorrelated. Uncorrelated scores need not be statistically independent.
Conceptually, there are component directions for features. Centering limits the number with nonzero variance to . With fewer observations than features, some directions contain no sample variation.
Connect spread with closest fit
Project a point perpendicularly onto the PC1 line through the mean. Its squared distance from the mean splits into squared distance along the line plus squared distance away from the line. The total is fixed. Maximizing the along-line spread therefore minimizes the total squared perpendicular residuals. The first two components give the corresponding best-fitting plane.
| Fit | How the residual is measured | Roles of the variables |
|---|---|---|
| PCA line | Perpendicular to the fitted line | All features enter symmetrically |
| Regression of y on x | Vertically along the y axis | y is the response; x is the predictor |
For the covariance matrix with variances 5 and 2 and covariance 2, the regression slope of y on x is . PC1's slope is . Reversing the regression gives yet another line; the different objectives explain the different answers.
A direction has two signs
The vectors and describe the same line. Reversing all loadings reverses all scores, leaving the fit and variance unchanged. If eigenvalues are exactly equal, even the directions within their shared subspace are not unique. A reproducible-looking sign alone is no evidence that two analyses disagree.
Key Takeaways
- PC1 maximizes score variance over unit-length loading vectors.
- Loadings describe features; scores describe observations.
- Component directions are orthogonal and their scores are uncorrelated.
- PCA minimizes perpendicular squared error; regression minimizes response-direction error.
- Signs can flip without changing a component.
- At most centered components have nonzero variance.
2.2 Calculate components from a small matrix
An eigenvector is a direction that a matrix maps to a multiple of itself. For a covariance matrix, these special directions are the principal component directions. Their eigenvalues measure the variance along them.
From matrix to component
The equation is . Normalize each eigenvector to length 1 and sort by decreasing eigenvalue. The largest eigenvalue belongs to PC1. An eigenvector solver's output order is not the definition of component order.
Start by centering the columns, and standardize if the analysis calls for it. Form the covariance matrix of those prepared data. Using sample standard deviations for standardization makes this the correlation matrix.
Solve the eigenvalues
For , subtract from the diagonal and set the determinant to zero:
Expand to get . Factoring gives , so the ordered eigenvalues are 6 and 1. The subtraction of 4 comes from the product of the two off-diagonal entries.
Solve and normalize the directions
For eigenvalue 6, the first row of gives . One solution is . Its length is , so
For eigenvalue 1, the first row gives . Choose and divide by :
Either vector can be multiplied by −1. Keeping the same eigenvalue with its vector is essential.
Check before using the scores
Three quick checks expose different mistakes:
- The eigenvalues sum to the diagonal sum: .
- Each direction has unit length: .
- Their dot product is zero: .
Multiply each centered row by these directions to obtain scores. For the five-point example, PC2 scores are about −0.447, 0.447, 0, 1.342, and −1.342. Their squared values sum to 4, giving sample variance . PC1 scores have variance 6, and the covariance between the two score columns is zero.
A useful correlation-matrix case
For two standardized features with positive correlation , the matrix has rows and . Its eigenvalues are and . The first direction averages the features with equal weights, , and the second contrasts them. When , PC1 explains . When , both variances are 1 and there is no preferred direction.
Software often computes the same result directly from the centered data matrix. The hand calculation shows why eigenvalues give variances; the loading entries themselves are weights, not percentages explained.
Key Takeaways
- Loading vectors are unit eigenvectors; component variances are eigenvalues.
- Sort eigenvalue–vector pairs by decreasing eigenvalue.
- Check the trace, vector lengths, and perpendicularity.
- For two standardized positively correlated features, eigenvalues are and .
2.3 Read what the components measure
A component becomes useful when its loading pattern can be connected to the measured features. Look at the signs and sizes together, then use the same weights to interpret individual scores.
Read a loading pattern
Consider a constructed teaching example with four standardized fitness measurements: push-ups in one minute, sit-ups in one minute, 5 km run time in minutes, and resting heart rate in beats per minute. PC1 has eigenvalue about 2.43 and loading vector
More push-ups and sit-ups raise the score. Longer run times and higher resting heart rates lower it. A high score therefore combines muscular endurance with faster running and a lower resting heart rate. These measurements motivate the name “overall fitness.”
Because the features are standardized, the magnitudes can be compared on a common scale. A near-zero loading on PC1 says little about that feature's relationship to other components. Without standardization, different units complicate comparisons of loading sizes.
Compute an observation's score
For standardized feature values , multiply by the matching loadings:
The contributions are 0.624, 0.450, 0.156, and −0.235. Adding gives 0.995 with the rounded loadings. The shorter-than-average run time raises the score because both its value and its loading are negative. The above-average resting heart rate pulls the score down.
PC2, with eigenvalue about 0.745 and loadings , combines muscular endurance with slower running and higher resting heart rate. It contrasts aspects of fitness that PC1 largely combines.
Distinguish weights from correlations
For variables standardized with sample standard deviations, the variable–component correlation is
For push-ups and PC1, . The weight 0.52 and correlation 0.81 answer different questions. Some software calls either quantity a “loading.” Check the table's definition; scikit-learn's components_ stores unit-vector weights.
Read biplot arrows with their scaling
A biplot combines observations as points and features as arrows. In a correlation biplot, arrow coordinates are the variable's correlations with PC1 and PC2, and the observation scores are rescaled correspondingly. Similar arrow directions suggest positive correlation; opposite directions suggest negative correlation. Long arrows indicate features represented well by the displayed plane. When substantial variation lies outside that plane, arrow angles give only a partial view of relationships.
Arrows drawn from unit loading entries alone have a different meaning. With two features those two row-vectors are perpendicular even if the features correlate strongly, so their angle cannot reveal the correlation.
Key Takeaways
- Interpret a component from the relative signs and sizes of its loadings.
- A score is the sum of matching feature–loading products.
- Variable–component correlations differ from unit-vector loadings.
- Biplot arrow meanings depend on the scaling used.
- A near-zero PC1 loading can coexist with a large loading on another component.
3Prepare data for PCA and recognize its limits
The shape PCA finds depends on the numbers it receives. A change from meters to centimeters can shift an unscaled analysis, while standardizing changes which differences count equally. Choosing that scale is part of the analysis. The same care is needed when the data contain outliers, missing entries, curved patterns, or a target whose useful signal lies in a low-variance direction.
3.1 Choose a meaningful scale
PCA looks for large variance. A large numerical spread can reflect a meaningful difference or simply a choice of units. Decide what one unit of variation should mean before fitting components.
Centering and standardizing do different jobs
Centering subtracts a mean. Standardizing also divides by a standard deviation:
With sample standard deviations, every nonconstant column then has mean 0 and sample variance 1. PCA on these columns uses their correlation matrix. PCA on centered, unscaled columns uses their covariance matrix. Both analyses center the data.
Watch a unit conversion change PC1
Suppose adult height has standard deviation 0.1 m, body mass has standard deviation 12 kg, and their correlation is 0.6. Height variance is 0.01, mass variance is 144, and their covariance is . The huge numerical difference in variances makes unscaled PC1 almost entirely mass: its loadings are about and its PVE exceeds 99.99%.
Now record the same heights in centimeters. Height standard deviation becomes 10 cm, its variance becomes 100, and covariance becomes 72. The observations have not changed, yet PC1 now has loadings about and PVE about 80.9%.
Standardizing removes this dependence on meters versus centimeters. Both standardized features have variance 1 and correlation 0.6, so the first direction is and explains . This is an equal-scale summary of the two features.
Decide from the meaning of variation
| Data situation | Sensible starting choice | Reason |
|---|---|---|
| Features in different units | Standardize | Unit choices should not set the weights |
| Different spreads with no useful meaning | Standardize | Give each feature a comparable starting scale |
| Same-unit features with meaningful variance differences | Consider centering only | Retain those differences in spread |
Pixel intensities all recorded on a 0–255 scale illustrate the last case. A nearly constant border pixel may contain little useful signal. Dividing by its tiny standard deviation can magnify noise until it has the same variance as an informative pixel. Standardizing every column by habit can therefore make the representation worse.
Keep preparation consistent
scikit-learn's PCA centers its input but does not standardize it. Put StandardScaler before PCA when scaling is appropriate. StandardScaler uses the standard deviation with denominator ; PCA reports sample variance with denominator . This creates a small common variance factor without changing the explained-variance ratios.
For prediction, learn means and scales from training data and reuse them unchanged. Re-estimating them on a test batch changes the coordinate system. Report whether scaling was used, because loadings, scores, and PVE depend on that choice.
Standardization also leaves outliers and skewness in place. A meaningful log transformation of a strongly right-skewed positive measurement can reduce the influence of extreme values before scaling. Check that the transformed measurement still answers the intended question.
Key Takeaways
- Centering changes the origin; standardizing also changes relative feature scales.
- Unscaled PCA can change when a measurement unit changes.
- Standardize different-unit tabular features; assess same-unit variance differences by meaning.
- Fit preparation on training data and report the scale used.
3.2 Recognize a misleading reduction
PCA answers a precise question about squared linear variation. Problems arise when that answer is treated as evidence about a different question, such as which features predict a target or whether a curved pattern has one underlying coordinate.
Check the shape of the structure
Points spread evenly around a circle have equal variance in two perpendicular directions. PCA finds two equal eigenvalues and no preferred first direction. Yet one angle identifies a point on the known circle. The curve is simple, but a straight-line projection overlaps different points. A nonlinear map may reveal that neighborhood structure more clearly.
For standardized, uncorrelated features, the correlation matrix is the identity matrix. All eigenvalues equal 1, and every component explains of the total. There is no compact set of dominant components. Unscaled, uncorrelated features can have unequal variances; the largest-variance feature then supplies PC1 without combining shared structure.
Separate variation from relevance
Imagine two long, parallel clouds of points. They differ by a small offset across their short direction. PC1 follows the long direction because it has the most variation, but the short direction separates the labels. Dropping it can harm classification even while retaining most variance.
PCA does not use the target to decide what to keep. Judge a predictive pipeline by validation performance, and compare it with a model that keeps the original features. High PVE alone cannot select the best predictor.
Inspect unusual observations
PCA uses squared deviations, making it sensitive to extreme points. One erroneous sensor value can create a direction of large variance and pull PC1 toward itself. Inspect the original values and score plot, check the measurement record, and compare fits with and without a questioned point. A valid unusual observation may matter; deletion needs a reason grounded in the task.
Scaling is not a repair for this problem. An extreme standardized observation is still extreme, and its influence also enters the estimated mean and standard deviation.
Prepare suitable inputs
PCA takes numeric features. A numeric code for a category does not turn the gaps between codes into meaningful distances. Data dominated by categories often call for a method designed for categorical relationships. One-hot encoding supplies numbers but does not make ordinary PCA the best summary by itself.
scikit-learn's PCA rejects missing values. Impute them first, and fit the imputer on training data in a predictive workflow. Keep the target and arbitrary identifiers out of the feature matrix. A large-range identifier can otherwise contribute large but meaningless variation.
Assess whether the pattern is stable
Components describe the fitted sample. With few observations, a new sample can produce noticeably different directions. Close eigenvalues make neighboring directions especially unstable; a small change can swap their order or rotate them within nearly the same plane. Compare the retained subspace as well as individual vectors.
Finally, the new features mix original measurements. Reporting loadings helps others understand a model's inputs. When explanations in named variables are essential, consider feature selection or a model on the original features.
Key Takeaways
- PCA captures linear variance and can miss a simple curved structure.
- High variance can be unrelated to the target.
- Outliers can strongly change the fitted axes.
- Prepare numeric, complete features with training-fitted imputation.
- Close eigenvalues and small samples can make individual directions unstable.
4Decide how many components to keep
A smaller representation trades detail for simplicity. Explained variance accounts for the spread retained by each component, while reconstruction shows the part that was lost. Scree plots and selection rules help you choose a count, but their answers can differ. A useful decision connects the count to the intended plot, compression level, or predictive task, with the fitting scale kept in view.
4.1 Account for explained variance
Every component has a variance, its eigenvalue. Explained variance expresses this amount as a share of the total, making it easier to judge how much a smaller representation keeps.
Divide by the full total
The proportion of variance explained, or PVE, is
The denominator includes all component variances, including those you plan to discard. It also equals the sum of original feature variances in the prepared data. For sample-standardized features, total variance is .
Suppose four standardized features give eigenvalues 2.6, 0.9, 0.3, and 0.2. Their total is 4. Divide each by 4 to get 65%, 22.5%, 7.5%, and 5%. A loading such as 0.6 is a weight; it cannot replace an eigenvalue in this calculation.
Accumulate the kept shares
Cumulative PVE adds the shares from PC1 through the last component kept. In this example:
| Components kept | Cumulative PVE | Variance discarded |
|---|---|---|
| PC1 | 65% | 35% |
| PC1–PC2 | 87.5% | 12.5% |
| PC1–PC3 | 95% | 5% |
| All four | 100% | 0% |
The individual shares decrease, while their cumulative total increases. A component can have a small individual share and still be needed to reach a desired cumulative level.
For the constructed fitness example, PVE is about 60.7%, 18.6%, 10.8%, and 9.9%. PC1–PC2 retain 79.3%, and PC1–PC3 retain 90.1%. Use unrounded eigenvalues for decisions close to a threshold; displayed percentages may hide a small shortfall.
Say what the percentage measures
“PC1 explains 65%” means its scores contain 65% of the total variance in the fitted, prepared features. It does not count correctly described people, classify 65% of observations, or promise 65% predictive accuracy.
The feature scale is part of the meaning. In covariance PCA, variance retains the numerical scales of the original units. In correlation PCA, every feature starts with equal variance. A higher PVE after changing scales does not by itself identify the better analysis: the denominator and the task have changed.
Read the size in context
With 100 standardized, nearly uncorrelated features, an individual component would carry about 1%. PC1 carrying 30% then indicates strong common structure, although most variance remains outside PC1. With two features, 30% could not be the first component's share because the larger of two nonnegative eigenvalues carries at least half the total.
PVE from a model fitted on training data summarizes that training sample. A new batch need not have the same component variances. Keep the fitted axes for transformation, and assess whether the representation continues to work on the data and task you care about.
Key Takeaways
- PVE divides a component eigenvalue by total variance.
- Cumulative PVE sums the first several component shares.
- PVE describes variation in prepared features, not prediction accuracy.
- Interpret a share relative to feature count, scaling, and the fitted sample.
4.2 Choose components for the task
There is no universal best component count. A two-axis plot, a compressed data archive, and a predictive model need different evidence. Selection rules provide starting points, then the task decides.
Read the two kinds of plot
A scree plot puts component number on the horizontal axis and eigenvalue or individual PVE on the vertical axis. Values decrease. An elbow is where the steep decline gives way to a flatter tail; keeping the major components before that tail can provide a compact summary.
A cumulative plot adds the shares and rises toward 100%. Read it when the question asks how many components reach a chosen total. Do not read an individual scree value as though it were cumulative.
Compare rules with one example
Take six standardized features with eigenvalues 3.1, 1.4, 0.6, 0.4, 0.3, and 0.2. They sum to 6. The individual PVEs are about 51.7%, 23.3%, 10.0%, 6.7%, 5.0%, and 3.3%. Cumulative PVE is about 51.7%, 75.0%, 85.0%, 91.7%, 96.7%, and 100%.
| Rule | Decision in this example | What it asks |
|---|---|---|
| Elbow | About two components | Where does the substantial drop end? |
| 80% cumulative threshold | Three components | What is the smallest count reaching 80%? |
| 90% cumulative threshold | Four components | What is the smallest count reaching 90%? |
| 95% cumulative threshold | Five components | What is the smallest count reaching 95%? |
| Eigenvalue greater than 1 | Two components | Which components exceed one standardized feature's variance? |
The elbow is a visual judgment. A gradual bend can leave no convincing single elbow. A threshold is explicit but still chosen by the analyst; 90% is not a law of good modeling.
Apply the eigenvalue rule on the right scale
Kaiser's rule keeps eigenvalues strictly above 1 in correlation-based PCA. The benchmark is the variance of one standardized feature. It keeps 3.1 and 1.4 here. For eigenvalues 2.6, 0.9, 0.3, and 0.2, it keeps one component even though an 80% threshold needs two.
Using the same cutoff on arbitrary covariance units has no such meaning. Measuring a length in centimeters instead of meters could change the result of the rule. Treat it as a rough guide that can keep too many or too few components.
Match evidence to purpose
For visualization, choose two or three axes and report their cumulative PVE so the reader knows how much lies outside the picture. For compression, select a count with acceptable reconstruction error and include the loadings and mean in storage costs.
For prediction, tune the count by cross-validation of the complete model pipeline. PCA cannot know whether a low-variance direction predicts the target. Fit and compare within training folds, then use the held-out test set for final evaluation. Repeatedly choosing the count from test performance turns that test set into tuning data.
Keeping every component with nonzero variance preserves all sample variation, but does not reduce that variation to a smaller representation. Keeping all original feature directions simply rotates the coordinate system.
Key Takeaways
- Scree plots show individual eigenvalues or shares; cumulative plots show running totals.
- Threshold selection uses the smallest count reaching the chosen total.
- Kaiser’s rule applies to correlation-based eigenvalues above 1.
- Elbows and different rules can give different counts.
- Use model cross-validation for prediction and reconstruction error for compression.
4.3 Rebuild observations from scores
Projection keeps the part of each observation that lies in the retained component directions. Reconstruction converts those scores back into the original feature space, making the discarded part visible as an error.
Move from the mean along kept directions
With components, reconstruct observation as
Each score tells you how far to move along one unit direction. Add those moves to the mean. If the input was standardized, this formula first reconstructs the standardized features; reverse the scaling afterward to recover measurement units.
Use mean and . Observation centers to . Its score is . The kept part is
Adding the mean gives . The reconstruction lies on PC1's line; it need not match either original coordinate exactly.
Measure the missing part
The residual is . Squaring and adding gives
The discarded PC2 score is , whose square is also 1.8. Orthogonal directions make the total squared error equal the sum of squared discarded scores.
Across the fitted sample, the total squared reconstruction error is
For five observations with eigenvalues 6 and 1, keeping PC1 gives total error . The discarded variance share is . Dividing by total centered squared variation, , gives the same share. The factor distinguishes total squared error from summed sample variance.
Account for compression honestly
A collection of 1,000 grayscale images, each with 10,000 pixel features, contains 10,000,000 numbers. With 50 components, store 50,000 observation scores, 500,000 loading entries, and 10,000 means. Total storage is 560,000 numbers, or 5.6% of the original count. Counting only the scores would leave out the information needed to reconstruct the images.
PCA gives the smallest total squared error among flat subspaces of a chosen dimension in the scale used for fitting. For standardized data, that optimality is measured in standardized units; it need not minimize error expressed in the original mixed units.
Reconstruct and inspect
Low-variance directions can contain mostly random noise. Dropping them can smooth an image, while also removing fine detail. A large error for one observation means it differs from the main retained pattern and may merit inspection.
In Python, pca.inverse_transform(scores) returns the reconstructed PCA input. If StandardScaler came first, follow with scaler.inverse_transform(...). Inverse transformation cannot recover values discarded by keeping too few components.
Key Takeaways
- Reconstruct by adding score-weighted directions to the mean.
- Squared residual length equals squared discarded scores.
- Total sample error is times discarded eigenvalues.
- Compression must store scores, loadings, and means.
- Denoising can also remove useful fine detail.
- Reverse both PCA and scaling to return to original units.
5Apply PCA in Python for visualization and modeling
A reliable PCA workflow keeps feature preparation, component directions, and model inputs together. Read the fitted arrays carefully so that observation scores are not mistaken for loading vectors, and label score plots with the variation they display. For prediction, fit and tune the entire pipeline on training data, then apply the stored transformation unchanged to held-out and future observations.
5.1 Fit PCA and inspect its output
scikit-learn separates fitting a transformation from applying it. Fitting learns means and component directions; transforming uses those fitted quantities to produce observation scores.
Prepare a feature table
Let X be a pandas table of complete numeric feature columns. Exclude the target and arbitrary row identifiers. A date-derived feature can be useful when it has a clear meaning, suitable encoding, and is available at prediction time. For exploratory analysis of this table, a scaled two-component fit is:
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
scaler = StandardScaler()
X_std = scaler.fit_transform(X)
pca = PCA(n_components=2)
scores = pca.fit_transform(X_std)
Each row of scores belongs to the corresponding observation in X; its two columns are PC1 and PC2. Use fit_transform on the fitting data, then transform on new data. For predictive evaluation, split before fitting and keep these steps inside the training workflow.
Read directions and variances
pca.components_ has one row per kept component and one column per original feature. Each row is a unit-length direction. Transpose it to display feature names down the rows:
loadings = pd.DataFrame(
pca.components_.T,
index=X.columns,
columns=["PC1", "PC2"],
)
r = pca.explained_variance_ratio_
cumulative = np.cumsum(r)
explained_variance_ holds the component variances, while explained_variance_ratio_ holds their shares of the full total. mean_ contains the means of the data PCA received, which will be near zero after standardization. Loading rows do not correspond to observations; the score rows do.
Fit enough components for the question
A two-component fit reports two shares. Their sum is only the retained share and need not equal 1. Use a full fit to inspect the entire scree curve:
full = PCA().fit(X_std)
r_all = full.explained_variance_ratio_
The default full output contains up to the smaller of sample count and feature count, including a possible zero-variance component due to centering. A fractional setting selects a count by retained variance:
pca95 = PCA(n_components=0.95, svd_solver="full")
scores95 = pca95.fit_transform(X_std)
k = pca95.n_components_
Here the cumulative share must exceed 0.95. An explicit full solver makes that fractional selection clear. This software boundary is slightly different from a hand rule that says “at least 95%” at exact equality.
Plot and reverse the transformation
import matplotlib.pyplot as plt
plt.plot(range(1, len(r_all) + 1), r_all, marker="o")
plt.xlabel("Component")
plt.ylabel("Proportion of variance explained")
Replace r_all with np.cumsum(r_all) for a cumulative plot. For reconstruction, use scaler.inverse_transform(pca.inverse_transform(scores)).
StandardScaler uses denominator , while PCA variances use . For 50 observations and four nonconstant scaled features, the full eigenvalue sum is . This common factor cancels from PVE. Finally, equivalent fits may reverse component signs: compare patterns and reconstructions, not signs alone.
Key Takeaways
- Fit learns axes; transform applies the fitted axes to observations.
- Rows of
components_are directions; rows of transformed data are observations. - Use a full fit for the full scree curve and cumulative total.
- Fractional
n_componentsselects a retained-variance count. - Reverse scaling after inverse PCA when recovering measurement units.
5.2 Read a score plot fairly
A score plot shows observations in component coordinates. It is useful because many features can be viewed at once through two axes, but its empty space and overlap must be interpreted as features of a projection.
Make the plotted coordinates explicit
Place PC1 scores horizontally and PC2 scores vertically. Label both with their shares, such as “PC1 (60.7%)” and “PC2 (18.6%).” These axes retain 79.3% of the fitted variance together; 20.7% lies in the omitted directions.
For the fitted objects and scores from a two-component analysis:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(scores[:, 0], scores[:, 1], s=16)
ax.set_xlabel(f"PC1 ({100 * pca.explained_variance_ratio_[0]:.1f}%)")
ax.set_ylabel(f"PC2 ({100 * pca.explained_variance_ratio_[1]:.1f}%)")
ax.set_aspect("equal", adjustable="datalim")
Equal axis scaling makes one score unit the same displayed length in both directions. Expanding PC2 to fill the panel can make its smaller variation look as large as PC1's.
Distinguish projected from full distance
With ordinary, unwhitened PCA scores, dropping coordinates cannot increase Euclidean distance. For two observations, squared full distance is the sum of squared score differences across all component directions. A two-axis plot retains only two of those nonnegative terms.
Points far apart on the plot are far apart in the prepared feature space. Points close on the plot may differ strongly on PC3 or a later component. For example, two points with identical PC1 and PC2 scores but PC3 scores −4 and 4 overlap in the plot while being 8 score units apart in the full space.
This reasoning uses the same feature scale as the fit. A standardized-data plot describes standardized distances, not distances formed from raw meters and kilograms. Additional display rescaling or whitening also changes how numerical distances should be read.
Add labels after the unsupervised fit
Coloring points by known classes helps show whether the large-variance directions separate those classes. The colors do not enter the PCA fit. The scikit-learn digits data contain 1,797 images with 64 pixel features each. Two components reveal some class structure but also substantial overlap; a poor two-axis separation does not establish that the full data cannot separate the digits.
Inspect which measurements drive any visible axis. A high PC1 score acquires meaning from its loadings. In the fitness example it combines several measurements; it is not a measured variable called “PC1.”
Investigate visible patterns
An isolated point may be unusual, or it may reflect a data error. Groups may follow real differences, a measurement day, or a machine. Compare original features and metadata before interpreting the pattern. If PC3 carries substantial variance, a PC1–PC3 view can reveal differences hidden in the first plot. A map supplies a view of the data; evidence about distinct populations needs more than a visible gap.
Key Takeaways
- Plot scores, and label the component variance shares.
- Use equal axis scales to show distances honestly.
- Projection can hide distance but cannot increase it in the fitted feature scale.
- Color labels can aid interpretation without entering the PCA fit.
- Investigate groups and outliers in the original measurements.
5.3 Keep PCA inside the training workflow
PCA can reduce model inputs, remove linear dependence among retained features, and shorten training. These advantages matter only if the full predictive workflow is evaluated without using information from held-out observations.
Fit preparation on training data
Split before fitting means, scales, imputers, or PCA. Fit them on training observations and reuse the fitted objects for validation, test, and future data. Even without labels, PCA fitted on all rows lets held-out feature values shape the representation. That is data leakage and undermines an independent evaluation.
A pipeline keeps transformation order and fitted state together:
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
pipe = make_pipeline(
StandardScaler(),
PCA(n_components=10),
LogisticRegression(max_iter=2000),
)
pipe.fit(X_train, y_train)
test_accuracy = pipe.score(X_test, y_test)
Here the input has at least ten suitable features and enough training observations. The pipeline's score transforms test data using training-fitted steps before evaluating the classifier.
Tune inside cross-validation
A transformation fitted once before cross-validation leaks each validation fold into preparation. Cross-validate the whole pipeline so every fold learns its own scaler and PCA from its training portion.
from sklearn.model_selection import GridSearchCV
search = GridSearchCV(
pipe,
{"pca__n_components": [5, 10, 20, 40]},
cv=5,
)
search.fit(X_train, y_train)
best_settings = search.best_params_
test_accuracy = search.score(X_test, y_test)
Use candidate counts that fit the number of features and the smallest training fold. make_pipeline names the PCA step pca; the double underscore addresses its parameter. Constructing GridSearchCV does not run the search. Calling fit evaluates candidates and, with default refitting, trains the best configuration on all training data.
Compare with the original features
PCA can help a distance-based model when many features repeat similar information or add noise. It can also remove a small-variance direction needed for prediction. Compare cross-validated performance with a pipeline without PCA. Regularized models can already manage correlated features, and tree models may benefit from splitting on named original features that PCA mixes together.
Principal components regression fits linear regression on retained PCA scores. Its directions are selected from feature variation without the response. Cross-validation therefore matters even if a variance threshold looks convincing.
Reuse the same coordinate system
At prediction time, call the fitted pipeline on raw new features in the same order. Refitting PCA on a new batch creates new axes, possibly reordered or sign-reversed, that the model has never seen.
For a linear model on standardized component scores, component coefficient contributes to the coefficient of standardized feature . Sum across retained components to recover that feature's combined coefficient. Returning to original measurement units also requires the scaler's standard deviations and the corresponding intercept adjustment.
Key Takeaways
- Fit scaler and PCA on training data and reuse them for new observations.
- Cross-validate the complete pipeline, including preparation.
- Call
GridSearchCV.fitto run tuning and refit the best configuration. - Compare PCA against a model using original features.
- Principal components regression can discard predictive low-variance directions.
- A deployed model needs the same fitted axes and feature order.
6Explore nonlinear structure with t-SNE and UMAP
Curved patterns can look compressed or overlapping in a linear projection. t-SNE and UMAP offer nonlinear views that emphasize neighborhoods, with settings that can change the visible layout. Understanding those settings helps distinguish a stable local pattern from a plotting effect. The choice of method depends on whether you need interpretable axes, an exploratory map, or a transformation for later observations.
6.1 Read local structure with t-SNE
t-SNE builds a nonlinear map for examining nearby observations. Its neighborhoods can reveal structure that a two-component PCA plot misses, but its axes and large gaps have no direct variance interpretation.
What the map tries to preserve
The name means t-distributed stochastic neighbor embedding. The method converts original-space distances into neighbor probabilities using Gaussian curves. In the low-dimensional map it uses a heavy-tailed Student t curve with one degree of freedom. It moves points to reduce disagreement between these probability patterns, measured by Kullback–Leibler divergence.
You do not need the optimization formula to read the result. The key is that the method emphasizes local relationships. Nearby points in the original data are encouraged to stay nearby in the map; long-range distances are not the main objective. Separation can become visually clear even when the map is a poor ruler for distances between distant groups.
Change the neighborhood scale
Perplexity controls roughly how many neighbors matter around a point. In scikit-learn the default is 30; values from 5 to 50 are commonly explored, and perplexity must be smaller than the sample count. It is not a requested number of clusters.
Small values emphasize fine local detail; larger values consider a broader neighborhood. Compare settings and seeds to identify stable patterns. Fixing random_state helps reproduce one run, but does not establish that its layout is uniquely correct.
Use a practical starting workflow
For complete features with many columns, PCA reduction to about 50 dimensions can remove some noise and speed up t-SNE. Keep the count compatible with the sample size and feature count. For the 64-feature digits data:
from sklearn.datasets import load_digits
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
X, labels = load_digits(return_X_y=True)
X50 = PCA(n_components=50).fit_transform(X)
embedding = TSNE(
n_components=2, perplexity=30, random_state=42
).fit_transform(X50)
The pixels share a scale, so this example centers without standardizing them. The labels can color the finished map; they were not used to build it. Digits often separate more clearly here than in a two-component PCA view.
Read the map without using it as a ruler
Dense groups can expand and sparse groups contract. Their displayed areas do not preserve original density or spread. The gap between two distant groups is not a dependable measure of how different they are. Even random data can form apparent clumps, especially with very local settings.
Map orientation can rotate, mirror, or rearrange across runs. Names such as “t-SNE 1” identify coordinates, not feature combinations with loadings or PVE. Check a visible grouping in original features, alternative settings, or another suitable analysis before drawing a substantive conclusion.
scikit-learn's TSNE has fit_transform but no fitted transform for new observations. Fitting a new map changes the coordinate system. That makes this implementation suited to exploratory visualization, not a reusable preprocessing step for a model that will receive future cases.
Key Takeaways
- T-SNE emphasizes local neighbor relationships.
- Perplexity controls neighborhood scale and must be below sample count.
- Check several settings and seeds; one reproducible map can still be misleading.
- Cluster areas and distant gaps are unreliable measures of original spread.
- scikit-learn’s
TSNEcannot transform new observations into a fitted map.
6.2 Choose PCA, t-SNE, or UMAP
UMAP provides another way to build a nonlinear map from neighborhoods. Choose between methods by the output you need: interpretable linear scores, an exploratory local map, or a nonlinear representation that can also place new observations.
Build a graph, then a map
UMAP, or uniform manifold approximation and projection, builds a weighted graph of nearest-neighbor connections in the original feature space. It then arranges low-dimensional points to give a similar pattern of connections. This lets it unfold some curved relationships that a straight projection misses.
Two settings have especially visible effects. n_neighbors controls how many neighbors define the local graph. Small values emphasize local detail; larger values use broader neighborhoods. min_dist controls how tightly points may pack in the map. Smaller values allow tighter clumps, while larger values spread points more widely. These settings change the view, not the underlying measurements.
Fit and reuse the mapper
UMAP is supplied by the separate umap-learn package, imported as umap. For a complete standardized feature matrix X_std:
import umap
reducer = umap.UMAP(
n_neighbors=15,
min_dist=0.1,
random_state=42,
)
embedding = reducer.fit_transform(X_std)
The values shown are the defaults for the two main settings. If a scaler produced X_std, transform raw new data with that fitted scaler before calling reducer.transform(X_new_std). The new observations must have the same feature definitions and order.
UMAP can also produce more than three output dimensions for model inputs. Any predictive use still needs training-only fitting, validation, and comparison with simpler baselines.
Choose by what you must explain
| Need | Starting method | Reason |
|---|---|---|
| Feature weights and variance accounting | PCA | Linear directions have loadings and PVE |
| A reusable fast linear preprocessing step | PCA | Fitted projections apply directly to new rows |
| A map emphasizing local neighbors | t-SNE or UMAP | Nonlinear layouts reveal local structure |
| A nonlinear map that accepts later observations | UMAP | A fitted mapper offers transform |
UMAP is often faster than t-SNE on large data sets and can retain more broad arrangement, but neither gives a reliable geometric scale for every distant gap. Runtime and map quality depend on the data and settings.
Check the interpretation
A survey analyst who needs to explain which questions drive large differences can inspect PCA loadings. A UMAP coordinate cannot supply those weights. For tens of thousands of high-dimensional measurements, UMAP after an initial PCA reduction can give a useful neighborhood view.
UMAP is stochastic. Fix a seed for repeatability, then compare other seeds and plausible settings. A cluster that tightens when min_dist decreases has changed its displayed packing; that alone says nothing about whether the original observations became more distinct. The axes have no standalone substantive meaning and no PVE. Investigate visible groups in the original features before naming them.
Key Takeaways
- UMAP builds and maps a weighted neighbor graph.
n_neighborssets neighborhood breadth;min_distcontrols map packing.- Fitted UMAP can transform compatible new observations.
- Use PCA for loadings and PVE, and nonlinear maps for local structure.
- UMAP axes and distant gaps require careful interpretation.
Principal Component Analysis examples
1From a feature table to directions of spread
12 steps
- 1IntroductionStart with a table
A table with many columns is a cloud of points with many coordinates. The question is which differences among those points can be summarized with fewer numbers. That is dimensionality reduction, and principal component analysis (PCA) is the standard linear method for it. First identify what reduction changes; then center a small table and use its covariance matrix to compare directions, the spread PCA will organize.
- 2ExampleCount coordinates, not rows
An grayscale image has 64 pixel values. Store one image per row and one pixel per column: 1,000 images give 1,000 points in 64 dimensions. Adding more images supplies more points in the same space. It does not add coordinates to an individual image.
- 3ExplanationCombine repeated measurements
Height and arm span in centimeters often move together. A combined size coordinate can describe much of their shared variation; another coordinate can describe differences in proportion. Keeping just size is useful compression when proportion is unimportant to the task, but it removes those differences.
- 4ExampleSee why neighborhoods get broad
For points spread uniformly in a unit cube, a smaller cube covering 10% needs edge length . That is 0.1 in one dimension but about 0.794 in ten dimensions. A supposedly local group then spans almost 80% of every axis. This helps explain why a distance-based model can need many more observations as the number of features grows.
- 5Key InsightFewer outputs still need the inputs
PCA builds new weighted combinations. Even if you store only three component scores, computing those scores for a new observation usually needs all original feature measurements. Selecting three original sensors is a different operation: feature selection. The output count and required measurement count need not match.
- 6ChallengeChoose the kind of reduction
A laboratory wants later cases to require only four of its twenty original measurements. Does keeping four ordinary PCA scores meet that measurement goal?
---reveal---
No. The scores usually combine all twenty measurements. Feature selection can keep four original columns; PCA reduces the number of output coordinates, not usually the number of measurements needed to produce them.
- 7ExampleMove the average to zero
Use features and . Their means are 10 and 5. Subtract the matching mean from each value to get .
The average point is now the origin. Every difference between two observations is unchanged.
- 8ExampleCalculate the shared spread
The centered x squares sum to 20 and the y squares sum to 8. Divide each by 4 to get variances 5 and 2. The paired products sum to 8, giving covariance 2.
Thus . Its diagonal sum is total variance, 7; the off-diagonal entries record shared movement.
- 9ExplanationCompare unit directions
A projection takes a dot product with a unit direction . The score variance is . Horizontal direction gives 5. Direction gives . Direction gives 6.
The best direction need not be an original axis or the simple diagonal.
- 10ChallengeRead spread after a unit change
A length feature is converted from meters to centimeters. Its old variance is 0.04 and its covariance with an unchanged feature is 0.3. What are the new values?
---reveal---
Variance is ; covariance is . One changed feature contributes one factor of 100 to a cross-product, but two factors to its own squared deviation.
- 11ChallengeConnect purpose and measurement
Two laboratories record the same lengths using different units. They want comparable PCA summaries that give each feature equal starting spread. What preparation addresses the unit difference, and what does it preserve?
---reveal---
Standardize each feature using its mean and standard deviation. This removes the unit multiplier while retaining correlations. Merely centering leaves variance dependent on the chosen length unit.
- 12RecapKnow what will be summarized
A row is an observation and a column is a coordinate. PCA extracts combinations to retain linear spread, while feature selection keeps measurements. Centering locates the mean at zero; the covariance matrix then records variances and shared movement. Unit directions make projected spreads comparable, and feature scales help decide which spread should count.
2Calculate axes and give them meaning
16 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn spread into coordinates
- 2ExplanationConstrain the direction
- 3ConnectionFit a line with perpendicular residuals
- 4ChallengeCheck a claimed PCA direction
- 5ExampleSolve the eigenvalue equation
- 6ExampleNormalize the leading eigenvector
- 7ExampleFind and check the second direction
- 8ChallengeCalculate another matrix
- 9Key InsightCount directions with nonzero spread
- 10ExampleInterpret signs together
- 11ExampleMultiply contributions before adding
- 12Key InsightA weight is not a correlation
- 13TipCheck how biplot arrows were built
- 14ChallengeCompute a fresh score
- 15ChallengeCompare a mirrored analysis
- 16RecapKeep the roles distinct
3Prepare a scale and check the limits
11 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDecide which differences should count
- 2ExampleLet units expose the problem
- 3ExplanationGive features a common spread
- 4ChallengeChoose preparation for pixels
- 5AnalogyA circular track has no preferred diameter
- 6ExampleFind the target in the short direction
- 7TipCheck data quality before trusting axes
- 8ChallengeRead the absence of a dominant direction
- 9TipCheck whether individual axes persist
- 10ChallengeConnect scaling with useful information
- 11RecapMatch the representation to the question
4Choose a count and measure the loss
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the tradeoff visible
- 2ExampleDivide each eigenvalue by the total
- 3ExplanationAdd shares in component order
- 4ChallengeFind the missing share
- 5ExampleLet the threshold choose the smallest count
- 6ConnectionWhy the rules disagree
- 7ChallengeSelect for a model
- 8ExampleCalculate the retained displacement
- 9ExampleReturn to the mean and measure error
- 10Key InsightSum error with the sample denominator
- 11TipInclude the shared reconstruction data
- 12ConnectionDistinguish noise removal from detail loss
- 13ChallengeChoose by an error budget
- 14RecapUse the purpose to settle the count
5Fit, plot, and deploy a PCA pipeline
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack the fitted state
- 2ExampleFit a two-component representation
- 3ExplanationRead the two different arrays
- 4Key InsightKeep ratios separate from eigenvalues
- 5ExampleRequest a retained-variance count
- 6ChallengeDiagnose a reported total
- 7ExamplePlot with equal coordinate units
- 8ChallengeLook beyond overlapping points
- 9ExplanationSplit before learning preparation
- 10ExampleFit the complete predictive pipeline
- 11ExampleRun selection inside training folds
- 12ChallengeRepair a cross-validation shortcut
- 13ConnectionJudge regression on scores by prediction
- 14ChallengeKeep new cases on the trained axes
- 15RecapKeep arrays and evaluation roles clear
6Use nonlinear maps without overreading them
13 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionA map has a purpose
- 2ExplanationMatch neighbor relationships
- 3TipTry more than one neighborhood scale
- 4ExampleReduce many features before mapping
- 5ChallengeInterpret a changed cluster size
- 6Key InsightA fitted t-SNE map cannot score a new case
- 7ExplanationUMAP builds a neighborhood graph
- 8ExampleSeparate neighborhood breadth from packing
- 9ChallengeChoose a mapper for later cases
- 10ExampleFit a mapper that can accept new rows
- 11ConnectionKeep interpretation as a separate requirement
- 12ChallengeDesign a useful pair of views
- 13RecapChoose the output you actually need
Principal Component Analysis practice questions
Set 1: Dimensions, spread, and new directions10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
Show answerHide answer
Question 4 of 10
Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
Show answerHide answer
Question 7 of 10
Show answerHide answer
Question 8 of 10
Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
Show answerHide answer
Set 2: Calculate and interpret principal components10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 3: Scaling, retained variance, and reconstruction10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Python output, plots, and leak-free models10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
components_?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
explained_variance_ratio_ = [0.46, 0.29]. What can this output establish?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
StandardScaler to 11 observations with 3 nonconstant features, then fits full PCA. What eigenvalue sum and ratio sum should be expected?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
n_components=0.875. Its full eigenvalues are 3.0, 0.5, and 0.5, and 12 new observations each have 3 suitable features. What is the shape of the new score array?Show answerHide answer
Save this lesson to see this answer.
Set 5: Nonlinear maps and decisions in new situations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
min_dist is reduced. What is the direct explanation?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
TSNE and the existing classifier. What breaks, and what is a viable alternative?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
B
Batch effect
Biplot
C
Centering
components_
components_ attribute stores one unit loading vector per row of a fitted scikit-learn PCA object, in input-feature order.components_ puts the original feature names down the rows of a readable loading table.Compression
Correlation biplot
Correlation matrix
Correlation-based PCA
Covariance matrix
Covariance-based PCA
Cross-validation
Cumulative PVE
Cumulative threshold rule
Curse of dimensionality
D
Data leakage
Data matrix
Denoising
Determinant equation
Dimension
Dimensionality reduction
Discarded variance
E
Eigenvalue
Eigenvector
Elbow rule
Embedding
Equal aspect ratio
explained_variance_ratio_
explained_variance_ratio_ attribute holds each retained component’s share of the complete variance, not a share of only the kept components.F
Feature extraction
Feature scale
Feature selection
fit
fit method learns a transformation’s parameters from the supplied data, such as feature means, scales, or principal component directions.fit on training features establishes the coordinate system later used for new observations.G
GridSearchCV
GridSearchCV evaluates candidate parameter settings by cross-validation and normally refits the best configuration after its fit method is called.pca__n_components addresses the PCA count inside a pipeline step named pca.H
Held-out test set
Hyperparameter
I
Imputation
Inverse transformation
K
Kaiser’s rule
L
Linear structure
Loading
Loading vector
Local neighborhood
M
min_dist
min_dist setting controls how tightly UMAP points may pack in an embedding, with smaller values allowing more compact groups.min_dist even though none of the original measurements changed.N
n_components_
n_components_ attribute reports how many components a fitted PCA retained, including a count chosen from a fractional variance request.n_components_ to learn how many score columns were selected.n_neighbors
n_neighbors setting controls the breadth of UMAP’s original-space neighborhoods, with larger values emphasizing broader connections.n_neighbors can smooth fine local detail while showing more of the overall arrangement.Normalization
O
Orthogonality
Outlier
P
Perplexity
Pipeline
Principal component
Principal components regression
Projection
Proportion of variance explained
R
Random seed
random_state=42 reproduces one map; trying other seeds helps assess whether its patterns persist.Reconstruction
Reconstruction error
S
Sample covariance
Sample variance
Sampling instability
Score
Score plot
Scree plot
Sign ambiguity
Standardization
T
t-SNE
Total variance
Trace
transform
transform method applies an already fitted transformation without estimating a new set of means, scales, or component directions.transform at each preparation step.U
UMAP
Unsupervised learning
V
Variable–component correlation
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.