Model Evaluation in Data Analysis

Learn how to measure, compare, and validate machine learning models using practical Python techniques and real-time examples from sales, customer churn, fraud detection, loan approval, and business analytics.

What is Model Evaluation?

Model evaluation is the process of measuring how well a machine learning model performs on data it has not seen during training.

A model may produce predictions, but evaluation helps us understand whether those predictions are accurate and useful for the intended business problem.

Training Data:
Data used to learn patterns.
Testing Data:
Unseen data used to measure generalization.
Evaluation Metric:
A numerical measure of model performance.
Business Goal:
Determine whether model predictions are useful for the real-world task.
1. Model Evaluation Workflow
Data
→
Train / Test
→
Train Model
→
Predict
→
Evaluate
→
Improve

A good evaluation workflow separates model training from model testing and uses metrics appropriate to the problem.

2. Why Model Evaluation is Important
  • Measures how well predictions match real outcomes.
  • Helps identify overfitting.
  • Allows comparison between different models.
  • Helps identify weaknesses in predictions.
  • Supports better model selection.
  • Shows whether the model is suitable for a business problem.
A high score on training data does not automatically mean that a model will perform well on new, unseen data.
3. Regression vs Classification Evaluation
Problem Type Example Common Metrics
Regression Predict house price MAE, MSE, RMSE, R²
Binary Classification Predict customer churn Accuracy, Precision, Recall, F1, ROC-AUC
Multiclass Classification Predict product category Accuracy, Precision, Recall, F1
4. Creating a Real-Time Regression Dataset

Suppose an online business wants to predict monthly sales from advertising spending.

Python
import pandas as pd

data = {
    "Advertising": [10, 12, 15, 18, 20, 25, 28, 30, 35, 40],
    "Sales": [120, 135, 150, 175, 190, 220, 250, 270, 300, 340]
}

df = pd.DataFrame(data)

print(df)
5. Splitting Data into Training and Testing Sets

A common approach is to train the model using one portion of the data and evaluate it on another portion.

Python
from sklearn.model_selection import train_test_split

X = df[["Advertising"]]
y = df["Sales"]

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42
)
Important: The test set should represent data that the model did not use when learning its parameters.
6. Training a Regression Model
Python
from sklearn.linear_model import LinearRegression

model = LinearRegression()

model.fit(X_train, y_train)

predictions = model.predict(X_test)

print(predictions)
7. Mean Absolute Error (MAE)

MAE calculates the average absolute difference between actual values and predicted values.

MAE = Average(|Actual - Predicted|)
Python
from sklearn.metrics import mean_absolute_error

mae = mean_absolute_error(
    y_test,
    predictions
)

print("MAE:", mae)

If MAE is 12, the model's predictions differ from the actual values by 12 units on average for the evaluated observations.

8. Mean Squared Error (MSE)

MSE calculates the average squared prediction error. Squaring gives larger errors more influence.

MSE = Average((Actual - Predicted)²)
Python
from sklearn.metrics import mean_squared_error

mse = mean_squared_error(
    y_test,
    predictions
)

print("MSE:", mse)
9. Root Mean Squared Error (RMSE)

RMSE is the square root of MSE. Because it is expressed in the same units as the target variable, it can be easier to interpret.

RMSE = √MSE
Python
import numpy as np
from sklearn.metrics import mean_squared_error

rmse = np.sqrt(
    mean_squared_error(
        y_test,
        predictions
    )
)

print("RMSE:", rmse)
10. R² Score

R², or the coefficient of determination, describes how much of the variation in the target is explained by the regression model relative to a baseline based on the mean target.

Python
from sklearn.metrics import r2_score

r2 = r2_score(
    y_test,
    predictions
)

print("R² Score:", r2)
R² can be negative on unseen data when the model performs worse than the mean-prediction baseline.
11. Evaluating a Regression Model Together
Python
from sklearn.metrics import (
    mean_absolute_error,
    mean_squared_error,
    r2_score
)

mae = mean_absolute_error(y_test, predictions)
mse = mean_squared_error(y_test, predictions)
rmse = mse ** 0.5
r2 = r2_score(y_test, predictions)

