Principal Component Analysis and Dimensionality Reduction

Learn how principal component analysis (PCA) turns many correlated variables into a few new ones that keep most of the variation in the data. Find components from the covariance or correlation matrix, read loadings, scores and biplots, decide when to standardize, and choose how many components to keep with explained variance and scree plots. Then use PCA in Python with scikit-learn to visualize high-dimensional data and to prepare features for a model without data leakage, and see what the nonlinear maps of t-SNE and UMAP can and cannot show.

IntermediateLesson 9 of 9 in Machine Learning Course

What you will learn

  1. 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 helps
      Recognize 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 covariance
      Center a data matrix, compute variances, covariances and a covariance matrix, and find the variance of the data along a chosen direction.
  2. 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 variance
      Define 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 matrix
      Find loading vectors as eigenvectors and component variances as eigenvalues of the covariance or correlation matrix, and check the results.
    • Interpret loadings, scores and biplots
      Read what each component measures from its loadings, compute and explain an observation's score, and read a biplot.
  3. 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 PCA
      Explain 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 misleads
      Identify the assumptions behind PCA and the situations where it summarizes data poorly, and choose a sensible response.
  4. 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 variance
      Compute the proportion and cumulative proportion of variance explained by components, and read them correctly.
    • Choose the number of components with scree plots and rules
      Draw 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 lost
      Rebuild observations from a few components, compute the reconstruction error, and relate it to the discarded variance and to compression and noise reduction.
  5. 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 output
      Standardize and fit PCA in scikit-learn, and read loadings, explained variance and scores from the fitted object.
    • Visualize high-dimensional data with component scores
      Plot 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 leakage
      Place standardization and PCA inside a pipeline, fit them on training data only, tune the number of components, and judge whether PCA helps the model.
  6. 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 plots
      Describe 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 task
      Describe the idea behind UMAP and its main settings, compare it with t-SNE and PCA, and choose a method to fit the purpose.

Principal Component Analysis study guide

6 chapters

1

Explain 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, p, not the number of observations, n. An 8×8 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

ℓ=0.11/p.

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.

ApproachWhat remainsWhat a new observation needs
Feature selectionA subset of named original columnsThose selected measurements
Feature extractionNew coordinates built from the original columnsThe 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 n×p matrix X. Entry xij is observation i's value for feature j. Centering subtracts each column mean, placing the average observation at the origin without changing differences between observations.

For five observations, take x=(7,9,10,11,13) and y=(3,5,5,7,5). The means are 10 and 5. Subtract them to get the points (−3,−2),(−1,0),(0,0),(1,2),(3,0). 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:

sx2=∑i(xi−xˉ)2n−1,sxy=∑i(xi−xˉ)(yi−yˉ)n−1.

For the first column, the squared deviations sum to 9+1+0+1+9=20, so its variance is 20/4=5. For the second, they sum to 8, giving variance 2. The cross-products sum to 6+0+0+2+0=8, giving covariance 2.

Place variances on the diagonal and covariances off the diagonal:

S=(5222).

The matrix is symmetric because reversing the order of multiplication leaves covariance unchanged. Its diagonal sum, called the trace, is the total variance: 5+2=7. The correlation divides covariance by both standard deviations: r=2/(52)≈0.632. The correlation matrix has 1 on each diagonal entry for nonconstant features.

Measure variance in a new direction

Choose a unit vector u and take each centered point's dot product with it. The resulting coordinates have variance u⊤Su. Requiring length 1 makes directions comparable: otherwise multiplying a vector would multiply the spread without changing its direction.

Along u=(1,0), variance is 5. Along the diagonal u=(1,1)/2, it is

5+2(2)+22=5.5.

Along u=(2,1)/5, it is

4(5)+2(2)(2)+25=6.

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 u⊤Su; units affect its value.
2

Find 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

Z1=ϕ11X1+⋯+ϕp1Xp.

The weights are loadings, collected in a loading vector ϕ1. PCA chooses the unit-length loading vector that makes the variance of this combination as large as possible. The constraint is ∑jϕj12=1. 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 i is

zi1=ϕ1⊤(xi−xˉ).

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 (−3,−2),(−1,0),(0,0),(1,2),(3,0), use ϕ1=(2,1)/5. The first point scores (−6−2)/5≈−3.578. 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 p component directions for p features. Centering limits the number with nonzero variance to min⁡(n−1,p). 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.

FitHow the residual is measuredRoles of the variables
PCA linePerpendicular to the fitted lineAll features enter symmetrically
Regression of y on xVertically along the y axisy 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 2/5=0.4. PC1's slope is 1/2=0.5. Reversing the regression gives yet another line; the different objectives explain the different answers.

A direction has two signs

The vectors ϕ1 and −ϕ1 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 min⁡(n−1,p) 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 Sϕk=λkϕk. 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 S=(5222), subtract λ from the diagonal and set the determinant to zero:

det⁡(S−λI)=(5−λ)(2−λ)−4.

Expand to get λ2−7λ+6=0. Factoring gives (λ−6)(λ−1)=0, 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 (S−6I)v=0 gives −a+2b=0. One solution is (a,b)=(2,1). Its length is 5, so

ϕ1=(2,1)5≈(0.894,0.447).

For eigenvalue 1, the first row gives 4a+2b=0. Choose (−1,2) and divide by 5:

ϕ2=(−1,2)5≈(−0.447,0.894).

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: 6+1=5+2=7.
  • Each direction has unit length: (22+12)/5=1.
  • Their dot product is zero: [2(−1)+1(2)]/5=0.

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 4/4=1. 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 r, the matrix has rows (1,r) and (r,1). Its eigenvalues are 1+r and 1−r. The first direction averages the features with equal weights, (1,1)/2, and the second contrasts them. When r=0.8, PC1 explains 1.8/2=90%. When r=0, 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 1+r and 1−r.

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

