Python + AI/ML · Tutorial 8 of 12
Regression Models, explained for beginners
By the FUTEAC Team · 23 November 2026 · 14 min read · Beginner
In short
Regression predicts a number from other numbers. You show a model examples with known answers, and it finds the pattern connecting inputs to answers. This tutorial fits one on twelve students: study hours and practice tests predict an exam score. You will read the line it finds, test it on students it has never seen, and learn where it breaks.
- Regression predicts a number, classification predicts a category. Exam score, house price, temperature: regression. Pass or fail, spam or not spam, cat or dog: classification.
- A linear regression model is a line (or a flat surface) through your data. With one input it is
score = intercept + slope x hours. With two inputs it is a flat plane, one slope per input. - Each coefficient answers a plain question. Ours says each extra study hour adds about 6.3 marks, and each extra practice test changes the prediction by about 0.2 marks, when the other input is held fixed. Hours already carries almost all the information, so tests add nearly nothing once hours is in the model.
- A model must be tested on data it never trained on. Ours scores R-squared 0.964 on three unseen students, and its average error is 2.68 marks. A score measured on the training rows is not a test.
- Regression breaks outside the data it learned from. Ask it about 20 study hours and it predicts 155.2 marks, a score that cannot exist. The line keeps going; reality stops at 100.
- This tutorial feeds the AI & Machine Learning: First Steps course (/course/ai-ml-first-steps) and the Regression Models (/skill/regression) skill.
Before you start
What is regression, in one sentence?
Regression answers a question whose answer is a number. How much will this house sell for? What score will this student get? How many visitors will the site get tomorrow? The answer is a number, not a label, and that single fact decides the whole approach.
Think of a shopkeeper who prices second-hand phones. She has sold fifty phones, and she knows each phone's age and what it sold for. A new phone arrives, two years old, and she needs a price. She does not sort it into a category. She looks at the pattern in her fifty sales and reads off a number. Regression is that habit, written as code.
The simplest version is a straight line through a scatter of points. Plot study hours on one axis and exam score on the other, and the points climb upward: more hours, higher score. A line drawn through the middle of that climb is the model. Feed it a new student's hours, read the line at that point, and you have a prediction. The model is the line. Training is finding where the line should sit.
That is also the difference from classification, which you met in item 33. Classification sorts a record into a category: this flower is a setosa, this email is spam. Regression predicts a quantity: this student scores 70, this house sells for 155. If your answer is a number, reach for regression. If it is a label, reach for classification. The next tutorial in this series, Classification Models, explained for beginners (/tutorials/python/classification-models-explained) (item 68), takes the same twelve students and sorts them into pass and fail, so you can see the two side by side.
The data: twelve students, two inputs, one score
The data for this tutorial is twelve students, each with two inputs and one answer. Hours studied, practice tests taken, and the exam score out of 100. It is small on purpose: you can hold all twelve rows in your head, check every claim by hand, and see exactly what the model does with them.
import numpy as np
import pandas as pd
hours = np.array([1, 2, 3, 4, 5, 6, 7, 8, 2, 5, 9, 10], dtype=float)
tests = np.array([0, 1, 1, 2, 2, 3, 3, 4, 0, 1, 4, 5], dtype=float)
score = np.array([38, 45, 52, 58, 63, 71, 76, 82, 41, 66, 88, 93], dtype=float)
df = pd.DataFrame({"hours": hours, "practice_tests": tests, "score": score})
print(df.head())Expected behaviour: the first five rows print exactly as below. The averages over all twelve are 5.2 hours, 2.2 practice tests and a score of 64.4, with scores running from 38 to 93.
hours practice_tests score
0 1.0 0.0 38.0
1 2.0 1.0 45.0
2 3.0 1.0 52.0
3 4.0 2.0 58.0
4 5.0 2.0 63.0Two things to notice before any model runs. First, the pattern is visible without code: as hours rise, scores rise. Second, the data is clean: no missing values, no duplicates, no wild typos. Regression has no defence against dirty data, it just fits the line to whatever you give it, so the cleaning step from item 27 is not optional in real work.
Step 1: one input, one line
Start with one input, study hours, and let the model find the line. This is the whole idea in its simplest form, and you can read every number it produces.
from sklearn.linear_model import LinearRegression
model_one = LinearRegression().fit(hours.reshape(-1, 1), score)
print("Slope:", round(float(model_one.coef_[0]), 2))
print("Intercept:", round(float(model_one.intercept_), 2))Expected behaviour: the code prints Slope: 6.25 and Intercept: 32.14. In plain words, the line is:
score = 32.14 + 6.25 x hoursRead it like a sentence. A student who studies zero hours is predicted to score 32.14, which is the intercept, the line's starting point. Each extra hour adds 6.25 marks, which is the slope. A student who studies 6 hours is predicted to score 32.14 + 6.25 x 6 = 69.6. The R-squared for this one-input line, fitted on all twelve students, is 0.993, which means the line explains 99.3 percent of the variation in scores. That is very high, and it is also a warning sign you will meet again in step 3: this number was measured on the same students the line was fitted to, so it flatters the model.
The reshape(-1, 1) is not decoration. scikit-learn expects a table of rows and columns, even when there is only one column, so a flat list of twelve numbers must be reshaped into twelve rows of one number each. Forgetting this is the single most common beginner error in scikit-learn, and you will hit it yourself in the wrong-turn section below.
Step 2: two inputs, one flat plane
One input is a line. Two inputs make a flat plane, one slope per input, and the reading stays just as plain. Add practice tests as a second input and fit the same kind of model.
X = df[["hours", "practice_tests"]].values
model = LinearRegression()
model.fit(X, score)
print("Coefficients:", np.round(model.coef_, 2))
print("Intercept:", round(float(model.intercept_), 2))Expected behaviour: the code prints Coefficients: [6.33 -0.16] and Intercept: 32.04. The model is now:
score = 32.04 + 6.33 x hours - 0.16 x practice_testsEach coefficient answers the same plain question, with one condition attached: what happens when this input rises by one and the other input stays put? Each extra study hour adds about 6.3 marks, holding practice tests fixed. Each extra practice test changes the prediction by about 0.2 marks, holding hours fixed, which is to say it adds almost nothing. That is not because practice tests do not matter. It is because the two inputs move together: students who study more also take more practice tests, and the correlation between them is 0.96, so hours already carries nearly all the information tests carry. Once the model knows the hours, the tests have little left to add.
Notice the hours coefficient barely moved, from 6.25 to 6.33, when practice tests joined the model. The new input did not split the work the way a beginner expects; it mostly repeated what hours already said. That is the honest result, and it is why you add inputs one at a time and watch the coefficients move: when two inputs overlap, the split between them is unstable, and a coefficient near zero is the model telling you the input adds nothing new. The intercept, 32.04, is the predicted score for a student with zero hours and zero practice tests.
A student with 6 hours and 3 practice tests is predicted to score 69.6. That is the number the code prints for model.predict([[6, 3]]); working it out from the rounded coefficients above gives 32.04 + 6.33 x 6 - 0.16 x 3 = 69.5, and the 0.1 gap is the rounding of the coefficients, not a mistake.
Step 3: split, train, test honestly
Fitting on all twelve students and then admiring the result is cheating, because the model has already seen the answers. The honest test is the one from item 33: split the data, train on nine students, test on the three the model has never seen.
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score, mean_absolute_error
X_train, X_test, y_train, y_test = train_test_split(
X, score, test_size=0.25, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
predictions = model.predict(X_test)
print("Predictions:", np.round(predictions, 1))
print("Actual: ", y_test)
print("R-squared on test data:", round(r2_score(y_test, predictions), 3))
print("Mean absolute error:", round(mean_absolute_error(y_test, predictions), 2))Expected behaviour: the three test students are (9 hours, 4 tests, score 88), (5 hours, 1 test, score 66) and (1 hour, 0 tests, score 38). The model predicts 86.8, 59.4 and 38.2. The code prints R-squared on test data: 0.964 and Mean absolute error: 2.68.
Read those two numbers separately, because they answer different questions. R-squared, 0.964, says the model explains 96.4 percent of the variation in the unseen scores. It runs from 0 to 1, and closer to 1 is better. Mean absolute error, 2.68, says the predictions are off by 2.68 marks on average. It is in marks, the same units as the answer, so it is the number you can picture: "usually within about 3 marks."
The same model scores R-squared 0.995 on the nine students it trained on. That gap, 0.995 on familiar data against 0.964 on new data, is normal and small here, but the direction is the lesson: a model always looks better on data it has seen. If you ever see a tutorial report a score measured on the training data as if it were a test result, that number is flattery, not evidence. Three test students is a tiny test set, so treat 0.964 as a demonstration, not a guarantee: with twelve rows, one unusual student moves the score a lot. Real datasets have hundreds or thousands of rows, and the same split-and-test discipline applies at that scale.
The wrong turn: a list where a table was expected
Here is the error every beginner meets, usually in the first hour. You have a trained model and a new student, 6 hours and 3 practice tests, and you write the natural thing. The model here is the one from step 3, trained on nine students, so this student scores 70.1 here rather than the 69.6 from the all-twelve model in step 2. Two different models give two different answers, which is why you always say which model you mean:
model.predict([6, 3])Expected behaviour: the code fails, and the error is worth reading in full:
ValueError: Expected 2D array, got 1D array instead:
array=[6 3].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.What it means: scikit-learn thinks in tables. [6, 3] is one flat list, and the model cannot tell whether you mean one student with two inputs or two students with one input each. The fix is to wrap the student in another pair of brackets, so it is a table with one row:
model.predict([[6, 3]])
# array([70.1])The double bracket is the fix for every predict call with a single sample, in regression and in classification alike. You will meet this error again in item 68, and the second time it will take you ten seconds instead of ten minutes. We use the double-bracket form everywhere in this tutorial because it is the form scikit-learn actually wants, not because it looks tidy.
as a flat row labelled "1D: the model cannot tell rows from columns" with a cross, and one showing [[6, 3]]` as a one-row table labelled "2D: one student, two inputs" with a tick.]
Where regression breaks: extrapolation, and correlation is not causation
Two limits matter more than any formula, and both are easy to miss when the test score looks good.
First, extrapolation. The line does not know where the data ends. Ask it about a student who studies 20 hours and takes 10 practice tests, far beyond anything in the twelve rows, and it answers without hesitating:
model.predict([[20, 10]])
# array([155.2])A score of 155.2 out of 100 cannot exist. The model is not broken, it is doing exactly what a straight line does: it keeps climbing past the edge of the data. The prediction is only trustworthy inside the range the model learned from, roughly 1 to 10 hours and 0 to 5 tests here. Outside that range, the line is a guess dressed as arithmetic. The same trap appears in real work whenever someone predicts next year's sales from three years of data, or a house price in a neighbourhood with no comparable sales.
Second, correlation is not causation. The data says students who study more score higher, but it does not say studying causes the score. A motivated student studies more and also sleeps better, eats better and asks more questions in class. The model cannot separate those, and it does not try to. It finds a pattern and uses it. Use regression to predict, and use a designed experiment, not a fitted line, to prove a cause.
Regression also has a boundary you should respect. It predicts numbers. The moment your answer becomes a category, pass or fail, spam or not spam, you have left regression behind, and forcing a line onto categories gives nonsense: a model that predicts "0.7 of a pass" for a student. That is the next tutorial's job, and it starts from this same dataset.
Try it yourself
1. Change the data: add a thirteenth student, 7 hours, 2 practice tests, score 74, refit the two-input model on all thirteen rows, and write down the new coefficients. Do they move much? One row in twelve should not move them far, and if it does, your data is thinner than you thought. 2. Fit a model using practice tests alone as the single input. Compare its R-squared with the hours-only line from step 1 (0.993). Which single input explains scores better, and does the answer surprise you? 3. Predict the score for a student with 4 hours and 0 practice tests, then for a student with 4 hours and 5 practice tests. The difference between the two answers is the model's price for five practice tests, in marks. If it comes out near zero or negative, that is the same lesson as step 2: tests add almost nothing once hours is known. 4. Break it on purpose: predict for 30 hours and 15 tests, and write down the score. Then explain in one sentence why no one should trust that number.
Continue in the free course: AI & Machine Learning: First Steps →
Common mistakes
- Measuring the model on the data it trained on. R-squared 0.995 on the nine training students flatters the model. Report the test number, 0.964 on unseen students, and say how many test rows it came from.
- Passing a flat list to
predict.model.predict([6, 3])raisesValueError: Expected 2D array, got 1D array instead. Wrap one sample in double brackets:model.predict([[6, 3]]). - Trusting predictions outside the data's range. Twenty hours predicts 155.2 marks, which cannot exist. Regression is only trustworthy inside the range it learned from.
- Reading a coefficient as a cause. Each extra hour is associated with about 4.5 more marks, holding practice tests fixed. The data cannot prove the hour caused the marks.
- Adding inputs without watching the coefficients move. Hours barely moved, 6.25 to 6.33, and the practice-tests coefficient came out at -0.16, near zero. The two inputs move together, so the model cannot tell them apart, and the split between them is not stable.
- Forgetting the intercept has a meaning. The intercept, 32.04, is the predicted score at zero hours and zero tests. If that number is absurd for your problem, say so: it tells you the line is being asked to describe a situation no row in the data covers.
Frequently asked questions
When do I use regression instead of classification?
Look at the answer you want. A number, such as a score, a price or a temperature, means regression. A category, such as pass or fail, spam or not spam, means classification. If you catch yourself predicting 0.7 of a category, you picked the wrong tool.
What does R-squared actually mean?
It is the share of the variation in the answers that the model explains, from 0 to 1. Ours is 0.964 on unseen students, so the model explains 96.4 percent of why scores differ. The rest is everything the model cannot see: sleep, luck, a hard paper. R-squared says nothing about whether the model is right for your problem, only how much of the variation it captures.
Is a higher R-squared always better?
No. A model can reach R-squared 1.0 by memorising the training data, and then fail on new students. That is overfitting, and it is why the test split matters more than the number itself. Item 69, Model Evaluation, goes into overfitting properly.
Can I use regression with categories as inputs?
Yes, once they are turned into numbers. A category such as "morning" or "evening" study session becomes a 0 or 1 column, the same treatment item 33 used for turning categories into numbers. The coefficient then reads as the difference that category makes. The mechanics are the same; only the preparation changes.
How much data do I need?
More than twelve rows. Twelve is a teaching size: enough to see the pattern, too small to trust the exact coefficients. A common working rule is at least ten rows per input, so two inputs want twenty rows as a floor, and hundreds before you quote a coefficient to anyone else.
Follow the Python + AI/ML Beginner Roadmap
Learn Python from zero and take your first steps into AI and machine learning. Free, step by step, at your pace.
View the Roadmap