print("MAE:", mae)
print("MSE:", mse)
print("RMSE:", rmse)
print("R²:", r2)
MAE
Average absolute error
MSE
Squared error
RMSE
Error in target units
R²
Explained variation relative to baseline
12. Actual vs Predicted Values

Comparing actual and predicted values helps analysts understand individual prediction errors.

Python
comparison = pd.DataFrame({
    "Actual": y_test.values,
    "Predicted": predictions
})

comparison["Error"] = (
    comparison["Actual"]
    - comparison["Predicted"]
)

print(comparison)
13. Real-Time Example: Sales Prediction

A retail company predicts monthly sales from advertising expenditure. Model evaluation can help determine whether the prediction error is small enough for planning purposes.

  • Marketing budget can be compared with predicted sales.
  • Actual sales can be compared with predictions after each month.
  • MAE can communicate average prediction error.
  • RMSE can highlight larger prediction mistakes.
  • R² can describe explanatory performance relative to a baseline.
14. Creating a Classification Dataset

Now suppose an online company wants to predict whether a customer will leave the service.

Python
import pandas as pd

data = {
    "Age": [22, 25, 30, 35, 40, 45, 50, 55, 60, 65],
    "Monthly_Usage": [20, 25, 40, 45, 50, 30, 28, 22, 18, 15],
    "Churn": [1, 1, 0, 0, 0, 1, 1, 1, 1, 1]
}

df = pd.DataFrame(data)

print(df)
15. Training a Classification Model
Python
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

X = df[
    ["Age", "Monthly_Usage"]
]

y = df["Churn"]

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.2,
    random_state=42
)

model = LogisticRegression()

model.fit(X_train, y_train)

predictions = model.predict(X_test)

print(predictions)
16. Accuracy Score

Accuracy is the proportion of predictions that are correct.

Accuracy = Correct Predictions / Total Predictions
Python
from sklearn.metrics import accuracy_score

accuracy = accuracy_score(
    y_test,
    predictions
)

print("Accuracy:", accuracy)
Accuracy can be misleading when classes are highly imbalanced.
17. Confusion Matrix

A confusion matrix shows how classification predictions are distributed across actual and predicted classes.

Predicted Positive Predicted Negative
Actual Positive True Positive False Negative
Actual Negative False Positive True Negative
Python
from sklearn.metrics import confusion_matrix

cm = confusion_matrix(
    y_test,
    predictions
)

print(cm)
18. Precision

Precision answers: Of the observations predicted as positive, how many were actually positive?

Precision = TP / (TP + FP)
Python
from sklearn.metrics import precision_score

precision = precision_score(
    y_test,
    predictions,
    zero_division=0
)

print("Precision:", precision)
19. Recall

Recall answers: Of all actual positive observations, how many did the model identify?

Recall = TP / (TP + FN)
Python
from sklearn.metrics import recall_score

recall = recall_score(
    y_test,
    predictions,
    zero_division=0
)

print("Recall:", recall)
20. F1 Score

F1 score is the harmonic mean of precision and recall.

F1 = 2 × (Precision × Recall) / (Precision + Recall)
Python
from sklearn.metrics import f1_score

f1 = f1_score(
    y_test,
    predictions,
    zero_division=0
)

print("F1 Score:", f1)
21. Classification Report

The classification report provides precision, recall, F1 score, and support for each class.

Python
from sklearn.metrics import classification_report

print(
    classification_report(
        y_test,
        predictions,
        zero_division=0
    )
)
22. Real-Time Example: Customer Churn

A telecom company wants to identify customers who may leave the service.

Metric Business Question
Accuracy How often is the classification correct overall?
Precision How reliable are predicted churn cases?
Recall How many actual churners were detected?
F1 How does the model balance precision and recall?

The appropriate metric depends on the cost and consequences of different types of mistakes.

23. ROC Curve and AUC

For binary classification, the ROC curve examines the trade-off between true positive rate and false positive rate across classification thresholds.

AUC summarizes the area under the ROC curve. It is commonly used as a threshold-independent ranking metric.

Python
from sklearn.metrics import roc_auc_score

probabilities = model.predict_proba(
    X_test
)[:, 1]

auc = roc_auc_score(
    y_test,
    probabilities
)

