Predict Salaries with Linear Regression in Python
Code with me
0:00 / 0:00
Predict Salaries with Linear Regression in Python
7 просмотров · 3 дня назад
Code with me
25 подписчиков
7 просмотров · 3 дня назад
Predict a salary from years of experience with your first real machine learning model — linear regression in Python with scikit-learn, trained and honestly tested.
The model learns a line: start at $34,031.77, add $5,880.45 for every extra year. On five people it never saw, it predicts 6 years at $69,314, misses by $3,788.91 on average (MAE), and scores R-squared 0.977. You will learn the best-fit line, slope and intercept in plain words, features (X) versus label (y), the honest train/test split, model.fit and model.predict, and the shape mistake that breaks every beginner's first prediction.
Why learn this? Machine learning theory appears in 72.5% of 10,704 machine learning job postings (Huntr 2026 analysis), Python in 81.4%, and scikit-learn in 15.8% — and linear regression is the first model interviewers ask about.
FULL CODE — salary_prediction.py (copy, run, put it on GitHub):
"""Predict Salaries with Linear Regression - Portfolio project #15."""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
20 people: years of experience and their salary in dollars.
people = pd.DataFrame({
"years_experience": [0, 1, 1, 2, 2, 3, 3, 4, 5, 5,
6, 7, 7, 8, 9, 10, 11, 12, 13, 15],
"salary": [34000, 39000, 36000, 48000, 44000, 53000, 50000,
61000, 58000, 69000, 66000, 79000, 73000, 86000,
82000, 98000, 94000, 112000, 106000, 128000],
})
FEATURES (X) = the question. LABEL (y) = the answer.
X = people[["years_experience"]]
y = people["salary"]
print(f"Examples: {len(people)} people")
print(f"Feature (X): years_experience")
print(f"Label (y): salary")
Honest split first (Episode 12): train on 15, test on 5 unseen.
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42)
print(f"Train: {len(X_train)} people, Test: {len(X_test)} people")
Train: fit finds the best-fit line through the training points.
model = LinearRegression()
model.fit(X_train, y_train)
print(f"Slope: ${model.coef_[0]:,.2f} per extra year")
print(f"Intercept: ${model.intercept_:,.2f} at zero years")
Predict on the 5 people the model never saw.
predictions = model.predict(X_test)
print("\nTest predictions vs reality:")
for years, real, guess in zip(X_test["years_experience"], y_test, predictions):
print(f" {years} years: predicted ${guess:,.0f}, real ${real:,}")
Honest scores: average miss in dollars, and R-squared.
mae = mean_absolute_error(y_test, predictions)
r2 = r2_score(y_test, predictions)
print(f"\nMean absolute error: ${mae:,.2f}")
print(f"R-squared: {r2:.3f}")
Predict a brand-new person: 6 years of experience.
Note: predict needs a table shape, not a bare number.
new_person = pd.DataFrame({"years_experience": [6]})
print(f"\nPrediction for 6 years: ${model.predict(new_person)[0]:,.0f}")
print("Done - your first real model, trained and honestly tested.")
CHAPTERS:
0:00 Hook: predict a salary in one line
1:08 Why employers care: ML theory in 72.5% of postings
2:26 Regression: the best-fit line, slope and intercept
3:52 Features, label and the honest split: 20 salaries
5:25 Train, fit and predict with scikit-learn
7:15 Honest scores: MAE and R-squared
8:53 The shape mistake, and the extrapolation warning
10:35 Pause & build: portfolio project #15
12:21 Recap + tomorrow: classification
Series: Python from Scratch for AI Engineers (30 days)
Watch the full series: • AI/ML with Python — Beginner Series
Subscribe for daily Python-for-ML tutorials: new episode every day.
Question for you: what number would YOU predict — a house price, a salary, an exam score? Tell me your feature and your label in the comments. I read every comment.
Job stat cited: Huntr analysis of 10,704 ML/AI job postings (2026)
#python #linearregression #machinelearning #scikitlearn #pythonforbeginners