(0.52,0.50,−0.52,−0.47).

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 (1.2,0.9,−0.3,0.5), multiply by the matching loadings:

0.52(1.2)+0.50(0.9)+(−0.52)(−0.3)+(−0.47)(0.5).

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 (0.40,0.55,0.33,0.66), 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

corr⁡(Xj,Zk)=ϕjkλk.

For push-ups and PC1, 0.522.43≈0.81. 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.
3

Prepare 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:

z=x−xˉs.

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 0.6(0.1)(12)=0.72. The huge numerical difference in variances makes unscaled PC1 almost entirely mass: its loadings are about (0.005,1.000) 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 (0.59,0.80) 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 (1,1)/2 and explains (1+0.6)/2=80%. This is an equal-scale summary of the two features.

Decide from the meaning of variation
Data situationSensible starting choiceReason
Features in different unitsStandardizeUnit choices should not set the weights
Different spreads with no useful meaningStandardizeGive each feature a comparable starting scale
Same-unit features with meaningful variance differencesConsider centering onlyRetain 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 n; PCA reports sample variance with denominator n−1. 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 1/p 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.
4

Decide 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

PVEk=λk∑j=1pλj.

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 p.

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 keptCumulative PVEVariance discarded
PC165%35%
PC1–PC287.5%12.5%
PC1–PC395%5%
All four100%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%.

RuleDecision in this exampleWhat it asks
ElbowAbout two componentsWhere does the substantial drop end?
80% cumulative thresholdThree componentsWhat is the smallest count reaching 80%?
90% cumulative thresholdFour componentsWhat is the smallest count reaching 90%?
95% cumulative thresholdFive componentsWhat is the smallest count reaching 95%?
Eigenvalue greater than 1Two componentsWhich 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 k components, reconstruct observation i as

x^i=xˉ+∑j=1kzijϕj.

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 (10,5) and ϕ1=(2,1)/5. Observation (13,5) centers to (3,0). Its score is 6/5≈2.683. The kept part is

65(2,1)5=(2.4,1.2).

Adding the mean gives (12.4,6.2). The reconstruction lies on PC1's line; it need not match either original coordinate exactly.

Measure the missing part

The residual is (13,5)−(12.4,6.2)=(0.6,−1.2). Squaring and adding gives

0.62+(−1.2)2=0.36+1.44=1.8.

The discarded PC2 score is −3/5, 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

(n−1)∑j>kλj.

For five observations with eigenvalues 6 and 1, keeping PC1 gives total error 4(1)=4. The discarded variance share is 1/7≈14.3%. Dividing by total centered squared variation, 4(7)=28, gives the same share. The factor n−1 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 (n−1) 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.
5

Apply 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 n, while PCA variances use n−1. For 50 observations and four nonconstant scaled features, the full eigenvalue sum is 4(50/49)≈4.08. 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_components selects 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 βk contributes βkϕjk to the coefficient of standardized feature j. 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.fit to 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.
6

Explore 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 TSNE cannot 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
NeedStarting methodReason
Feature weights and variance accountingPCALinear directions have loadings and PVE
A reusable fast linear preprocessing stepPCAFitted projections apply directly to new rows
A map emphasizing local neighborst-SNE or UMAPNonlinear layouts reveal local structure
A nonlinear map that accepts later observationsUMAPA 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_neighbors sets neighborhood breadth; min_dist controls 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

6 Walkthroughs

1

From a feature table to directions of spread

12 steps
See why fewer coordinates can help, then calculate the spread that PCA will organize.
  1. 1
    IntroductionStart 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.

  2. 2
    ExampleCount coordinates, not rows

    An 8×8 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.

  3. 3
    ExplanationCombine 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.

  4. 4
    ExampleSee why neighborhoods get broad

    For points spread uniformly in a unit cube, a smaller cube covering 10% needs edge length 0.11/p. 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.

  5. 5
    Key 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.

  6. 6
    ChallengeChoose 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.

  7. 7
    ExampleMove the average to zero

    Use features x=(7,9,10,11,13) and y=(3,5,5,7,5). Their means are 10 and 5. Subtract the matching mean from each value to get (−3,−2),(−1,0),(0,0),(1,2),(3,0).

    The average point is now the origin. Every difference between two observations is unchanged.

  8. 8
    ExampleCalculate 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 S=(5222). Its diagonal sum is total variance, 7; the off-diagonal entries record shared movement.

  9. 9
    ExplanationCompare unit directions

    A projection takes a dot product with a unit direction u. The score variance is u⊤Su. Horizontal direction (1,0) gives 5. Direction (1,1)/2 gives (5+4+2)/2=5.5. Direction (2,1)/5 gives 6.

    The best direction need not be an original axis or the simple diagonal.

  10. 10
    ChallengeRead 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 0.04(1002)=400; covariance is 0.3(100)=30. One changed feature contributes one factor of 100 to a cross-product, but two factors to its own squared deviation.

  11. 11
    ChallengeConnect 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.

  12. 12
    RecapKnow 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.

2

Calculate axes and give them meaning