print("ROC-AUC:", auc)
24. Precision-Recall Curve

A precision-recall curve shows how precision and recall change as the classification threshold changes.

Python
from sklearn.metrics import precision_recall_curve

precision, recall, thresholds = precision_recall_curve(
    y_test,
    probabilities
)

print("Precision values:", precision)
print("Recall values:", recall)
Precision-recall analysis can be especially informative when the positive class is relatively uncommon.
25. Cross-Validation

Cross-validation repeatedly splits the available training data into training and validation portions to estimate model performance more robustly.

Python
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("Mean R²:", scores.mean())
26. Why Cross-Validation is Useful
  • Uses multiple train-validation splits.
  • Provides several performance measurements.
  • Helps assess variation across different data splits.
  • Can support model comparison.
  • Can be useful for selecting model configurations.
Test data should remain separate when you need an unbiased final estimate after model selection.
27. Comparing Two Regression Models

Suppose we want to compare Linear Regression and Random Forest Regression on the same evaluation data.

Python
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error

linear_model = LinearRegression()

forest_model = RandomForestRegressor(
    n_estimators=100,
    random_state=42
)

linear_model.fit(X_train, y_train)
forest_model.fit(X_train, y_train)

linear_pred = linear_model.predict(X_test)
forest_pred = forest_model.predict(X_test)

linear_mae = mean_absolute_error(
    y_test,
    linear_pred
)

forest_mae = mean_absolute_error(
    y_test,
    forest_pred
)

print("Linear Regression MAE:", linear_mae)
print("Random Forest MAE:", forest_mae)

The metric values can be examined alongside model complexity, interpretability, computational requirements, and business requirements.

28. Real-Time Example: House Price Prediction

A real-estate company predicts property prices using:

  • Area
  • Number of bedrooms
  • Location-related features
  • Property age
  • Parking availability

MAE can communicate the average price error in currency units, while RMSE gives more influence to larger mistakes. R² can provide a complementary measure of explained variation.

29. Real-Time Example: Loan Approval

A financial institution may use a classification model to predict whether an application belongs to an approval category based on application features.

Evaluation Element Purpose
Confusion Matrix Inspect types of classification errors.
Precision Measure reliability of predicted positive cases.
Recall Measure coverage of actual positive cases.
F1 Score Summarize precision and recall together.
Financial decisions require careful validation, appropriate governance, and consideration of fairness and regulatory requirements beyond a single model metric.
30. Real-Time Example: Fraud Detection

Fraud detection datasets can be highly imbalanced, with legitimate transactions greatly outnumbering fraudulent ones.

In such cases, accuracy alone may hide poor detection of the minority class. Analysts often examine precision, recall, F1, ROC-AUC, and precision-recall behavior.

Python
from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score
)

print("Accuracy:",
      accuracy_score(y_test, predictions))

print("Precision:",
      precision_score(
          y_test,
          predictions,
          zero_division=0
      ))

print("Recall:",
      recall_score(
          y_test,
          predictions,
          zero_division=0
      ))

print("F1:",
      f1_score(
          y_test,
          predictions,
          zero_division=0
      ))
31. Multiclass Classification Evaluation

Some problems have more than two classes, such as predicting whether a support ticket is Billing, Technical, Account, or General.

Python
from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score
)

accuracy = accuracy_score(
    y_test,
    predictions
)

precision = precision_score(
    y_test,
    predictions,
    average="weighted",
    zero_division=0
)

recall = recall_score(
    y_test,
    predictions,
    average="weighted",
    zero_division=0
)

f1 = f1_score(
    y_test,
    predictions,
    average="weighted",
    zero_division=0
)

print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1:", f1)
32. Training Score vs Testing Score

Comparing training and testing performance can reveal potential generalization problems.

Python
train_score = model.score(
    X_train,
    y_train
)

test_score = model.score(
    X_test,
    y_test
)

print("Training Score:", train_score)
print("Testing Score:", test_score)
A very large gap between training and test performance can be a sign of overfitting, although the correct interpretation depends on the model and evaluation setup.
33. Overfitting and Model Evaluation

Overfitting occurs when a model learns training-specific patterns that do not generalize well to unseen data.

