Bird
Raised Fist0
ML Pythonml~8 mins

Anomaly detection basics in ML Python - Model Metrics & Evaluation

Choose your learning style10 modes available
Metrics & Evaluation - Anomaly detection basics
Which metric matters for anomaly detection and WHY

Anomaly detection finds rare or unusual cases in data, like fraud or faults. Because anomalies are rare, Recall is very important. Recall tells us how many real anomalies the model finds. Missing anomalies can be costly or dangerous.

Precision is also important to avoid too many false alarms, which waste time. But usually, finding all anomalies (high recall) is the priority.

Accuracy is less useful here because most data is normal, so a model can be very accurate by just guessing normal all the time.

Confusion matrix for anomaly detection
      | Predicted Normal | Predicted Anomaly |
      |------------------|-------------------|
      | True Negative (TN)| False Positive (FP)|
      | False Negative (FN)| True Positive (TP) |

      Example with 1000 samples:
      - TP = 40 (correctly found anomalies)
      - FP = 10 (normal flagged as anomaly)
      - TN = 940 (correctly found normal)
      - FN = 10 (missed anomalies)

      Total = TP + FP + TN + FN = 1000
    
Precision vs Recall tradeoff with examples

Imagine a credit card fraud detector:

  • High Recall: Finds almost all frauds, but may flag some good transactions wrongly (more false alarms).
  • High Precision: Flags only very sure frauds, fewer false alarms, but might miss some frauds.

For fraud, missing fraud (low recall) is worse than some false alarms, so recall is prioritized.

In other cases, like spam filters, high precision is preferred to avoid blocking good emails.

What good vs bad metric values look like

Good model:

  • Recall close to 1.0 (finds almost all anomalies)
  • Precision reasonably high (few false alarms)
  • Accuracy may be high but is less important

Bad model:

  • Recall very low (misses many anomalies)
  • Precision very low (many false alarms)
  • Accuracy high but misleading (just predicts normal)
Common pitfalls in anomaly detection metrics
  • Accuracy paradox: High accuracy can hide poor anomaly detection because anomalies are rare.
  • Data leakage: If anomaly info leaks into training, metrics look better but model fails in real use.
  • Overfitting: Model fits training anomalies too closely but misses new types.
  • Ignoring class imbalance: Not adjusting for rare anomalies leads to misleading metrics.
Self-check question

Your anomaly detection model has 98% accuracy but only 12% recall on anomalies. Is it good for production? Why or why not?

Answer: No, it is not good. The model misses 88% of anomalies, which defeats the purpose of anomaly detection. High accuracy is misleading because most data is normal. You need to improve recall to catch more anomalies.

Key Result
In anomaly detection, recall is key to catch rare anomalies, while precision controls false alarms; accuracy alone can be misleading.

Practice

(1/5)
1. What is the main goal of anomaly detection in machine learning?
easy
A. To reduce the number of features in the data
B. To increase the size of the training dataset
C. To find unusual data points that differ from normal patterns
D. To cluster data points into groups

Solution

  1. Step 1: Understand anomaly detection purpose

    Anomaly detection aims to identify data points that do not fit the expected pattern.
  2. Step 2: Compare options with definition

    Only To find unusual data points that differ from normal patterns describes finding unusual data points, which matches the goal.
  3. Final Answer:

    To find unusual data points that differ from normal patterns -> Option C
  4. Quick Check:

    Anomaly detection = find unusual points [OK]
Hint: Anomaly detection finds data points that stand out [OK]
Common Mistakes:
  • Confusing anomaly detection with clustering
  • Thinking it reduces features
  • Assuming it increases dataset size
2. Which of the following is the correct way to import the IsolationForest model from scikit-learn in Python?
easy
A. from sklearn.ensemble import IsolationForest
B. import IsolationForest from sklearn
C. from sklearn.isolation import Forest
D. import sklearn.IsolationForest

Solution

  1. Step 1: Recall correct import syntax for IsolationForest

    The IsolationForest model is in sklearn.ensemble module and imported as shown in from sklearn.ensemble import IsolationForest.
  2. Step 2: Check other options for syntax errors

    Options A, C, and D have incorrect syntax or wrong module names.
  3. Final Answer:

    from sklearn.ensemble import IsolationForest -> Option A
  4. Quick Check:

    Correct import = from sklearn.ensemble import IsolationForest [OK]
Hint: Remember sklearn.ensemble holds IsolationForest [OK]
Common Mistakes:
  • Using wrong module name like sklearn.isolation
  • Incorrect import syntax like 'import X from Y'
  • Trying to import directly from sklearn without submodule
3. Given the following Python code using IsolationForest, what will be the output of print(predictions)?
from sklearn.ensemble import IsolationForest
import numpy as np

X_train = np.array([[1], [2], [3], [4], [5]])
model = IsolationForest(random_state=42)
model.fit(X_train)

X_test = np.array([[1], [10], [3]])
predictions = model.predict(X_test)
print(predictions)
medium
A. [0 1 0]
B. [-1 -1 -1]
C. [1 1 1]
D. [ 1 -1 1]

Solution

  1. Step 1: Understand IsolationForest prediction output

    IsolationForest predicts 1 for normal points and -1 for anomalies.
  2. Step 2: Analyze test points relative to training data

    Points 1 and 3 are close to training data, so predicted as normal (1). Point 10 is far, predicted as anomaly (-1).
  3. Final Answer:

    [ 1 -1 1] -> Option D
  4. Quick Check:

    Close points = 1, far point = -1 [OK]
Hint: Normal points get 1, anomalies get -1 in IsolationForest [OK]
Common Mistakes:
  • Assuming all predictions are 1
  • Confusing -1 with 0 for anomalies
  • Ignoring distance of test points from training data
4. The following code throws an error. What is the most likely cause?
from sklearn.ensemble import IsolationForest
model = IsolationForest()
model.predict([[1], [2], [3]])
medium
A. The input data format is incorrect
B. The model was not trained before prediction
C. IsolationForest cannot predict on lists
D. Missing random_state parameter

Solution

  1. Step 1: Check if model is trained before prediction

    The code calls predict without calling fit first, so the model is not trained.
  2. Step 2: Understand IsolationForest requirements

    Model must be trained with fit() before predict() to avoid error.
  3. Final Answer:

    The model was not trained before prediction -> Option B
  4. Quick Check:

    Call fit() before predict() [OK]
Hint: Always train model with fit() before predict() [OK]
Common Mistakes:
  • Trying to predict without training
  • Thinking input format causes error here
  • Assuming random_state is mandatory
5. You have a dataset with mostly normal data and a few anomalies. You want to detect anomalies using IsolationForest. Which approach is best to prepare your model?
hard
A. Train IsolationForest only on normal data, then predict on all data
B. Train IsolationForest on all data including anomalies
C. Train IsolationForest only on anomalies
D. Train IsolationForest on random subsets ignoring labels

Solution

  1. Step 1: Understand IsolationForest training strategy

    IsolationForest is an unsupervised algorithm designed to be trained on data that mostly contains normal points. Training only on normal data helps the model learn the normal pattern and then detect anomalies during prediction.
  2. Step 2: Evaluate options for training data

    Training only on normal data, then predicting on all data (D) is the best approach. Training on all data including anomalies (B) can reduce detection accuracy as anomalies influence the model.
  3. Final Answer:

    Train IsolationForest only on normal data, then predict on all data -> Option A
  4. Quick Check:

    Train on normal data only [OK]
Hint: Train IsolationForest on normal data only for better anomaly detection [OK]
Common Mistakes:
  • Training on all data including anomalies
  • Training only on anomalies
  • Ignoring the importance of training data quality
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