16 steps
Find eigenvalues and loading vectors, project an observation, and read component patterns and biplot arrows.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTurn spread into coordinates
  2. 2
    ExplanationConstrain the direction
  3. 3
    ConnectionFit a line with perpendicular residuals
  4. 4
    ChallengeCheck a claimed PCA direction
  5. 5
    ExampleSolve the eigenvalue equation
  6. 6
    ExampleNormalize the leading eigenvector
  7. 7
    ExampleFind and check the second direction
  8. 8
    ChallengeCalculate another matrix
  9. 9
    Key InsightCount directions with nonzero spread
  10. 10
    ExampleInterpret signs together
  11. 11
    ExampleMultiply contributions before adding
  12. 12
    Key InsightA weight is not a correlation
  13. 13
    TipCheck how biplot arrows were built
  14. 14
    ChallengeCompute a fresh score
  15. 15
    ChallengeCompare a mirrored analysis
  16. 16
    RecapKeep the roles distinct
3

Prepare a scale and check the limits

11 steps
See a unit change reshape PCA, then diagnose noise, outliers, curved structure, and predictive loss.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionDecide which differences should count
  2. 2
    ExampleLet units expose the problem
  3. 3
    ExplanationGive features a common spread
  4. 4
    ChallengeChoose preparation for pixels
  5. 5
    AnalogyA circular track has no preferred diameter
  6. 6
    ExampleFind the target in the short direction
  7. 7
    TipCheck data quality before trusting axes
  8. 8
    ChallengeRead the absence of a dominant direction
  9. 9
    TipCheck whether individual axes persist
  10. 10
    ChallengeConnect scaling with useful information
  11. 11
    RecapMatch the representation to the question
4

Choose a count and measure the loss

14 steps
Calculate variance shares, compare selection rules, and reconstruct an observation from a retained component.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the tradeoff visible
  2. 2
    ExampleDivide each eigenvalue by the total
  3. 3
    ExplanationAdd shares in component order
  4. 4
    ChallengeFind the missing share
  5. 5
    ExampleLet the threshold choose the smallest count
  6. 6
    ConnectionWhy the rules disagree
  7. 7
    ChallengeSelect for a model
  8. 8
    ExampleCalculate the retained displacement
  9. 9
    ExampleReturn to the mean and measure error
  10. 10
    Key InsightSum error with the sample denominator
  11. 11
    TipInclude the shared reconstruction data
  12. 12
    ConnectionDistinguish noise removal from detail loss
  13. 13
    ChallengeChoose by an error budget
  14. 14
    RecapUse the purpose to settle the count
5

Fit, plot, and deploy a PCA pipeline

15 steps
Read fitted arrays, make a fair score plot, and tune a predictive workflow without leaking held-out information.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack the fitted state
  2. 2
    ExampleFit a two-component representation
  3. 3
    ExplanationRead the two different arrays
  4. 4
    Key InsightKeep ratios separate from eigenvalues
  5. 5
    ExampleRequest a retained-variance count
  6. 6
    ChallengeDiagnose a reported total
  7. 7
    ExamplePlot with equal coordinate units
  8. 8
    ChallengeLook beyond overlapping points
  9. 9
    ExplanationSplit before learning preparation
  10. 10
    ExampleFit the complete predictive pipeline
  11. 11
    ExampleRun selection inside training folds
  12. 12
    ChallengeRepair a cross-validation shortcut
  13. 13
    ConnectionJudge regression on scores by prediction
  14. 14
    ChallengeKeep new cases on the trained axes
  15. 15
    RecapKeep arrays and evaluation roles clear
6

Use nonlinear maps without overreading them

13 steps
Explore neighborhood settings, check apparent groups, and choose an appropriate mapper for new observations.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionA map has a purpose
  2. 2
    ExplanationMatch neighbor relationships
  3. 3
    TipTry more than one neighborhood scale
  4. 4
    ExampleReduce many features before mapping
  5. 5
    ChallengeInterpret a changed cluster size
  6. 6
    Key InsightA fitted t-SNE map cannot score a new case
  7. 7
    ExplanationUMAP builds a neighborhood graph
  8. 8
    ExampleSeparate neighborhood breadth from packing
  9. 9
    ChallengeChoose a mapper for later cases
  10. 10
    ExampleFit a mapper that can accept new rows
  11. 11
    ConnectionKeep interpretation as a separate requirement
  12. 12
    ChallengeDesign a useful pair of views
  13. 13
    RecapChoose the output you actually need

Principal Component Analysis practice questions

50 Practice Questions in 5 sets

Set 1: Dimensions, spread, and new directions10 Practice Questions

Question 1 of 10

A table contains 240 audio clips, each represented by 80 numeric features. What is its feature-space dimension?
  1. 240
  2. 320
  3. 80
  4. 19,200
Show answerHide answer
Answer: C
Each clip is one observation with 80 coordinates, so the feature space has dimension 80. The 240 clips increase the number of points, not their dimension. Multiplying the row and column counts gives the number of stored entries, which is a different quantity.

Question 2 of 10

A team replaces 12 sensor measurements with three PCA scores. What measurements does it usually need to score a new observation?
  1. All 12 original measurements
  2. Three highest-variance sensors
  3. Three most correlated sensors
  4. The nine dropped measurements
Show answerHide answer
Answer: A
Each score is a weighted combination of the original features, so the usual PCA transformation needs all 12 measurements. Keeping three scores reduces the output coordinates, not the required input columns. Measuring only three selected sensors would require a feature-selection approach or a differently fitted model.

Question 3 of 10

A feature has values 4, 8, and 12. What are its centered values?
  1. (−8,0,8)
  2. (−1,0,1)
  3. (−4,4,12)
  4. (−4,0,4)
Show answerHide answer
Answer: D
The mean is 8, so subtracting it from every entry gives −4, 0, and 4. The result has mean zero and retains the original differences between values. The values −1, 0, and 1 also change scale; centering alone does not divide by a standard deviation.

Question 4 of 10

Three centered observations are (−2,−1),(0,0),(2,1). What is their sample covariance?
  1. 1
  2. 2
  3. 4
  4. 1.33