Observation Possible Interpretation
High training performance, much lower test performance Possible overfitting
Low training and test performance Possible underfitting
Similar training and test performance More consistent generalization, subject to metric and data quality
34. Underfitting and Model Evaluation

Underfitting occurs when a model is too limited to capture important patterns in the data.

If both training and testing performance are poor, the analyst may investigate feature quality, model complexity, data quantity, and preprocessing.

35. Baseline Models

A baseline is a simple reference model against which more complex models can be compared.

Python
from sklearn.dummy import DummyRegressor

baseline = DummyRegressor(
    strategy="mean"
)

baseline.fit(
    X_train,
    y_train
)

baseline_pred = baseline.predict(
    X_test
)

print(
    "Baseline MAE:",
    mean_absolute_error(
        y_test,
        baseline_pred
    )
)

A sophisticated model should be evaluated against an appropriate baseline rather than judged only by its own metric value.

36. Model Evaluation with Cross-Validation
Python
from sklearn.model_selection import cross_val_score
from sklearn.ensemble import RandomForestRegressor

model = RandomForestRegressor(
    n_estimators=100,
    random_state=42
)

scores = cross_val_score(
    model,
    X,
    y,
    cv=5,
    scoring="neg_mean_absolute_error"
)

mae_scores = -scores

print("MAE Scores:", mae_scores)
print("Average MAE:", mae_scores.mean())
Scikit-learn uses negative scoring values for loss metrics such as MAE in cross-validation because its scoring interface is designed so that higher scores are better.
37. Real-Time Example: Employee Salary Prediction

An HR analytics team predicts salary using years of experience, education-related variables, role, and other relevant features.

The team can evaluate the model using MAE and RMSE and compare results across validation folds. The evaluation should also consider whether the dataset and features appropriately represent the intended use.

38. Real-Time Example: Support Ticket Classification

A company automatically classifies support tickets into categories such as:

  • Billing
  • Technical Issue
  • Account
  • Shipping

The classification report can show precision, recall, and F1 for each category instead of relying only on overall accuracy.

39. Comparing Multiple Models

Model comparison should use the same evaluation protocol wherever possible.

Model Evaluation Metric Purpose
Linear Regression MAE / RMSE / R² Regression prediction
Decision Tree Accuracy / F1 or regression metrics Flexible prediction
Random Forest Classification or regression metrics Ensemble prediction
Logistic Regression Accuracy / Precision / Recall / F1 / AUC Classification
40. Complete Real-Time Model Evaluation Project

The following example demonstrates a complete classification evaluation workflow for customer churn prediction.

Complete Python Example
import pandas as pd

from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

from sklearn.metrics import (
    accuracy_score,
    precision_score,
    recall_score,
    f1_score,
    confusion_matrix,
    classification_report,
    roc_auc_score
)


# 1. Create dataset
df = pd.DataFrame({
    "Age": [22, 25, 28, 30, 35, 40, 45, 50, 55, 60],
    "Usage": [20, 25, 30, 45, 50, 40, 35, 25, 20, 15],
    "Churn": [1, 1, 1, 0, 0, 0, 1, 1, 1, 1]
})


# 2. Select features and target
X = df[["Age", "Usage"]]
y = df["Churn"]


# 3. Split the data
X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.3,
    random_state=42
)


# 4. Train the model
model = LogisticRegression()

model.fit(X_train, y_train)


# 5. Generate predictions
predictions = model.predict(X_test)

probabilities = model.predict_proba(
    X_test
)[:, 1]


# 6. Calculate metrics
accuracy = accuracy_score(
    y_test,
    predictions
)

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
)

auc = roc_auc_score(
    y_test,
    probabilities
)


# 7. Display results
print("Accuracy:", accuracy)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1)
print("ROC-AUC:", auc)

print("\nConfusion Matrix:")
print(
    confusion_matrix(
        y_test,
        predictions
    )
)

