Machine Learning with scikit-learn

Linear Regression in Python with scikit-learn

Fit the best straight line through your data, read its slope and intercept, and predict new values.

  • Intermédiaire
  • 3 min de lecture
  • 1 exemple exécutable
Ce que vous allez apprendre
  • LinearRegression fit and predict
  • coef_ and intercept_
  • Measuring the fit with R^2 and MAE
Hours studied to score
  1. 1hours = 9New input
  2. 24.48 x 9 + 46.86Slope times input plus intercept
  3. 387.1Predicted score

The best straight line

Découvrez Linear Regression in Python with scikit-learn avec un exemple pratique modifiable et exécutable en ligne.

Points clés

  1. hours must be 2D (one row per sample, one column per feature); scores is 1D.
  2. The fitted line is score = 4.48 x hours + 46.86.
  3. r2_score of 0.992 means the line explains almost all of the variation.
  4. mean_absolute_error says predictions are 0.82 points off on average.

Quand l’utiliser ?

  • Train and evaluate classic machine learning models on tabular data.
  • Prepare features: split, scale and encode data the way real projects do.
  • Compare models fairly with cross-validation and the right metric.

Code d’exemple

main.py
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score

# Hours studied and exam score for 8 students
hours = np.array([[1], [2], [3], [4], [5], [6], [7], [8]])
scores = np.array([52, 55, 61, 64, 70, 72, 79, 83])

model = LinearRegression()
model.fit(hours, scores)

print(f"Slope (coef_):  {model.coef_[0]:.2f} points per hour")
print(f"Intercept:      {model.intercept_:.2f}")

predicted = model.predict(hours)
print(f"R^2:            {r2_score(scores, predicted):.3f}")
print(f"MAE:            {mean_absolute_error(scores, predicted):.2f} points")

new_students = np.array([[2.5], [9]])
for h, p in zip(new_students.ravel(), model.predict(new_students)):
    print(f"{h} hours -> predicted score {p:.1f}")
Obtenir un bouton Run pour cet exemple

Résultat de l’exécution

Slope (coef_):  4.48 points per hour
Intercept:      46.86
R^2:            0.992
MAE:            0.82 points
2.5 hours -> predicted score 58.0
9.0 hours -> predicted score 87.1

Explication du code

Cet exemple montre Linear Regression in Python with scikit-learn en pratique. Modifiez les valeurs d’entrée et relancez le code pour voir ce qui change.

Modifiez les valeurs et exécutez le programme avec le compilateur Python en ligne CodeUtility, sans installation locale.

Exercices d’approfondissement

Essayez de modifier le code en suivant les pistes ci-dessous. Changer le code et observer le résultat vous fera bien mieux comprendre la leçon que la simple lecture.

  1. Change random_state and see how much the score moves.
  2. Swap in another built-in dataset (wine, breast_cancer, digits) and rerun.
  3. Try a different model or hyperparameter and compare the scores.
Exécuter dans le compilateur Python →

Leçon terminée ?

Marquez-la comme apprise pour suivre votre progression.

S'entraîner avec un défi

Utilisez le contenu de cette leçon pour résoudre un vrai problème. Chaque défi s'exécute dans le navigateur, avec des tests instantanés et une revue par l'IA.

Tous les défis

Outils pour cette leçon