Show answerHide answer
Answer: B
The paired products are 2, 0, and 2, totaling 4. Sample covariance divides by one less than the three observations, giving 4/2=2. Dividing by 3 gives about 1.33, which uses the population-style denominator instead of the requested sample convention.

Question 5 of 10

A covariance matrix is S=(9334). What is its total variance?
  1. 19
  2. 13
  3. 6
  4. 36
Show answerHide answer
Answer: B
Total variance is the sum of the feature variances on the diagonal, giving 9 + 4 = 13. The two entries equal to 3 describe shared movement between features. Adding every matrix entry would count those covariances too and would not measure total variance.

Question 6 of 10

What constraint makes the maximum-variance definition of PC1 meaningful?
  1. The loading vector has length 1.
  2. The loading entries sum to 1.
  3. The observation scores sum to 1.
  4. The component variance equals 1.
Show answerHide answer
Answer: A
A unit-length loading vector lets PCA compare directions on equal terms. Without this constraint, multiplying a direction vector would increase its score variance indefinitely. Requiring weights to sum to 1 is a different constraint and is not the definition of ordinary PCA.

Question 7 of 10

Two analyses return PC1 loadings and scores with all signs reversed. The eigenvalue is unchanged. How do their one-component reconstructions compare?
  1. They flip in sign.
  2. Their errors double.
  3. Their columns reverse.
  4. They are identical.
Show answerHide answer
Answer: D
Each reconstructed contribution is score times loading vector. Reversing both signs leaves that product unchanged, so the reconstructed observations are identical. Reversing only the scores while leaving the loadings fixed would reflect the projected positions, but that is not the stated change.

Question 8 of 10

A table combines duration in seconds and mass in kilograms, with no reason to prioritize either feature’s spread. What preparation is the sensible starting choice?
  1. Center and standardize both features.
  2. Center both and retain their raw scales.
  3. Scale only the feature with larger values.
  4. Use raw columns and center the scores.
Show answerHide answer
Answer: A
Standardizing puts both features on a common variance scale before PCA. Centering alone removes their means but leaves the different numerical spreads, so the unit choices can dominate PC1. The choice should reflect measurement meaning, and this scenario gives no reason to privilege either raw scale.

Question 9 of 10

A data set has two component variances, 9.6 and 0.4. A hand rule retains the smallest count reaching 95% PVE. The target classes overlap along PC1 and are separated only along PC2. What is the outcome of applying this rule?
  1. It keeps two components and preserves the separating direction.
  2. It keeps one component and preserves the separating direction.
  3. It keeps one component and removes the separating direction.
  4. It keeps two components and removes the separating direction.
Show answerHide answer
Answer: C
Total variance is 10, so PC1 alone retains 96% and meets the 95% threshold. The rule therefore discards PC2, which the stated classes need for separation. The retained variance exceeds the threshold, but this does not establish that the representation retains the information needed for classification.

Question 10 of 10

For S=(8222), an analyst calls (2,1) a unit direction and reports variance 42 along it. What is the variance along the corresponding unit direction?
  1. 42
  2. 8.4
  3. 21
  4. 18.8
Show answerHide answer
Answer: B
The direction vector has squared length 5, and its quadratic form is 4(8)+2(2)(2)+2=42. Normalizing both sides of the quadratic form divides by 5, giving 8.4. Dividing only by the length, rather than its square, would leave the variance incorrectly scaled.
Set 2: Calculate and interpret principal components10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A covariance matrix has eigenvalues 7.2, 0.5, and 2.3. Which is the variance of PC2?
  1. 0.5
  2. 2.3
  3. 7.2
  4. 10.0
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What are the eigenvalues of S=(4224)?
  1. 4 and 4
  2. 8 and 0
  3. 6 and 4
  4. 6 and 2
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A leading eigenvector is proportional to (3,4). What unit loading vector has positive entries?
  1. (0.6,0.8)
  2. (3/7,4/7)
  3. (0.8,0.6)
  4. (0.36,0.64)
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A centered observation is (3,−1) and a loading vector is (0.6,0.8). What is its score?
  1. 2.6
  2. −1.0
  3. 1.0
  4. 1.4
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A component weights standardized production output positively and defect rate negatively. What does a high score tend to describe?
  1. High output and high defect rate
  2. Low output and low defect rate
  3. High output and low defect rate
  4. Low output and high defect rate
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A sample-standardized variable has loading 0.4 on a component with eigenvalue 2.25. What is their correlation?
  1. 0.60
  2. 0.40
  3. 0.90
  4. 0.27
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An analysis has 6 observations and 20 features. What is the largest possible number of nonzero-variance centered components?
  1. 6
  2. 19
  3. 20
  4. 5
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Two features have covariance matrix (2112). Keep PC1 and project the centered point (2,0). What point in the centered feature plane results?
  1. (2,0)
  2. (1,1)
  3. (2,2)
  4. (1,−1)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A two-axis correlation biplot gives two variables short arrows pointing in the same direction, while omitted PCs retain substantial variation. What can be concluded about their full correlation?
  1. Their full correlation must be close to +1 because the arrows point together.
  2. Their full correlation must be zero because both arrows are short in the plane.
  3. Their displayed contributions align, but omitted contributions can change the full correlation.
  4. Their full correlation equals the product of the two displayed arrow lengths.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A covariance matrix is (3113). An analyst proposes PC1 slope 1/3 because that is the regression slope of y on x. What is the PCA slope?
  1. 1
  2. 1/3
  3. 3
  4. −1
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