print("\nClassification Report:")
print(
    classification_report(
        y_test,
        predictions,
        zero_division=0
    )
)
Evaluation result:
The analyst receives several complementary measurements instead of relying on a single score.
41. Selecting the Right Metric
Situation Useful Metrics to Consider
Continuous prediction MAE, RMSE, R²
Balanced classification Accuracy, F1, confusion matrix
Rare positive class Precision, Recall, F1, PR-AUC
Probability ranking ROC-AUC and other probability-quality metrics
Business cost of errors Threshold analysis and cost-based evaluation
There is no single metric that is appropriate for every machine learning problem.
42. Threshold Tuning

Many classification models produce probabilities. The classification threshold can be changed depending on the application's objectives.

Python
probabilities = model.predict_proba(
    X_test
)[:, 1]

threshold = 0.40

custom_predictions = (
    probabilities >= threshold
).astype(int)

print(custom_predictions)

Changing the threshold changes the balance between false positives and false negatives, so threshold selection should be evaluated against the actual business objective.

43. Evaluating Model Stability

A model should not be evaluated from only one arbitrary train-test split when the dataset and problem require more robust analysis.

  • Use cross-validation where appropriate.
  • Inspect performance variation across folds.
  • Check whether results change substantially with different splits.
  • Evaluate on a final holdout test set after model selection.
  • Monitor performance after deployment.
44. Model Evaluation After Deployment

Evaluation does not necessarily end when a model is deployed. Real-world data can change over time.

New Data
→
Predictions
→
Actual Outcomes
→
Monitor

Once actual outcomes become available, the organization can compare predictions with reality and monitor whether model performance changes.

45. Data Leakage and Evaluation

Data leakage occurs when information that would not be available at prediction time improperly enters the training or evaluation process.

Leakage can make evaluation results look much better than the model's true performance on future unseen data.

Preprocessing steps such as scaling or imputation should generally be fitted using training data within the evaluation workflow rather than using the complete dataset before splitting.

46. Model Evaluation with a Pipeline

A Scikit-learn pipeline can combine preprocessing and model training so that preprocessing is performed consistently within cross-validation.

Python
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score

pipeline = Pipeline([
    ("scaler", StandardScaler()),
    ("model", LogisticRegression())
])

scores = cross_val_score(
    pipeline,
    X,
    y,
    cv=5,
    scoring="accuracy"
)

print("CV Scores:", scores)
print("Mean Accuracy:", scores.mean())
47. Common Model Evaluation Mistakes
  • Evaluating only on training data.
  • Using accuracy for every classification problem.
  • Ignoring class imbalance.
  • Choosing a model using the test set repeatedly.
  • Allowing data leakage during preprocessing.
  • Comparing models using different evaluation datasets.
  • Ignoring business costs of false positives and false negatives.
  • Reporting one metric without explaining its context.
  • Ignoring performance changes after deployment.
48. Model Evaluation Best Practices
  • Define the business objective before selecting metrics.
  • Keep evaluation data separate from training data.
  • Use a suitable baseline.
  • Select metrics appropriate to the problem type.
  • Use cross-validation when appropriate.
  • Check for data leakage.
  • Inspect multiple metrics rather than relying on one number.
  • Examine individual prediction errors.
  • Compare models using the same evaluation protocol.
  • Monitor model performance after deployment.
49. Complete Model Evaluation Checklist
01
Define Objective
Know what the model must predict.
02
Split Data
Separate training and evaluation data.
03
Choose Metrics
Use metrics suitable for the task.
04
Validate
Check generalization and errors.
50. Important Model Evaluation Rules
Rule 1: Never evaluate a model only on the data used for training.
Rule 2: Choose evaluation metrics according to the problem and business objective.
Rule 3: MAE, MSE, RMSE, and R² are common regression metrics.
Rule 4: Accuracy, precision, recall, F1, confusion matrix, and AUC are common classification evaluation tools.
Rule 5: Accuracy alone can be misleading for imbalanced datasets.
Rule 6: Cross-validation can provide a more robust estimate of performance during model development.
Rule 7: Avoid data leakage during preprocessing and model selection.
Rule 8: Keep a final evaluation set separate when appropriate.
Rule 9: A model metric should always be interpreted in the context of the real-world problem.
Rule 10: Continue monitoring important model performance measures after deployment.

Model Evaluation in Data Analysis

Python Data Analysis • Machine Learning • Real-Time Examples