直线方程:斜率、截距与预测
您将回顾 y=mx+b 公式,在真实数据上绘制回归线,并理解模型如何将输入映射为输出
直线方程:斜率、截距与预测 是 CoddyKit 上的免费 Machine Learning Academy 课时。 这是第 1 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Machine Learning Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Machine Learning Academy 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Linear Relationships in Data
Many real-world relationships are approximately linear: as square footage increases, house price increases proportionally; as advertising spend rises, sales rise. Linear regression models these relationships by finding the straight line that best fits the data.
Before tackling the algorithm, you need to deeply understand the mathematical object it is trying to find: the equation of a line. Every linear regression model is ultimately a line (in 2D) or a hyperplane (in higher dimensions), and the two parameters that define it — slope and intercept — carry meaningful interpretations for the problem you are solving.
The Equation y = mx + b
The equation of a line in 2D is y = mx + b, where:
- y — the dependent variable (what we want to predict, e.g., house price)
- x — the independent variable or feature (e.g., square footage)
- m — the slope: how much y changes for each one-unit increase in x
- b — the intercept: the value of y when x is zero
In machine learning notation, this is often written as ŷ = w₁x + w₀ or ŷ = θ₁x + θ₀, where w or θ are the weights (parameters) the model learns.
import numpy as np
import matplotlib.pyplot as plt
# Define a line: y = 2x + 5
m = 2.0 # slope
b = 5.0 # intercept
x = np.linspace(0, 10, 100)
y = m * x + b # vectorised — computes all 100 points at once
plt.plot(x, y, color='blue', linewidth=2)
plt.xlabel('x (square footage / 100)')
plt.ylabel('y (price in $1000s)')
plt.title('Line: y = 2x + 5')
plt.grid(True, alpha=0.3)
plt.show()Interpreting the Slope
The slope m tells you the rate of change: for every one-unit increase in x, y changes by m units. The sign matters: a positive slope means x and y move together (positive correlation), a negative slope means they move in opposite directions.
In a house-price model where x is square footage and y is price in dollars, a slope of 150 means each additional square foot adds $150 to the predicted price. This interpretability is one of linear regression's biggest strengths — you can explain exactly what drives the prediction.
import numpy as np
# Example: house price model
# y = 150 * sqft + 50000
def predict_price(sqft, slope=150, intercept=50000):
return slope * sqft + intercept
print('Price for 1000 sqft:', predict_price(1000)) # $200,000
print('Price for 1500 sqft:', predict_price(1500)) # $275,000
print('Price for 2000 sqft:', predict_price(2000)) # $350,000
# Each 500 sqft increase adds:
delta = predict_price(1500) - predict_price(1000)
print(f'Adding 500 sqft increases price by: ${delta:,}')Interpreting the Intercept
The intercept b is the value of y when x equals zero. It anchors the line at a specific y-value on the vertical axis. Interpreting the intercept requires care — sometimes it makes physical sense, and sometimes it does not.
In the house-price example, an intercept of $50,000 would mean a house with zero square footage costs $50,000, which is physically meaningless. The intercept is best thought of as a calibration constant that shifts the entire line up or down to fit the data, rather than a quantity with direct real-world meaning in every context.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([500, 800, 1000, 1200, 1500, 2000])
y = np.array([125000, 170000, 200000, 230000, 275000, 350000])
# The intercept shifts the line vertically
for intercept in [0, 50000, 100000]:
y_line = 150 * np.linspace(0, 2000, 100) + intercept
plt.plot(np.linspace(0, 2000, 100), y_line,
label=f'b = {intercept:,}')
plt.scatter(x, y, color='black', zorder=5, label='Data')
plt.xlabel('Square Footage')
plt.ylabel('Price ($)')
plt.legend()
plt.show()Plotting Data and a Regression Line
Before fitting a model, always plot your data to confirm a linear relationship actually exists. If the scatter plot shows a curved or non-linear pattern, a linear model is the wrong choice. Visualising the fitted line on top of the scatter plot is the first validation step after training.
Seaborn's regplot() computes and plots the regression line with a confidence interval in one call, making it a quick sanity check during EDA.
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# Simulate house price data
np.random.seed(42)
sqft = np.random.uniform(500, 3000, 100)
price = 150 * sqft + 50000 + np.random.normal(0, 20000, 100)
# Quick regression plot with seaborn
plt.figure(figsize=(8, 5))
sns.regplot(x=sqft, y=price, scatter_kws={'alpha': 0.5},
line_kws={'color': 'red', 'linewidth': 2})
plt.xlabel('Square Footage')
plt.ylabel('Price ($)')
plt.title('House Price vs Square Footage')
plt.show()Making Predictions with a Line
Once you have a line (slope m and intercept b), making a prediction for a new input x is just arithmetic: plug x into the equation and compute y. This is called inference or prediction.
The key insight is that the model does not know the true output for a new input — it estimates it based on the patterns it learned from training data. The quality of these predictions depends entirely on how well the training data represents the new inputs and how linear the true relationship actually is.
import numpy as np
# Learned parameters (from training, simplified here)
slope = 150.0
intercept = 52000.0
def predict(x_new, m, b):
return m * x_new + b
# Single prediction
new_house_sqft = 1800
predicted_price = predict(new_house_sqft, slope, intercept)
print(f'Predicted price for {new_house_sqft} sqft: ${predicted_price:,.0f}')
# Batch prediction (multiple houses)
houses = np.array([1000, 1200, 1500, 2000, 2500])
prices = predict(houses, slope, intercept)
for sqft, price in zip(houses, prices):
print(f'{sqft} sqft -> ${price:,.0f}')Residuals: The Gap Between Prediction and Reality
No real dataset falls perfectly on a line. The residual for each data point is the difference between the actual value and the model's predicted value: residual = y_actual - y_predicted. A positive residual means the model under-predicted; a negative residual means it over-predicted.
Residuals are the raw material for evaluating and improving a linear model. If residuals show a systematic pattern (e.g., always positive for large x values), that is evidence the true relationship is non-linear and a more complex model is needed.
import numpy as np
y_actual = np.array([200000, 250000, 310000, 180000, 420000])
# Model predictions
m, b = 150.0, 52000.0
x = np.array([1000, 1300, 1700, 850, 2400])
y_pred = m * x + b
residuals = y_actual - y_pred
for i, (actual, pred, res) in enumerate(zip(y_actual, y_pred, residuals)):
print(f'House {i+1}: Actual=${actual:,} Predicted=${pred:,.0f} Residual=${res:,.0f}')
print(f'\nMean residual: ${residuals.mean():,.0f}')
print(f'Std of residuals: ${residuals.std():,.0f}')Negative Slope: Inverse Relationships
A negative slope models an inverse relationship: as x increases, y decreases. For example, the older a car, the lower its resale value. Or the more competitors a business has, the lower its market share.
Linear regression handles negative slopes naturally — the algorithm will find whatever slope (positive, negative, or zero) best fits the training data. A slope of exactly zero would mean x provides no information about y, and the best prediction for every input would just be the mean of y.
import numpy as np
import matplotlib.pyplot as plt
# Car age vs resale value (inverse relationship)
np.random.seed(0)
age = np.random.uniform(1, 15, 50)
value = -1500 * age + 25000 + np.random.normal(0, 2000, 50)
value = np.clip(value, 1000, 30000) # clip to realistic range
plt.scatter(age, value, alpha=0.6)
plt.plot([1, 15], [-1500*1+25000, -1500*15+25000],
color='red', linewidth=2, label='y = -1500x + 25000')
plt.xlabel('Car Age (years)')
plt.ylabel('Resale Value ($)')
plt.title('Inverse Relationship: Age vs Resale Value')
plt.legend()
plt.show()From Line to Hyperplane
In reality, we almost always have multiple input features, not just one. When you extend the line equation to multiple features, the model becomes a hyperplane in high-dimensional space:
ŷ = w₁x₁ + w₂x₂ + ... + wₙxₙ + b
Each wᵢ is a separate coefficient (weight) for the corresponding feature xᵢ. The prediction is still just a linear combination of inputs plus a bias. This extension — from a line to a hyperplane — is all that changes when you go from simple to multiple linear regression.
import numpy as np
# Multiple linear regression prediction
# y = w1*sqft + w2*bedrooms + w3*age + b
def predict_multi(features, weights, bias):
# features shape: (n_features,) or (n_samples, n_features)
return np.dot(features, weights) + bias
weights = np.array([150.0, 5000.0, -200.0]) # sqft, bedrooms, age
bias = 30000.0
# One house: 1500 sqft, 3 bedrooms, 10 years old
house = np.array([1500, 3, 10])
price = predict_multi(house, weights, bias)
print(f'Predicted price: ${price:,.0f}')
# = 150*1500 + 5000*3 + (-200)*10 + 30000 = $282,000Correlation vs Causation in Linear Models
Linear regression finds statistical correlations, not causal relationships. A high slope between ice cream sales and drowning deaths does not mean ice cream causes drowning — both are caused by hot weather. A model's slope tells you about the relationship in training data, not about the underlying causal mechanism.
This distinction matters enormously when deploying ML models for decision-making. A model that predicts loan defaults might find that zip code is a strong predictor — but using zip code as a decision factor may encode racial discrimination rather than genuine credit risk. Always interrogate why a feature has high predictive power.
Setting Up for scikit-learn
Now that you understand what a line is and what its parameters mean, you are ready to use scikit-learn to automatically learn the optimal slope and intercept from data. The algorithm will minimise the total prediction error across all training examples, finding the best-fit line without you manually tuning m and b.
In the next lesson you will learn exactly how this optimisation works — what 'best fit' means mathematically, and how the Mean Squared Error cost function turns fitting a line into a problem of minimising a mathematical expression.
from sklearn.linear_model import LinearRegression
import numpy as np
# scikit-learn finds the optimal slope and intercept automatically
np.random.seed(42)
sqft = np.random.uniform(500, 3000, 100).reshape(-1, 1)
price = 150 * sqft.ravel() + 50000 + np.random.normal(0, 20000, 100)
model = LinearRegression()
model.fit(sqft, price)
print(f'Learned slope (coef_): {model.coef_[0]:.1f}')
print(f'Learned intercept (b): {model.intercept_:.1f}')
print(f'Prediction for 1500 sqft: ${model.predict([[1500]])[0]:,.0f}')Quick Check
Test your understanding of Machine Learning with Python concepts from this lesson.
Lesson Recap
In this lesson you learned: the equation y=mx+b defines a line with slope m (rate of change) and intercept b (y-value at x=0), residuals measure the gap between actual and predicted values, and multiple linear regression extends the line to a hyperplane with one weight per feature. Next up we explore cost functions and least squares — the mathematical framework that defines what 'best fit' means and how the algorithm finds the optimal parameters.
常见问题解答
「直线方程:斜率、截距与预测」课时是免费的吗?
是的 — 「直线方程:斜率、截距与预测」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Machine Learning Academy 课程的其余内容,请升级到 CoddyKit PRO。 Machine Learning Academy 课程共包含 4 节课。
「直线方程:斜率、截距与预测」这节课中我会学到什么?
您将回顾 y=mx+b 公式,在真实数据上绘制回归线,并理解模型如何将输入映射为输出 你通过在浏览器中直接运行的动手代码来练习 Machine Learning Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Machine Learning Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Machine Learning Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 4 节。
「直线方程:斜率、截距与预测」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Machine Learning Academy 课中编写并运行代码吗?
能。每节 Machine Learning Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 直线方程:斜率、截距与预测
- 代价函数与最小二乘法
- 使用 scikit-learn 训练线性回归
- 多元线性回归与特征重要性