A fitted analysis has total variance 12 and PC1 eigenvalue 4.8. What proportion does PC1 explain?
  1. 40%
  2. 48%
  3. 25%
  4. 57.6%
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Eigenvalues are 3.2, 1.6, 0.8, and 0.4. A hand rule keeps the smallest count reaching at least 90% cumulative PVE. How many components are kept?
  1. 2
  2. 4
  3. 3
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A correlation matrix has eigenvalues 2.4, 1.0, 0.4, and 0.2. How many does the eigenvalue-greater-than-one rule keep?
  1. 2
  2. 3
  3. 4
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A length column is changed from meters to millimeters before an unscaled PCA. How does that column’s variance change?
  1. It is multiplied by 1,000.
  2. It is multiplied by 1,000,000.
  3. It is divided by 1,000,000.
  4. It stays unchanged after centering.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Eight sample-standardized features are exactly uncorrelated. How much variance can any two principal components retain?
  1. 50%
  2. 25%
  3. 75%
  4. 100%
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A fit has mean (5,7) and retained unit direction (0.6,0.8). For original point (7,6), what is the one-component reconstruction?
  1. (0.24,0.32)
  2. (6.2,8.6)
  3. (5.24,7.32)
  4. (5.72,7.96)
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A sample of 21 observations has eigenvalues 5, 2, and 0.5. The analyst keeps one component. What are the total squared reconstruction error and lost variance share?
  1. 50 and about 33.3%
  2. 2.5 and about 33.3%
  3. 50 and about 66.7%
  4. 52.5 and about 33.3%
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A table has 600 observations and 200 features. A PCA archive keeps 10 components and stores scores, loadings, and means. What fraction of the original number count is stored?
  1. 5.0%
  2. About 1.8%
  3. About 68.3%
  4. About 6.8%
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two sample-standardized features correlate at −0.6. Which PC1 pattern and PVE should result?
  1. Same-sign equal weights; 80%
  2. Opposite-sign equal weights; 60%
  3. Same-sign equal weights; 20%
  4. Opposite-sign equal weights; 80%
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

Three candidate PCA counts retain 70%, 88%, and 96% variance. Their full-pipeline cross-validation accuracies are 0.84, 0.90, and 0.86. Using mean validation accuracy, which should be selected for prediction?
  1. The count retaining 88%
  2. The count retaining 96%
  3. The count retaining 70%
  4. The count with the best test accuracy
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

A PCA fit keeps 3 components from 14 features. What is the shape of components_?
  1. (14, 3)
  2. (3, 3)
  3. (14, 14)
  4. (3, 14)
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A two-component fit reports explained_variance_ratio_ = [0.46, 0.29]. What can this output establish?
  1. PC2 retains 29% of the variation remaining after PC1.
  2. The model correctly predicts 75% of held-out cases.
  3. The two components retain 75% of fitted total variance.
  4. The two ratios must be rescaled to sum to 100%.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Two observations overlap on PC1 and PC2 but have PC3 scores −3 and 3. What does the overlap tell you about their full distance?
  1. It hides a separation of at least 6 score units.
  2. It establishes a full distance of zero score units.
  3. It limits their full distance to at most 6 score units.
  4. It establishes a full distance of exactly 3 score units.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A plot stretches PC2 so one vertical score unit is twice as long as one horizontal score unit. What change makes the visual distances faithful to ordinary PCA scores?
  1. Divide both score columns by their own variances.
  2. Give both axes the same displayed length per unit.
  3. Standardize both score columns to unit variance.
  4. Fit PCA again using the existing component scores.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A PCA classifier receives a new batch with a shifted feature mean. How should it obtain scores for prediction?
  1. Apply the stored training scaler and PCA.
  2. Fit a new scaler and PCA to the new batch.
  3. Center the batch on its own mean first.
  4. Rescale the batch, then apply training PCA.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A team scales all rows, then cross-validates a PCA–regression pipeline on those scaled rows. Test rows were included in the first scaling. What repair makes the evaluation independent?
  1. Keep the global scaling; move only regression into each cross-validation training fold.
  2. Split after global PCA; cross-validate a scaler–regression pipeline on component scores.
  3. Split raw rows first; cross-validate a scaler–PCA–regression pipeline on training rows.
  4. Keep the global scaling and PCA; reserve target labels when fitting the regression.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An analyst fits StandardScaler to 11 observations with 3 nonconstant features, then fits full PCA. What eigenvalue sum and ratio sum should be expected?
  1. 3.0 and 1
  2. 3.3 and 1.1
  3. 3.0 and 1.1
  4. 3.3 and 1
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A five-fold search uses a training set of 30 rows and 40 features, with equally sized folds. Which candidate list stays within the upper bound for nonzero-variance components in every training fold?
  1. [5, 24, 30]
  2. [5, 12, 23]
  3. [12, 30, 40]
  4. [5, 23, 24]
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A linear model uses two standardized-feature PCA scores, with coefficients 2 and −1. Feature A has loadings 0.6 and −0.8 on those components and training standard deviation 4. What is its coefficient in original feature units?
  1. 2.0
  2. 0.5
  3. 0.1
  4. 8.0
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A full-solver PCA fit requests 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?
  1. (12, 2)
  2. (3, 12)
  3. (12, 3)
  4. (2, 12)
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

