Machine Learning Academy · Leçon

Équation d’une droite : pente, ordonnée à l’origine et prédictions

Rappelez la formule y=mx+b, tracez une droite de régression sur des données réelles et comprenez comment le modèle associe les entrées aux sorties.

Leçon 1 sur 413 étapes

Équation d’une droite : pente, ordonnée à l’origine et prédictions est une leçon Machine Learning Academy gratuite sur CoddyKit. Ceci est la leçon 1 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Machine Learning Academy, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Machine Learning Academy comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

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,000

Correlation 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.

Gratuit pour commencer

Apprends Python avec un tuteur IA — gratuit

Écris et exécute du vrai code dans ton navigateur, obtiens de l'aide instantanée d'un tuteur IA disponible 24h/24, et reprends là où tu t'es arrêté sur le web ou dans l'app.

Cours
30
Leçons
120

Questions Fréquemment Posées

La leçon « Équation d’une droite : pente, ordonnée à l’origine et prédictions » est-elle gratuite ?

Oui — le texte complet de « Équation d’une droite : pente, ordonnée à l’origine et prédictions » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Machine Learning Academy, passe à CoddyKit PRO. Le cours Machine Learning Academy comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Équation d’une droite : pente, ordonnée à l’origine et prédictions » ?

Rappelez la formule y=mx+b, tracez une droite de régression sur des données réelles et comprenez comment le modèle associe les entrées aux sorties. Tu pratiques Machine Learning Academy avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Machine Learning Academy ?

Aucune expérience préalable n'est requise. Machine Learning Academy sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 1 sur 4.

Combien de temps prend la leçon « Équation d’une droite : pente, ordonnée à l’origine et prédictions » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Machine Learning Academy ?

Oui. Chaque leçon Machine Learning Academy inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Équation d’une droite : pente, ordonnée à l’origine et prédictions
  2. Fonctions de coût et moindres carrés
  3. Entraîner une régression linéaire avec scikit-learn
  4. Régression linéaire multiple et importance des caractéristiques
← Retour à Machine Learning Academy