Saltar al contenido

Lección 14 · Many Variables

Correlation Matrices and Pair Plots

Screen many numeric variables with correlation matrices, heatmaps and pair plots, find redundant columns and avoid the traps of reading hundreds of pairs.

Multivariate analysis looks at three or more variables. With 10 numeric columns there are already 45 pairs. A correlation matrix summarizes them all in one grid, and a pair plot draws them. Both are screening tools: they tell you where to look next.

Reading a correlation matrix

Each row and column is a variable. Each cell is the correlation of that pair. The diagonal is 1 for any column that varies, and the matrix is symmetric, so you only need half.

Python A correlation matrix from scratch

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

All values here are invented. Read the matrix like this: size and price move together strongly; size and rooms also move together, because we built rooms from size; age has a negative link with price and little link with size.

Heatmaps

A heatmap colors each cell. Use a diverging color map centered at zero, so that positive and negative values look different, and fix the limits at -1 and 1.

Python Heatmap with fixed color limits

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

White text or black text may read better on strong colors; adjust it for a published chart. The seaborn function heatmap creates this in fewer lines; see correlation heatmaps.

What a matrix hides

A matrix inherits every weakness of a single correlation: Pearson shows only linear association (Spearman shows rank order), and Pearson in particular can be driven by outliers. Mixed groups affect both. Also check:

  • How many pairs each cell used. With missing values, pandas computes each pair from its own available rows, so cells may describe different subsets.
  • Which columns were left out. Categories and text need other methods.
  • Fake numbers. Identifiers and codes may be numeric but meaningless to correlate.

Rank the pairs

With many columns, a sorted list is easier to read than a grid.

Python Strongest pairs first

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Sort by the absolute value, so that strong negative links are not buried at the bottom.

Redundant variables

Very strongly correlated columns may carry nearly the same information, such as height in centimeters and in inches, or a price and a tax computed from it. In EDA, ask why. In later modeling, near-duplicate predictors can make individual effects unstable, a problem called multicollinearity. A high correlation alone does not tell you which column to remove; meaning and data quality should guide that.

Pair plots

A pair plot (scatter plot matrix) shows a scatter plot for each pair and a distribution for each variable. It reveals curves, clusters and outliers that the numbers hide. pandas offers pd.plotting.scatter_matrix, and seaborn offers pairplot.

Pair plots become unreadable beyond a handful of columns. Pick the variables that matter to your question, sample large datasets and color points by one category.

Screening many variables

Matrix Find candidates
Plot Inspect each candidate
Think What could explain it?
Retest Use new data
1 / 2

Chance findings

When you scan many pairs, some will look related by chance, especially with few rows. Try it: 20 random columns of 15 values each give 190 pairs.

Python Correlations in pure noise

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Every column is independent noise, yet some pairs look convincing. Treat surprising matrix hits as leads to verify.

Do not build a story around the darkest cell in a heatmap before you plot that pair and consider chance, shared causes and calculated columns.

A practical screening routine

  1. Remove identifiers and codes from the list of numeric columns.
  2. Check missing values and constant columns. A column with a single value has no defined correlation.
  3. Compute the matrix, and look at both Pearson and rank correlation. A large difference between them is a reason to plot the pair.
  4. List the strongest pairs and the pairs that surprise you, including surprisingly weak ones.
  5. Plot each listed pair, colored by an important category.
  6. Write one line per pair: expected, explained by construction, data problem or lead to investigate.

The surprisingly weak pairs are easy to forget. If advertising spend and visits show no association at all, that is worth a question about data alignment, delays or the grain of each column.

Try it yourself

In the first example, add a column called size_ft2 that multiplies size by 10.76. Look at its correlations. Then add a random ID column and see what values it gets. Explain why neither result teaches you anything new about houses.

Keep screening separate from claims

Label the output of this stage as screening. A list of strong pairs is a to-do list for investigation, not a list of findings. If you share a heatmap, say how many variables and rows went into it, which correlation measure you used and how you treated missing values. Without that note, readers may treat every dark cell as an established fact.

If you will use the same data to build a model later, be aware that choosing variables because they correlate with the outcome is already a modeling step. To judge the model fairly, make that choice without looking at the data you reserve for testing.

Check important subsets

Repeat the matrix for one or two meaningful subsets, such as each year or each product type, and compare. A pair that keeps its direction and rough strength is a steadier lead than one that changes sign. Remember that smaller subsets vary more by chance, so show the row count for each matrix and avoid reading small differences between them.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why use fixed limits of -1 and 1 with a diverging color map?

    Automatic limits could make weak values look extreme.
  2. 2. Why sort pairs by absolute correlation?

    Strength is the size of r, regardless of its sign.
  3. 3. With missing values, what should you check in a pandas correlation matrix?

    Each cell may be computed from a different set of rows.
  4. 4. You find one strong correlation after screening 500 pairs. What is the best view of it?

    With many comparisons, some strong values appear by chance.

Summary

  • Correlation matrices and pair plots screen many variables quickly.
  • Use diverging colors with fixed limits, or rank pairs by absolute value.
  • Check pair counts, left-out columns and meaningless numeric codes.
  • Near-duplicate columns deserve a look at how they were produced.
  • Many comparisons create chance findings.

Next: Confounders and Simpson's Paradox

Tu progreso se guarda en este navegador. No necesitas una cuenta.