A t-SNE run uses 28 observations. Which perplexity is valid?
  1. 28
  2. 20
  3. 30
  4. 40
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A UMAP map becomes much more tightly clumped after only min_dist is reduced. What is the direct explanation?
  1. The map allows closer packing of embedded points.
  2. The original features now have smaller variances.
  3. The number of original-space neighbors has increased.
  4. The data now have more confirmed population groups.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A team wants feature weights explaining the main variation across questionnaire responses. Which output directly meets that need?
  1. UMAP coordinate values
  2. t-SNE cluster centers
  3. PCA loading vectors
  4. UMAP group distances
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A t-SNE display has one group with twice the visible area of another. What should an analyst infer about the original groups’ spread?
  1. The first original group has twice the total variance of the second.
  2. The first original group has four times the spread of the second.
  3. The two original groups must have the same spread before mapping.
  4. The area ratio alone does not determine their original spread ratio.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A fitted UMAP model will place new raw observations. Its training data were standardized first. What is the compatible sequence?
  1. New scaler fit, then stored UMAP transform
  2. Stored scaler transform, then new UMAP fit
  3. New UMAP fit, then stored scaler transform
  4. Stored scaler transform, then stored UMAP transform
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A t-SNE map of a sample is used to train a classifier. The team plans to serve new cases using scikit-learn TSNE and the existing classifier. What breaks, and what is a viable alternative?
  1. TSNE lacks a fitted transform; refit a new map for each batch and reuse the classifier.
  2. TSNE lacks a fitted transform; validate a training-fitted PCA or UMAP pipeline instead.
  3. TSNE axes lack variance shares; standardize the map and reuse it for new observations.
  4. TSNE is unsupervised; include the target as a numeric feature before fitting each map.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A low-perplexity t-SNE map shows tiny groups. Some disappear at broader perplexities and different seeds; original features have not yet been checked. What is the strongest next analysis?
  1. Compare persistent neighborhoods and inspect the proposed groups in original features.
  2. Count every low-perplexity island and report that count as the number of populations.
  3. Choose the seed with the clearest gaps and treat that map as the definitive partition.
  4. Measure gap lengths in the broadest map and rank population differences from them.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A team must map 35,000 curved-feature observations, later add new cases, and explain each axis with linear feature weights. Which design addresses all three aims honestly?
  1. Use UMAP alone and interpret each coordinate as a fixed linear combination of the features.
  2. Use t-SNE alone and project later observations onto its fitted loading vectors.
  3. Use UMAP for the reusable nonlinear map and a separate PCA analysis for linear interpretation.
  4. Use a two-component PCA alone and describe its axes as a nonlinear neighborhood graph.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Two PCA fits on similar small samples give nearly identical leading two-dimensional planes, but PC1 and PC2 rotate strongly within those planes. Their first two eigenvalues are close. What is the best interpretation?
  1. The rotated loadings show that the two planes must be unrelated.
  2. The fit with the larger positive PC1 weights has the correct orientation.
  3. The retained plane can be stable while its individual axes are unstable.
  4. The close eigenvalues guarantee independently reproducible individual axes.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A sensor archive is compressed after standardization. One reconstruction has smaller total squared standardized error but larger squared error in original units than another. Which assessment is correct?
  1. The objectives weight features differently; PCA’s optimum applies in its fitted scale.
  2. The objectives must rank every reconstruction identically because both use squares.
  3. The original-unit ranking shows the PCA eigenvalues were necessarily sorted incorrectly.
  4. The standardized ranking shows inverse scaling should have been omitted from reconstruction.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

71 Key Terms, each with its definition

B

Batch effect
A batch effect is a systematic measurement difference between collection groups, such as days or machines, that can dominate visible component patterns.
Points colored by recording day may separate because the instrument changed, even without a substantive group difference.
Biplot
A biplot displays observations and variables together in a component plane, with interpretation depending on how points and arrows are scaled.
An analyst checks the arrow scaling before interpreting a biplot’s angles as feature relationships.

C

Centering
Centering subtracts each feature’s mean from its values, putting the average observation at zero while retaining differences between rows.
Subtracting a mean length of 12 cm expresses every measured length as a deviation from 12 cm.
components_
The components_ attribute stores one unit loading vector per row of a fitted scikit-learn PCA object, in input-feature order.
Transposing components_ puts the original feature names down the rows of a readable loading table.
Compression
Compression stores a reduced representation using fewer numbers, with PCA requiring scores, retained loadings, and means for reconstruction.
For many observations, the loading vectors can be shared instead of stored separately for every row.
Correlation biplot
A correlation biplot uses variable–component correlations as arrow coordinates and correspondingly rescales the observation scores.
A short arrow shows that the two displayed components leave much of that variable’s variation hidden.
Correlation matrix
A correlation matrix contains pairwise feature correlations and has diagonal entries of 1 for nonconstant features.
PCA on sample-standardized measurements uses this matrix to give each feature equal starting variance.
Correlation-based PCA
Correlation-based PCA analyzes sample-standardized features, giving each nonconstant feature variance 1 before choosing component directions.
Two features with correlation 0.7 give a leading eigenvalue of 1.7 on this equal-variance scale.
Covariance matrix
A covariance matrix is a symmetric square matrix with feature variances on its diagonal and pairwise covariances off the diagonal.
For five measured features, the covariance matrix has five rows and five columns in feature order.
Covariance-based PCA
Covariance-based PCA analyzes centered features without equalizing their variances, so original numerical measurement scales affect the axes.
Large mass variance can dominate an unscaled fit when height is recorded in meters instead of centimeters.
Cross-validation
Cross-validation compares performance across training and validation splits so model settings can be selected without tuning on the final test set.
Component counts are compared by the downstream model’s validation metric, not by training accuracy alone.
Cumulative PVE
The cumulative PVE is the sum of the variance shares of the leading components through a chosen count, showing total retained spread.
The first two shares, 45% and 30%, give 75% retained variance in their joint component plane.
Cumulative threshold rule
The cumulative threshold rule keeps the smallest leading-component count whose cumulative PVE reaches a selected retained-variance level.
A hand threshold of at least 90% keeps three components if two retain 87% and three retain 94%.
Curse of dimensionality
The curse of dimensionality describes problems caused by sparse coverage and broad neighborhoods as feature count increases.
A nearest-neighbor model may need many more observations to maintain useful local neighborhoods.

