0Pricing
Machine Learning Academy · 课时

多元线性回归与特征重要性

您将把模型扩展到多个输入特征,将每个系数解读为特征重要性,并使用 R 平方进行评估

多元线性回归与特征重要性 是 CoddyKit 上的免费 Machine Learning Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Machine Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Machine Learning Academy 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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 complexity

Multicollinearity: 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.

常见问题解答

「多元线性回归与特征重要性」课时是免费的吗?

是的 — 「多元线性回归与特征重要性」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Machine Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Machine Learning Academy 课程共包含 4 节课。

「多元线性回归与特征重要性」这节课中我会学到什么?

您将把模型扩展到多个输入特征,将每个系数解读为特征重要性,并使用 R 平方进行评估 你通过在浏览器中直接运行的动手代码来练习 Machine Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Machine Learning Academy 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Machine Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「多元线性回归与特征重要性」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Machine Learning Academy 课中编写并运行代码吗?

能。每节 Machine Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 直线方程:斜率、截距与预测
  2. 代价函数与最小二乘法
  3. 使用 scikit-learn 训练线性回归
  4. 多元线性回归与特征重要性
← 返回 Machine Learning Academy