Skip to learning content

DATA SCIENCE PYTHON PLAYGROUND

Machine Learning · Learn / Refresh

← Regression lessons
Several predictors · ML-R06 · 12–18 MIN

Correlated predictors and unstable coefficients

Separate coefficient stability from predictive stability.

  1. FollowRead and run the PythonCurrent exercise
  2. ChangeAdapt one part
  3. TransferCompute and inspect the evidence

Understand the idea

Highly correlated inputs can exchange coefficient weight with little change in predictions. This makes individual effects difficult to interpret. The Change round keeps X fixed and perturbs y slightly, measuring both coefficient sensitivity and prediction sensitivity. It is a controlled fitted-state experiment, not a held-out performance comparison.

Separate coefficient stability from predictive stability.Near-copy inputs: shared signalCoefficients can shiftCompare predictions as well as fitted coefficients.Predictive stability does not establish a unique feature effect.
Separate coefficient stability from predictive stability.Scroll the diagram horizontally if needed.

What the syntax does

rng.normal(0, .001, len(df))
  • Creates a small reproducible perturbation for each observation.
pd.Series(model.coef_, index=X.columns)
  • Labels the jointly fitted coefficients, including the near-duplicate input.

Outputs you create

answer
  1. The requested result, with the values, labels and row order described by this task.
MIX60 · first 8 rows
distanceweightserviceweekendduration
15.70526.75035standard061.7704
9.338694.81674express135.1694
17.31345.73931economy059.0766
14.257.69699standard156.5785
2.789376.42024express019.5577
19.53685.62508economy177.0289
15.46175.68023standard056.8109
15.93523.17871express152.08
Your task
  1. Fit a line using distance and a near-copy of distance.
  2. Store the two coefficients in answer, labelled by their feature names.
answer
Hints

Think: Nearly duplicate predictors can share the same predictive contribution in unstable proportions.

Tools: Seeded noise, dataframe construction and LinearRegression.coef_.

Approach: Create the near-copy column, fit both columns together and label the resulting coefficients.

Explained solution
from sklearn.linear_model import LinearRegression
rng=np.random.default_rng(42)
X=pd.DataFrame({'distance':df.distance,'near_copy':df.distance+rng.normal(0,.001,len(df))})
model=LinearRegression().fit(X,df.duration)
answer=pd.Series(model.coef_,index=X.columns)

The tiny perturbation preserves strong correlation; inspecting both coefficients exposes instability that prediction quality alone can conceal.

Ctrl/⌘+Enter: Run · Tab: indent · Esc then Tab: leave editor

Python loads when you run. Code and results stay in this activity only.

Run your code to inspect its output. Check uses that same run.