D

Data leakage
Data leakage occurs when information from held-out observations enters fitting or selection, weakening the independence of evaluation.
Fitting PCA to the complete table before splitting exposes the axes to the future test observations.
Data matrix
A data matrix is a rectangular array whose rows hold observations and whose columns hold the measured features used in an analysis.
In a sensor table, a row contains one recording and a column contains one measurement across recordings.
Denoising
Denoising removes unwanted random variation; discarding small PCA components can help when those directions contain mostly noise.
Smoother reconstructed images can also lose genuine detail that occupied the discarded directions.
Determinant equation
The determinant equation sets the determinant of S − λI to zero to find the eigenvalues of the covariance matrix S.
For a two-feature covariance matrix, expanding this equation gives a quadratic in the eigenvalue.
Dimension
The dimension of a feature space is the number of feature coordinates measured on each observation, regardless of the number of rows.
A table of 900 observations with 25 measured features describes points in a 25-dimensional space.
Dimensionality reduction
Dimensionality reduction represents observations with fewer coordinates while aiming to retain structure useful for a particular task.
An analyst uses a few scores to visualize a table whose original measurements need dozens of axes.
Discarded variance
The discarded variance is the sum of the eigenvalues for components left out of a reduced representation in the fitted feature scale.
Keeping 92% of the total variance leaves 8% in the component directions omitted from reconstruction.

E

Eigenvalue
An eigenvalue is the scalar multiplier paired with an eigenvector; for PCA it equals the variance of scores along that unit direction.
A component with eigenvalue 4 contains four variance units in the scale used to fit the analysis.
Eigenvector
An eigenvector is a nonzero direction that a matrix maps to a scalar multiple of itself; normalized covariance eigenvectors define PCA axes.
Multiplying a loading vector by the covariance matrix leaves its direction unchanged, up to sign.
Elbow rule
The elbow rule chooses a count near the point where a scree curve’s sharp decrease changes to a flatter tail, requiring visual judgment.
A gradual bend may leave several plausible counts instead of one clearly defined elbow.
Embedding
An embedding is a representation of observations in new coordinates; nonlinear map axes do not carry PCA-style feature weights or PVE.
Labels such as “UMAP 1” identify map coordinates without naming a measured feature or variance share.
Equal aspect ratio
An equal aspect ratio gives one horizontal coordinate unit the same displayed length as one vertical unit, preserving plotted distance geometry.
Setting an equal aspect ratio prevents a smaller-variance PC2 from looking wider through axis stretching.
explained_variance_ratio_
The explained_variance_ratio_ attribute holds each retained component’s share of the complete variance, not a share of only the kept components.
Two stored ratios may sum to 0.8 because the remaining 20% belongs to components excluded by the fit.

F

Feature extraction
Feature extraction constructs new variables from the original features, such as the weighted combinations produced by PCA.
A combined size score can summarize overlapping variation in height and arm span measurements.
Feature scale
A feature scale is the numerical size of a feature’s differences, determined by its unit and spread and changed by standardization.
Recording a length in millimeters multiplies its variance even though the physical lengths are unchanged.
Feature selection
Feature selection keeps a subset of the original measured columns, preserving their names and direct measurement meanings.
Keeping three sensor columns from a table of fifteen reduces the measurements needed for later cases.
fit
The fit method learns a transformation’s parameters from the supplied data, such as feature means, scales, or principal component directions.
Calling 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.
The parameter name pca__n_components addresses the PCA count inside a pipeline step named pca.

H

Held-out test set
A held-out test set contains observations reserved for final evaluation after fitting and model selection decisions have been completed.
Repeatedly choosing component counts by test accuracy would convert this evaluation data into tuning data.
Hyperparameter
A hyperparameter is a model or workflow setting chosen outside the direct fit, such as the number of components passed to a predictor.
Cross-validation compares several component counts before the final pipeline is fitted on all training rows.

I

Imputation
Imputation fills missing feature values using a chosen rule or fitted model before an analysis that requires complete numeric input.
A training-fitted median imputer can fill missing sensor readings before scaling and PCA.
Inverse transformation
An inverse transformation maps component scores back into the feature coordinates supplied to PCA, restoring only the retained variation.
After inverse PCA on scaled data, reversing the scaler returns reconstructed values to measurement units.

K

Kaiser’s rule
Kaiser’s rule retains correlation-based components whose eigenvalues are strictly above 1, using one standardized feature as a benchmark.
An eigenvalue of 0.9 is excluded by this rule even when needed to reach a cumulative threshold.

L

Linear structure
Linear structure is variation describable by straight directions in feature space, the kind of structure summarized by ordinary PCA.
An evenly sampled circle has a simple curved pattern but no single dominant linear direction.
Loading
A loading is a feature’s weight in a unit component direction; some conventions instead use the feature’s correlation with the component.
Check the convention before comparing a scikit-learn loading table with a correlation-based table.
Loading vector
A loading vector is a unit-length vector of feature weights that defines a principal component’s direction in the prepared feature space.
A two-feature loading vector of (0.6, 0.8) assigns both measurements positive score contributions.
Local neighborhood
A local neighborhood is a set of nearby observations in the prepared feature space, used to define relationships retained by nonlinear maps.
A point’s nearest measurements matter more to t-SNE than the exact distance to a distant group.

M

min_dist
The min_dist setting controls how tightly UMAP points may pack in an embedding, with smaller values allowing more compact groups.
A group can appear denser after reducing min_dist even though none of the original measurements changed.

N

