Bird
Raised Fist0
ML Pythonml~20 mins

Monitoring model performance in ML Python - ML Experiment: Train & Evaluate

Choose your learning style10 modes available
Experiment - Monitoring model performance
Problem:You have trained a classification model, but you do not have a system to track how well it performs over time on new data.
Current Metrics:Training accuracy: 92%, Validation accuracy: 88%, No monitoring in place.
Issue:Without monitoring, model performance may degrade unnoticed due to data changes or other factors.
Your Task
Implement a simple monitoring system that tracks model accuracy on new incoming data batches and alerts when accuracy drops below 85%.
Use only Python and scikit-learn.
Simulate new data batches for monitoring.
Do not retrain the model during monitoring.
Hint 1
Hint 2
Hint 3
Solution
ML Python
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
import numpy as np

# Step 1: Train initial model
X, y = make_classification(n_samples=1000, n_features=20, random_state=42)
X_train, X_val, y_train, y_val = train_test_split(X, y, test_size=0.2, random_state=42)
model = RandomForestClassifier(random_state=42)
model.fit(X_train, y_train)

# Step 2: Check initial validation accuracy
val_preds = model.predict(X_val)
val_accuracy = accuracy_score(y_val, val_preds)
print(f"Initial validation accuracy: {val_accuracy:.2f}")

# Step 3: Define monitoring function

def monitor_model(model, batches, threshold=0.85):
    accuracies = []
    for i, (X_batch, y_batch) in enumerate(batches, 1):
        preds = model.predict(X_batch)
        acc = accuracy_score(y_batch, preds)
        accuracies.append(acc)
        print(f"Batch {i} accuracy: {acc:.2f}")
        if acc < threshold:
            print(f"ALERT: Accuracy below threshold ({threshold}) on batch {i}!")
    return accuracies

# Step 4: Simulate new data batches for monitoring
np.random.seed(42)
batches = []
for _ in range(5):
    X_new, y_new = make_classification(n_samples=100, n_features=20, random_state=np.random.randint(1000))
    batches.append((X_new, y_new))

# Step 5: Run monitoring
monitor_accuracies = monitor_model(model, batches)
Added a function to evaluate model accuracy on new data batches.
Simulated new data batches to mimic incoming data.
Implemented alert printout when accuracy falls below 85%.
Results Interpretation

Before Monitoring: No tracking of model performance on new data, risk of unnoticed accuracy drops.

After Monitoring: Accuracy tracked on each batch; alert raised when accuracy dropped below 85% on batch 3.

Monitoring model performance on new data helps detect when the model starts to perform poorly, enabling timely action to maintain quality.
Bonus Experiment
Extend the monitoring system to log accuracy over time to a CSV file and plot the accuracy trend.
💡 Hint
Use Python's csv module or pandas to save data, and matplotlib to create a line plot.

Practice

(1/5)
1. Why is it important to monitor a machine learning model after deployment?
easy
A. To ensure the model continues to perform well on new data
B. To increase the model's training speed
C. To reduce the size of the model file
D. To change the model's algorithm automatically

Solution

  1. Step 1: Understand model deployment context

    After deployment, models face new data that may differ from training data.
  2. Step 2: Importance of monitoring

    Monitoring helps detect if the model's accuracy or other metrics drop over time.
  3. Final Answer:

    To ensure the model continues to perform well on new data -> Option A
  4. Quick Check:

    Monitoring = Ensure performance [OK]
Hint: Monitoring keeps models accurate after deployment [OK]
Common Mistakes:
  • Confusing monitoring with training speed
  • Thinking monitoring changes model algorithm automatically
  • Assuming monitoring reduces model size
2. Which of the following is the correct way to calculate accuracy in Python given true labels y_true and predicted labels y_pred?
easy
A. accuracy = sum(y_true != y_pred) / len(y_true)
B. accuracy = len(y_true) / sum(y_true == y_pred)
C. accuracy = sum(y_true == y_pred) / len(y_true)
D. accuracy = sum(y_pred) / sum(y_true)

