What is Supervised Learning?
Supervised Learning is a type of Machine Learning where a model learns from historical data containing both input features and known target values. After learning the relationship between inputs and targets, the model can make predictions for new data.
Input Features
Variables supplied to the model, such as area, experience, income, study hours, or number of visits.
Target
The known output that the model learns to predict, such as price, salary, grade, or customer churn.
Labeled Data
Training examples where both input variables and expected outcomes are available.
Prediction
The output produced by a trained model for previously unseen input data.
A supervised learning system learns a relationship between input variables and a known target variable.
Historical Data
↓
Features + Known Target
↓
Training Algorithm
↓
Learned Model
↓
New Data
↓
Prediction
The two major supervised-learning problem types are regression and classification.
| Type | Target | Example |
|---|---|---|
| Regression | Numerical value | Predict house price |
| Regression | Numerical value | Predict monthly sales |
| Classification | Category | Spam or not spam |
| Classification | Category | Customer churn or no churn |
Scikit-learn provides many supervised-learning algorithms and evaluation utilities.
pip install pandas numpy scikit-learn matplotlib seaborn
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
Consider a simple business dataset containing advertising spending and corresponding sales.
data = {
"Advertising": [
10, 15, 20, 25, 30,
35, 40, 45, 50, 55
],
"WebsiteVisits": [
100, 130, 160, 190, 220,
250, 290, 320, 350, 390
],
"Sales": [
20, 27, 33, 39, 45,
52, 60, 66, 73, 81
]
}
df = pd.DataFrame(data)
print(df)
Separate the input variables from the target variable.
X = df[
["Advertising", "WebsiteVisits"]
]
y = df["Sales"]
print("Features:")
print(X)
print("\nTarget:")
print(y)
y: Target value.
A common approach is to divide the data into training and testing portions.
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
print("Training data:")
print(X_train)
print("\nTesting data:")
print(X_test)
Linear Regression is a supervised-learning algorithm used to predict a continuous numerical target.
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(
X_train,
y_train
)
predictions = model.predict(
X_test
)
print(predictions)
Mean Absolute Error
mae = mean_absolute_error(
y_test,
predictions
)
print("MAE:", mae)
Mean Squared Error
mse = mean_squared_error(
y_test,
predictions
)
print("MSE:", mse)
R² Score
r2 = r2_score(
y_test,
predictions
)
print("R²:", r2)
comparison = pd.DataFrame({
"Actual": y_test.values,
"Predicted": predictions
})
print(comparison)
After training, the model can be used to estimate sales for a future business scenario.
new_data = pd.DataFrame({
"Advertising": [60],
"WebsiteVisits": [420]
})
predicted_sales = model.predict(
new_data
)
print(
"Predicted Sales:",
predicted_sales[0]
)
A real-estate company has historical property information and wants to estimate the price of a new property.
houses = pd.DataFrame({
"Area": [
800, 1000, 1200, 1500, 1800,
2000, 2200, 2500, 2800, 3000
],
"Bedrooms": [
2, 2, 3, 3, 3,
4, 4, 4, 5, 5
],
"Age": [
15, 10, 8, 12, 7,
5, 4, 6, 3, 2
],
"Price": [
45, 55, 68, 82, 95,
110, 125, 140, 158, 175
]
})
X = houses[
["Area", "Bedrooms", "Age"]
]
y = houses["Price"]
house_model = LinearRegression()
house_model.fit(X, y)
new_house = pd.DataFrame({
"Area": [1700],
"Bedrooms": [3],
"Age": [5]
})
predicted_price = house_model.predict(
new_house
)
print(
"Predicted Price:",
predicted_price[0],
"lakhs"
)
Target: House Price.
A company can use historical employee records to estimate salary from experience and other relevant variables.
employees = pd.DataFrame({
"Experience": [
1, 2, 3, 5, 7,
9, 11, 13
],
"Projects": [
1, 2, 3, 5, 7,
8, 10, 12
],
"Salary": [
30000, 35000, 42000, 55000,
68000, 80000, 95000, 110000
]
})
X = employees[
["Experience", "Projects"]
]
y = employees["Salary"]
salary_model = LinearRegression()
salary_model.fit(X, y)
new_employee = pd.DataFrame({
"Experience": [6],
"Projects": [6]
})
predicted_salary = salary_model.predict(
new_employee
)
print(
"Predicted Salary:",
predicted_salary[0]
)
Classification predicts a category instead of a continuous numerical value.
Customer Information
↓
Features
↓
Classification Model
↓
Predicted Category
Example:
Age + Visits + Spending
↓
Purchase Model
↓
Purchase / No Purchase
Logistic Regression is a common supervised-learning algorithm for classification tasks.
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(
X_train,
y_train
)
predictions = classifier.predict(
X_test
)
print(predictions)
An online store wants to predict whether a customer will purchase a product based on age, website visits, and previous spending.
customers = pd.DataFrame({
"Age": [
20, 22, 25, 28,
32, 35, 40, 45,
50, 55
],
"Visits": [
1, 2, 3, 5,
6, 7, 8, 10,
12, 14
],
"Spending": [
100, 150, 200, 350,
450, 500, 650, 800,
1000, 1200
],
"Purchased": [
0, 0, 0, 1,
1, 1, 1, 1,
1, 1
]
})
X = customers[
["Age", "Visits", "Spending"]
]
y = customers["Purchased"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.2,
random_state=42
)
classifier = LogisticRegression()
classifier.fit(
X_train,
y_train
)
new_customer = pd.DataFrame({
"Age": [30],
"Visits": [6],
"Spending": [400]
})
prediction = classifier.predict(
new_customer
)
print(
"Predicted Purchase:",
prediction[0]
)
0 can represent no purchase and
1 can represent purchase, based on how
the target was defined.
from sklearn.metrics import accuracy_score
accuracy = accuracy_score(
y_test,
predictions
)
print(
"Accuracy:",
accuracy
)
A confusion matrix summarizes classification results by comparing actual classes with predicted classes.
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(
y_test,
predictions
)
print(cm)
| Term | Meaning |
|---|---|
| True Positive | Positive case correctly predicted as positive |
| True Negative | Negative case correctly predicted as negative |
| False Positive | Negative case incorrectly predicted as positive |
| False Negative | Positive case incorrectly predicted as negative |
from sklearn.metrics import (
precision_score,
recall_score,
f1_score
)
precision = precision_score(
y_test,
predictions,
zero_division=0
)
recall = recall_score(
y_test,
predictions,
zero_division=0
)
f1 = f1_score(
y_test,
predictions,
zero_division=0
)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
A school can use historical study behavior to classify whether a student is likely to pass or fail.
students = pd.DataFrame({
"StudyHours": [
1, 2, 2, 3, 4,
5, 6, 7, 8, 9
],
"Attendance": [
55, 60, 65, 68, 72,
78, 82, 88, 92, 95
],
"Passed": [
0, 0, 0, 0, 1,
1, 1, 1, 1, 1
]
})
X = students[
["StudyHours", "Attendance"]
]
y = students["Passed"]
student_model = LogisticRegression()
student_model.fit(X, y)
new_student = pd.DataFrame({
"StudyHours": [5],
"Attendance": [80]
})
prediction = student_model.predict(
new_student
)
print(
"Predicted Result:",
prediction[0]
)
A Decision Tree learns a sequence of rules that can be used to make predictions.
from sklearn.tree import DecisionTreeClassifier
tree_model = DecisionTreeClassifier(
random_state=42,
max_depth=3
)
tree_model.fit(
X_train,
y_train
)
predictions = tree_model.predict(
X_test
)
print(predictions)
Random Forest combines predictions from multiple decision trees to build an ensemble model.
from sklearn.ensemble import RandomForestClassifier
forest_model = RandomForestClassifier(
n_estimators=100,
random_state=42
)
forest_model.fit(
X_train,
y_train
)
predictions = forest_model.predict(
X_test
)
print(predictions)
K-Nearest Neighbors makes predictions using nearby examples in the feature space.
from sklearn.neighbors import KNeighborsClassifier
knn_model = KNeighborsClassifier(
n_neighbors=3
)
knn_model.fit(
X_train,
y_train
)
predictions = knn_model.predict(
X_test
)
print(predictions)
Features can have very different numerical ranges. Standardization can make them comparable for algorithms that are sensitive to scale.
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(
X_train
)
X_test_scaled = scaler.transform(
X_test
)
A Pipeline keeps preprocessing and model training together and helps reduce accidental differences between training and prediction workflows.
from sklearn.pipeline import Pipeline
pipeline = Pipeline([
("scaler", StandardScaler()),
("model", LogisticRegression())
])
pipeline.fit(
X_train,
y_train
)
predictions = pipeline.predict(
X_test
)
print(predictions)
A financial application could classify historical loan applications using selected features and an approval target.
loans = pd.DataFrame({
"Income": [
25000, 30000, 35000, 40000,
45000, 50000, 60000, 70000
],
"CreditScore": [
550, 580, 610, 630,
660, 700, 730, 760
],
"LoanAmount": [
200000, 180000, 160000, 170000,
150000, 140000, 160000, 180000
],
"Approved": [
0, 0, 0, 1,
1, 1, 1, 1
]
})
X = loans[
["Income", "CreditScore", "LoanAmount"]
]
y = loans["Approved"]
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.25,
random_state=42
)
loan_model = LogisticRegression(
max_iter=1000
)
loan_model.fit(
X_train,
y_train
)
new_application = pd.DataFrame({
"Income": [48000],
"CreditScore": [690],
"LoanAmount": [150000]
})
prediction = loan_model.predict(
new_application
)
print(
"Predicted Approval:",
prediction[0]
)
Cross-validation evaluates a model across multiple training and validation splits instead of relying on one split.
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import LinearRegression
model = LinearRegression()
scores = cross_val_score(
model,
X,
y,
cv=5,
scoring="r2"
)
print("Scores:", scores)
print("Average Score:", scores.mean())
Hyperparameters are settings selected before or during model development rather than learned directly as model parameters.
| Algorithm | Example Hyperparameter |
|---|---|
| Decision Tree | max_depth |
| Random Forest | n_estimators |
| KNN | n_neighbors |
| Logistic Regression | C |
Grid Search can evaluate combinations of selected hyperparameter values using cross-validation.
from sklearn.model_selection import GridSearchCV
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier(
random_state=42
)
parameters = {
"n_estimators": [50, 100],
"max_depth": [2, 4, 6]
}
grid = GridSearchCV(
model,
parameters,
cv=5,
scoring="accuracy"
)
grid.fit(
X_train,
y_train
)
print(
"Best Parameters:",
grid.best_params_
)
Overfitting occurs when a model captures training-specific patterns too closely and does not generalize well to new data.
Training Performance
↓
Very High
Unseen Data Performance
↓
Much Lower
Possible Problem
↓
Overfitting
Possible approaches include simplifying the model, regularization, cross-validation, more representative data, and careful feature selection.
Underfitting occurs when a model is too simple to capture important patterns in the data.
High Bias
The model may be too simple and can lead to underfitting.
High Variance
The model may be too sensitive to training data and can lead to overfitting.
Generalization
The objective is to perform well on relevant unseen examples.
A subscription company wants to classify whether a customer is likely to churn using usage and support information.
customers = pd.DataFrame({
"MonthlyUsage": [
5, 8, 10, 12,
18, 22, 28, 32
],
"SupportTickets": [
5, 4, 4, 3,
3, 2, 1, 1
],
"Churn": [
1, 1, 1, 0,
0, 0, 0, 0
]
})
X = customers[
["MonthlyUsage", "SupportTickets"]
]
y = customers["Churn"]
model = LogisticRegression()
model.fit(X, y)
new_customer = pd.DataFrame({
"MonthlyUsage": [15],
"SupportTickets": [3]
})
prediction = model.predict(
new_customer
)
print(
"Predicted Churn:",
prediction[0]
)
Spam filtering is a classification problem where messages are assigned to categories such as spam or not spam.
Email
↓
Text Cleaning
↓
Feature Extraction
↓
Labeled Training Data
↓
Classification Model
↓
Spam / Not Spam
Text classification can use techniques such as TF-IDF features together with a suitable classifier.
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
messages = [
"Win a free prize today",
"Meeting scheduled for tomorrow",
"Claim your free reward now",
"Project report is attached",
"You have won a cash prize",
"Please review the project report"
]
labels = [
1,
0,
1,
0,
1,
0
]
text_model = Pipeline([
("tfidf", TfidfVectorizer()),
("classifier", LogisticRegression())
])
text_model.fit(
messages,
labels
)
new_message = [
"You won a free prize"
]
prediction = text_model.predict(
new_message
)
print(
"Predicted Class:",
prediction[0]
)
1 represents spam and
0 represents non-spam in this teaching example.
Supervised learning can also be used in healthcare-related research and decision-support systems when suitable labeled data is available.
Patient Features
↓
Training Data
↓
Supervised Classification Model
↓
Predicted Risk Category
↓
Professional Review
| Algorithm | Common Use | Example |
|---|---|---|
| Linear Regression | Regression | Sales prediction |
| Logistic Regression | Classification | Purchase prediction |
| Decision Tree | Regression / Classification | Customer classification |
| Random Forest | Regression / Classification | Risk classification |
| KNN | Classification / Regression | Similarity-based prediction |
The following example combines the main steps of a supervised regression project.
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
)
# --------------------------------
# 1. Create historical data
# --------------------------------
data = {
"Advertising": [
10, 15, 20, 25, 30,
35, 40, 45, 50, 55,
60, 65
],
"WebsiteVisits": [
100, 130, 160, 190,
220, 250, 290, 320,
350, 390, 420, 450
],
"Sales": [
20, 27, 33, 39,
45, 52, 60, 66,
73, 81, 88, 95
]
}
df = pd.DataFrame(data)
# --------------------------------
# 2. Define features and target
# --------------------------------
X = df[
["Advertising", "WebsiteVisits"]
]
y = df["Sales"]
# --------------------------------
# 3. Split the data
# --------------------------------
X_train, X_test, y_train, y_test = train_test_split(
X,
y,
test_size=0.25,
random_state=42
)
# --------------------------------
# 4. Create model
# --------------------------------
model = LinearRegression()
# --------------------------------
# 5. Train model
# --------------------------------
model.fit(
X_train,
y_train
)
# --------------------------------
# 6. Predict test data
# --------------------------------
predictions = model.predict(
X_test
)
# --------------------------------
# 7. Evaluate model
# --------------------------------
mae = mean_absolute_error(
y_test,
predictions
)
r2 = r2_score(
y_test,
predictions
)
print("Mean Absolute Error:", mae)
print("R² Score:", r2)
# --------------------------------
# 8. Predict future sales
# --------------------------------
future = pd.DataFrame({
"Advertising": [70],
"WebsiteVisits": [500]
})
future_sales = model.predict(
future
)
print(
"Predicted Future Sales:",
future_sales[0]
)
- Define the problem.
- Collect labeled historical data.
- Explore and clean the dataset.
- Select useful features and the target.
- Split data into appropriate development sets.
- Train one or more candidate models.
- Evaluate using suitable metrics.
- Tune the workflow when necessary.
- Test on appropriate unseen data.
- Deploy and monitor when the model is ready.
House Price
Regression problem.
Sales Forecasting
Regression problem.
Salary Prediction
Regression problem.
Spam Detection
Classification problem.
Customer Churn
Classification problem.
Purchase Prediction
Classification problem.
- Training on data that should have been held out for evaluation.
- Using features that contain information from the future target.
- Ignoring missing or inconsistent data.
- Using an unsuitable metric for the business problem.
- Relying only on training performance.
- Ignoring class imbalance in classification problems.
- Applying preprocessing before the train/test split in a way that leaks information.
- Using a very small or unrepresentative dataset to make strong conclusions.
- Ignoring changes in real-world data after deployment.
- Assuming that a model's prediction is automatically a causal explanation.
- Clearly define the prediction target.
- Understand where the labels came from.
- Use representative and relevant data.
- Perform exploratory data analysis.
- Separate training and evaluation data correctly.
- Prevent data leakage.
- Build a simple baseline before complex models.
- Use cross-validation when appropriate.
- Choose metrics that reflect the actual objective.
- Inspect errors instead of looking only at one score.
- Document preprocessing and model assumptions.
- Monitor performance after deployment.
| Question | Check |
|---|---|
| What are we predicting? | Target is clearly defined |
| What data is available? | Features and labels are understood |
| Is the data suitable? | Quality and representativeness are checked |
| How is the data split? | Evaluation data is protected from training |
| Which model? | Algorithm matches the problem |
| Which metric? | Metric reflects the real objective |
| Does it generalize? | Performance is tested on relevant unseen data |
| What happens after deployment? | Performance and data drift are monitored |
- Supervised learning requires labeled examples for training.
- Features are inputs and the target is the value being predicted.
- Regression predicts numerical values.
- Classification predicts categories.
- Training and testing data should be kept appropriately separate.
- Preprocessing must be designed to avoid data leakage.
- Model performance should be evaluated on data not used for fitting.
- Use metrics that match the problem and its costs.
- Watch for overfitting and underfitting.
- Start with a simple baseline before increasing model complexity.
- Use cross-validation when it is appropriate for the dataset and task.
- Real-world models require monitoring after deployment.
Python Supervised Learning • Regression • Classification • Real-Time Examples