n_components_
The n_components_ attribute reports how many components a fitted PCA retained, including a count chosen from a fractional variance request.
After a full-solver 0.95 request, inspect n_components_ to learn how many score columns were selected.
n_neighbors
The n_neighbors setting controls the breadth of UMAP’s original-space neighborhoods, with larger values emphasizing broader connections.
Increasing n_neighbors can smooth fine local detail while showing more of the overall arrangement.
Normalization
Normalization of a direction divides a vector by its length, making its squared entries sum to 1 without changing the line it describes.
Dividing the vector (3, 4) by 5 gives a valid unit direction for projecting prepared observations.

O

Orthogonality
Orthogonality is perpendicularity between vectors, expressed by a zero dot product; PCA loading directions are chosen this way.
Perpendicular loading vectors give component score columns with zero covariance in the fitted sample.
Outlier
An outlier is an observation unusually far from the main data pattern; its large squared deviations can strongly influence ordinary PCA.
An isolated score prompts a check of the original measurement record before any deletion is considered.

P

Perplexity
Perplexity sets a rough neighborhood scale in t-SNE and must be smaller than the observation count; it is not a requested cluster count.
An analyst compares perplexities 10 and 35 to see whether a visible local pattern persists.
Pipeline
A pipeline links fitted preparation and prediction steps in order, keeping transformations consistent and refitting them within training folds.
A scaler–PCA–classifier pipeline learns its preparation separately inside each cross-validation split.
Principal component
A principal component is a weighted combination of centered features with a unit loading vector, chosen to maximize variance along successive perpendicular directions.
PC1 follows the broadest spread, and PC2 follows the broadest direction perpendicular to it.
Principal components regression
Principal components regression fits linear regression on retained PCA scores, using directions chosen from feature variation without the response.
A small-variance component may predict the response well, making cross-validation important when choosing its count.
Projection
A projection keeps the part of a prepared observation along selected directions, discarding its coordinates in the perpendicular directions.
Two observations can overlap in a projected plane yet remain separated along an omitted component.
Proportion of variance explained
The proportion of variance explained is a component’s eigenvalue divided by the full eigenvalue sum, measuring its share of fitted spread.
An eigenvalue of 2 out of total variance 5 gives a PVE of 40%, independent of any class labels.

R

Random seed
A random seed initializes stochastic computations so a run can be reproduced under the same software and settings, without validating its interpretation.
Using random_state=42 reproduces one map; trying other seeds helps assess whether its patterns persist.
Reconstruction
A reconstruction approximates original feature values by adding retained score-weighted loading vectors to the fitted mean.
A point reconstructed from one component lies on that component’s line through the data mean.
Reconstruction error
The reconstruction error measures the difference between original and rebuilt features, commonly as summed squared residual coordinates.
A point with a large discarded score has a large squared error when that direction is omitted.

S

Sample covariance
The sample covariance is the average centered cross-product using denominator n − 1, describing how two variables vary together.
A positive covariance between two sensor readings means their deviations often have the same sign.
Sample variance
The sample variance is the sum of squared deviations from a sample mean divided by one less than the number of observations.
A feature with widely scattered measurements has a larger sample variance than a tightly grouped feature.
Sampling instability
Sampling instability is variation in estimated component directions across samples, especially with few observations or closely spaced eigenvalues.
Two fitted axes may rotate within a similar plane when the leading eigenvalues are almost tied.
Score
A score is an observation’s coordinate on a component, calculated by applying the component’s weights to its prepared feature values.
Two people with different measurements can receive the same PC1 score while differing on PC2.
Score plot
A score plot displays observations at coordinates supplied by selected component scores, often PC1 and PC2 with their variance shares labeled.
Coloring a score plot by class can reveal alignment between labels and the leading variation directions.
Scree plot
A scree plot shows component number against eigenvalue or individual PVE, with decreasing values that reveal a large-component head and small tail.
A steep early drop followed by a flatter tail suggests a compact group of substantial components.
Sign ambiguity
Sign ambiguity means a component can reverse all its loadings and scores without changing its line, explained variance, or reconstruction.
A second software library may mirror a score plot while representing the same fitted components.
Standardization
Standardization subtracts a feature’s mean and divides by its standard deviation, putting nonconstant features on a common spread scale.
Standardizing height and mass prevents meters versus centimeters from deciding the PCA weighting.

T

t-SNE
t-SNE is a stochastic nonlinear mapping method that arranges observations to emphasize original-space neighbor relationships in a small map.
A t-SNE plot can separate nearby digit patterns more clearly than a two-component linear projection.
Total variance
The total variance is the sum of the prepared feature variances, equal to the covariance matrix’s diagonal sum and full eigenvalue sum.
A PCA eigenvalue check compares the sum of component variances with the original diagonal total.
Trace
The trace of a square matrix is the sum of its diagonal entries, equal to total variance when the matrix is a covariance matrix.
If component eigenvalues do not sum to the trace, check the arithmetic and the omitted components.
transform
The transform method applies an already fitted transformation without estimating a new set of means, scales, or component directions.
A test table passes through the stored scaler and PCA using transform at each preparation step.

U

UMAP
UMAP is a nonlinear method that builds a weighted nearest-neighbor graph and arranges lower-dimensional points to retain similar connections.
A fitted UMAP mapper can place new observations after they receive the same training-fitted preparation.
Unsupervised learning
Unsupervised learning finds structure in features without using a target label to decide which patterns the fitted method should retain.
PCA can be fitted before class labels are added as colors to a finished observation score plot.

V

Variable–component correlation
A variable–component correlation measures linear association between a feature and a component, distinct from its unit-vector weight.
For sample-standardized inputs, multiply the loading by the square root of the matching eigenvalue.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started