Solution

  1. Step 1: Understand accuracy formula

    Accuracy = number of correct predictions divided by total predictions.
  2. Step 2: Match formula to code

    sum(y_true == y_pred) counts correct predictions; dividing by len(y_true) gives accuracy.
  3. Final Answer:

    accuracy = sum(y_true == y_pred) / len(y_true) -> Option C
  4. Quick Check:

    Correct predictions / total = accuracy [OK]
Hint: Accuracy = correct predictions divided by total [OK]
Common Mistakes:
  • Dividing total by correct instead of correct by total
  • Using inequality instead of equality for correct count
  • Summing predictions instead of comparing labels
3. Given the following Python code snippet monitoring model accuracy over time, what will be the printed output?
accuracies = [0.9, 0.85, 0.8, 0.75]
threshold = 0.8
alerts = [acc < threshold for acc in accuracies]
print(alerts)
medium
A. [False, False, True, True]
B. [True, True, True, True]
C. [True, False, False, False]
D. [False, False, False, True]

Solution

  1. Step 1: Evaluate each accuracy against threshold

    Check if each accuracy is less than 0.8: 0.9 < 0.8? False; 0.85 < 0.8? False; 0.8 < 0.8? False; 0.75 < 0.8? True.
  2. Step 2: Create alerts list

    List comprehension results in [False, False, False, True].
  3. Final Answer:

    [False, False, False, True] -> Option D
  4. Quick Check:

    Compare each value to threshold [OK]
Hint: Check each value against threshold in list comprehension [OK]
Common Mistakes:
  • Misunderstanding < vs <= in comparisons
  • Confusing True/False order in list
  • Assuming 0.8 < 0.8 is True
4. You have this Python code to monitor model loss, but it raises an error. What is the error and how to fix it?
losses = [0.3, 0.25, 0.4, 0.35]
for i in range(len(losses))
    if losses[i] > 0.3:
        print(f"High loss at index {i}: {losses[i]}")
medium
A. SyntaxError due to missing colon after for loop; add ':' after 'range(len(losses))' to fix
B. TypeError because losses is not iterable; convert losses to list to fix
C. IndentationError due to wrong indentation; fix indentation of print statement
D. NameError because variable 'i' is undefined; define 'i' before loop

Solution

  1. Step 1: Identify syntax error in for loop

    The for loop line is missing a colon at the end, which is required in Python syntax.
  2. Step 2: Fix syntax by adding colon

    Add ':' after range(len(losses)) to correct the syntax and allow the loop to run.
  3. Final Answer:

    SyntaxError due to missing colon after for loop; add ':' after 'range(len(losses))' to fix -> Option A
  4. Quick Check:

    Missing colon = SyntaxError [OK]
Hint: Check colons after for/if statements [OK]
Common Mistakes:
  • Ignoring missing colon causing syntax error
  • Confusing indentation error with syntax error
  • Assuming variable 'i' is undefined
5. You want to automate alerts when your model's F1 score drops below 0.7. Which approach best fits this monitoring task?
hard
A. Ignore F1 score and monitor only training loss during training
B. Set up a scheduled job that calculates F1 score daily and sends an alert if below 0.7
C. Manually check F1 score once a month and update the model if needed
D. Retrain the model automatically every hour regardless of performance

Solution

  1. Step 1: Understand monitoring automation

    Automated scheduled jobs can regularly check model metrics like F1 score.
  2. Step 2: Choose alerting based on threshold

    Sending alerts when F1 score drops below 0.7 helps catch performance issues early.
  3. Final Answer:

    Set up a scheduled job that calculates F1 score daily and sends an alert if below 0.7 -> Option B
  4. Quick Check:

    Automate checks + alerts = Set up a scheduled job that calculates F1 score daily and sends an alert if below 0.7 [OK]
Hint: Automate metric checks and alert on threshold breach [OK]
Common Mistakes:
  • Retraining without checking performance first
  • Manual checks too infrequent for timely alerts
  • Ignoring key metrics like F1 score
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard