Multiple Linear Regression and Feature Importance
Learners will extend the model to multiple input features, interpret each coefficient as feature importance, and evaluate with R-squared.
Multiple Linear Regression and Feature Importance is a free Machine Learning Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Machine Learning Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Beyond a Single Feature
Real prediction problems almost always have multiple relevant inputs. House price depends on square footage, number of bedrooms, location, age, and dozens of other factors. Multiple linear regression extends the single-feature line to use all available features simultaneously:
ŷ = w₁x₁ + w₂x₂ + ... + wₙxₙ + b
Each feature gets its own weight, and the model learns all weights simultaneously by minimising MSE. Adding more relevant features almost always improves prediction accuracy — as long as those features genuinely carry information about the target.
import pandas as pd
import numpy as np
# Multi-feature housing dataset
np.random.seed(42)
n = 300
df = pd.DataFrame({
'sqft': np.random.randint(600, 4000, n),
'bedrooms': np.random.randint(1, 7, n),
'bathrooms': np.random.randint(1, 5, n),
'age': np.random.randint(1, 60, n),
'distance_to_center': np.random.uniform(1, 30, n)
})
df['price'] = (150 * df['sqft'] + 8000 * df['bedrooms']
- 300 * df['age'] - 5000 * df['distance_to_center']
+ 40000 + np.random.normal(0, 20000, n))
print(df.head())Training with Multiple Features
The scikit-learn API is identical for one feature or one hundred features — you simply pass the full feature matrix. The model automatically fits one coefficient per column in X.
With multiple features, R² typically increases compared to the single-feature model, because each additional informative feature provides the model with more signal to work with. However, adding irrelevant or noisy features can actually hurt performance by introducing overfitting, especially on small datasets.
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
import pandas as pd
import numpy as np
# (df defined in previous scene)
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
X = df[features]
y = df['price']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print(f'Multi-feature R2: {r2_score(y_test, y_pred):.3f}')Inspecting the Coefficients
After fitting a multi-feature model, model.coef_ is an array with one value per feature. Each value is the predicted change in y for a one-unit increase in that feature, assuming all other features are held constant.
For example, a coefficient of 150 for sqft means: controlling for bedrooms, age, and all other features, one additional square foot is predicted to add $150 to the price. This partial effect interpretation is what makes linear regression so useful for explaining which factors drive a prediction.
import pandas as pd
from sklearn.linear_model import LinearRegression
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
# Create a readable coefficient table
coef_df = pd.DataFrame({
'Feature': features,
'Coefficient': model.coef_
}).sort_values('Coefficient', ascending=False)
print(coef_df.to_string(index=False))
print(f'\nIntercept: {model.intercept_:,.0f}')Why Raw Coefficients Can Be Misleading
Raw coefficients are not directly comparable when features have different units and scales. In the housing model, sqft ranges from 600 to 4000 while bathrooms ranges from 1 to 5. A coefficient of 150 for sqft and 8000 for bedrooms does not mean bedrooms are 53x more important — it means a one-unit change in bedrooms (a huge change) has 53x the effect of a one-unit change in sqft (a tiny change).
To compare feature importance fairly, you must first standardise all features to the same scale (zero mean, unit variance). Then the coefficients reflect the effect of a one-standard-deviation change in each feature, which is comparable across features.
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler
import pandas as pd
import numpy as np
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
# Scale features to zero mean, unit variance
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train[features])
model_scaled = LinearRegression()
model_scaled.fit(X_train_scaled, y_train)
# Now coefficients ARE comparable
coef_df = pd.DataFrame({
'Feature': features,
'Standardised Coefficient': model_scaled.coef_
}).sort_values('Standardised Coefficient', key=abs, ascending=False)
print(coef_df.to_string(index=False))Feature Importance Bar Chart
Visualising standardised coefficients as a bar chart gives stakeholders an intuitive view of which features drive the model's predictions. Positive bars push the prediction up; negative bars push it down. The longer the bar, the greater the impact of a one-standard-deviation change in that feature.
This plot is one of the most persuasive tools for communicating model behaviour to non-technical audiences. It answers 'what matters?' in a single, easy-to-read chart.
import matplotlib.pyplot as plt
import numpy as np
feature_names = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
coeffs = model_scaled.coef_
colors = ['steelblue' if c > 0 else 'salmon' for c in coeffs]
plt.figure(figsize=(8, 5))
plt.barh(feature_names, coeffs, color=colors)
plt.axvline(x=0, color='black', linewidth=0.8)
plt.xlabel('Standardised Coefficient (impact per 1 std dev)')
plt.title('Feature Importance from Linear Regression')
plt.tight_layout()
plt.show()R-Squared and Adjusted R-Squared
Regular R² always increases (or stays the same) when you add more features, even if those features are random noise. This makes it a misleading metric for model selection with different numbers of features.
Adjusted R² corrects for this by penalising for each additional feature: Adj R² = 1 - (1-R²)(n-1)/(n-p-1), where n is the number of samples and p is the number of features. If an added feature does not improve the model enough to justify its complexity, Adjusted R² decreases. Use Adjusted R² when comparing models with different numbers of features.
from sklearn.metrics import r2_score
import numpy as np
def adjusted_r2(y_true, y_pred, n_features):
r2 = r2_score(y_true, y_pred)
n = len(y_true)
adj = 1 - (1 - r2) * (n - 1) / (n - n_features - 1)
return adj
y_pred_test = model.predict(X_test[features])
r2 = r2_score(y_test, y_pred_test)
adj_r2 = adjusted_r2(y_test, y_pred_test, n_features=len(features))
print(f'R2: {r2:.4f}')
print(f'Adjusted R2: {adj_r2:.4f}') # slightly lower, penalises complexityMulticollinearity: Correlated Features
Multicollinearity occurs when two or more features are highly correlated with each other. For example, sqft and number_of_rooms often move together — bigger houses have more rooms. When features are highly correlated, the model cannot reliably estimate individual coefficients because it cannot distinguish which feature is actually responsible for the effect on y.
Symptoms include: coefficients that change dramatically when you add or remove a single feature, very large coefficient values with opposite signs, or high R² but all coefficients with large standard errors. The Variance Inflation Factor (VIF) is the standard diagnostic for multicollinearity.
import pandas as pd
import numpy as np
# Detect multicollinearity via correlation matrix
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
corr = df[features].corr()
print('Feature correlation matrix:')
print(corr.round(2))
# High correlation (>0.7) between two features indicates multicollinearity
high_corr = (corr.abs() > 0.7) & (corr != 1.0)
print('\nHighly correlated pairs:')
print(high_corr)Feature Selection: Adding and Removing Features
Not all features improve model performance. Adding irrelevant features increases complexity and can hurt generalisation. A disciplined approach to feature selection involves comparing models with different subsets of features using cross-validated Adjusted R².
Iterative forward selection adds one feature at a time, keeping it only if it improves the validation score. Recursive feature elimination (RFE) removes the least important feature iteratively. Scikit-learn provides both approaches.
from sklearn.feature_selection import RFE
from sklearn.linear_model import LinearRegression
import pandas as pd
import numpy as np
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
X_all = df[features].values
y_all = df['price'].values
# Keep the top 3 most informative features
rfe = RFE(estimator=LinearRegression(), n_features_to_select=3)
rfe.fit(X_all, y_all)
selected = [f for f, s in zip(features, rfe.support_) if s]
print('Selected features:', selected)Prediction on New Houses
Once you have a trained multi-feature model, making predictions on new data is straightforward: create a DataFrame or array with the same feature columns in the same order, and call model.predict(). The model returns one predicted price per row.
If you used a Pipeline with a scaler, pass the raw (unscaled) data — the pipeline automatically applies the same scaling transformation that was fitted on training data. This is another reason why Pipelines are the professional way to work.
import pandas as pd
import numpy as np
# New houses to value
new_houses = pd.DataFrame({
'sqft': [1200, 2500, 800],
'bedrooms': [3, 4, 2],
'bathrooms': [2, 3, 1],
'age': [10, 5, 30],
'distance_to_center': [5.0, 12.0, 2.5]
})
features = ['sqft', 'bedrooms', 'bathrooms', 'age', 'distance_to_center']
predictions = model.predict(new_houses[features])
for i, (_, row) in enumerate(new_houses.iterrows()):
print(f'House {i+1}: {row["sqft"]} sqft, {row["bedrooms"]}bd -> ${predictions[i]:,.0f}')Polynomial Features for Non-Linear Relationships
Linear regression is limited to linear relationships, but you can model non-linear patterns by engineering polynomial features. PolynomialFeatures in scikit-learn automatically creates squared, cubed, and interaction terms from your original features.
A degree-2 polynomial on two features x₁ and x₂ produces: x₁, x₂, x₁², x₂², x₁x₂. The model is still linear in its parameters (which is why it is still 'linear regression'), but it can fit curved relationships in the original feature space. Use with cross-validation to pick the optimal degree.
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.metrics import r2_score
import numpy as np
np.random.seed(0)
X = np.random.uniform(0, 5, 100).reshape(-1, 1)
y = X.ravel()**2 + np.random.randn(100) * 2 # quadratic true relationship
# Compare linear vs degree-2 polynomial
for degree in [1, 2, 3]:
pipe = Pipeline([('poly', PolynomialFeatures(degree=degree)),
('model', LinearRegression())])
pipe.fit(X, y)
r2 = r2_score(y, pipe.predict(X))
print(f'Degree {degree} R2 (train): {r2:.3f}')Summary: Coefficients as Feature Importance
Key takeaways for using coefficients to measure feature importance:
- Raw coefficients depend on feature scale — a coefficient of 150 for sqft is not directly comparable to 8000 for bedrooms unless both are standardised.
- Standardised coefficients (from a model trained on scaled features) measure the effect of a one-standard-deviation change in each feature, making them directly comparable.
- Large absolute values indicate influential features; small values (near zero) indicate weak or redundant features.
- Always confirm that high-importance features have a causal or meaningful relationship with the target, not just statistical correlation in the training data.
Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: multiple linear regression assigns one weight per feature in the equation ŷ = w₁x₁ + ... + wₙxₙ + b, raw coefficients must be standardised before comparing importance across features with different scales, and Adjusted R² penalises added features to prevent overfitting during model selection. Next up we cross the boundary from predicting numbers to predicting categories with logistic regression and threshold-based classification.
Frequently asked questions
Is the “Multiple Linear Regression and Feature Importance” lesson free?
Yes — the full text of “Multiple Linear Regression and Feature Importance” is free to read here on the web, and the Machine Learning Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Machine Learning Academy course, upgrade to CoddyKit PRO.
What will I learn in “Multiple Linear Regression and Feature Importance”?
Learners will extend the model to multiple input features, interpret each coefficient as feature importance, and evaluate with R-squared. You practise Machine Learning Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Machine Learning Academy?
No prior experience is required. Machine Learning Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Multiple Linear Regression and Feature Importance” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Machine Learning Academy lesson?
Yes. Every Machine Learning Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- The Equation of a Line: Slope, Intercept, and Predictions
- Cost Functions and Least Squares
- Training Linear Regression with scikit-learn
- Multiple Linear Regression and Feature Importance