Bird
Raised Fist0

Naive Bayes - Conditional Independence, When It Still Wins

THEORYintermediateInterview freq: medium
Choose your preparation mode6 modes available
🐛
The Feature Addition Paradox
Started immediately after the last feature update, ongoing for 3 days

Spam detection model using Naive Bayes, processing 500K emails per day

Symptom
Model accuracy remains stable at 0.92, but recall drops to 0.0 after adding a new feature
📡
Signals
metric
Recall on the test set
Recall dropped from 0.85 to 0.0 after adding 'email_length' feature
feature_importance
Feature importance ranking
'email_length' feature importance is disproportionately high at 0.95
distribution
Distribution of 'email_length' feature
Highly skewed with 90% of values in a narrow range
log
Model training logs
No errors or warnings during training
metric
Precision on the test set
Precision increased from 0.88 to 0.95
🔬
Hypotheses
The new feature 'email_length' is causing a conditional independence violation
Recall dropped to 0.0'email_length' feature importance is 0.95
Verify: Check if 'email_length' is highly correlated with other features
import numpy as np
np.corrcoef(df['email_length'], df['other_feature'])[0, 1]
The model is overfitting to the 'email_length' feature
'email_length' feature importance is 0.95Distribution of 'email_length' is highly skewed
Verify: Evaluate model performance without 'email_length'
model.fit(X_train.drop(columns=['email_length']), y_train)
model.evaluate(X_test.drop(columns=['email_length']), y_test)
🎯
Root Cause
The 'email_length' feature introduced a strong correlation with the target, violating Naive Bayes' conditional independence assumption.

The feature was added without checking its correlation with existing features and the target.

🔧
Fix Strategy
ImmediateRemove 'email_length' feature from the model
Short-termAnalyze feature correlations and retrain the model with a subset of features
Long-termImplement feature selection and correlation checks in the feature engineering pipeline
🐍
Python Fix
Python
correlation_matrix = df.corr()
features_to_remove = [col for col in correlation_matrix.columns if abs(correlation_matrix['target'][col]) > 0.8]
X_train_filtered = X_train.drop(columns=features_to_remove)
model.fit(X_train_filtered, y_train)
✗
Common Wrong Diagnoses
▼ Show
The model is overfitting due to too many features
Why candidates think this: High feature importance and skewed distribution suggest overfitting
Why wrong: The issue is not the number of features but the violation of conditional independence
The model has a bug in the training process
Why candidates think this: Recall dropping to zero suggests a training issue
Why wrong: Training logs show no errors, and the issue is feature-related
📊
Monitoring to Add
  • Monitor feature importance changes after each deployment
  • Set up alerts for drastic drops in recall
  • Track distribution changes of key features
📋
Process Change

Introduce a mandatory feature correlation analysis step before deployment

🏗️
Architectural Change

Incorporate automated feature selection techniques that account for feature correlations

💡
Key Insight
Naive Bayes can fail silently when a new feature violates its conditional independence assumption, even if accuracy remains high.

Practice

(1/5)
1.
import torch
x = torch.tensor([-1.0, 0.0, 1.0])
output = torch.nn.functional.relu(x)
print(output)
What is the output of this code?
easy
A. tensor([0.0, 0.0, 1.0])
B. tensor([-1.0, 0.0, 1.0])
C. tensor([0.0, 0.0, 0.0])
D. tensor([-1.0, 0.0, 0.0])

Solution

  1. Step 1: Understand ReLU behavior.

    ReLU outputs zero for negative inputs and the input itself for non-negative inputs.
  2. Step 2: Apply ReLU to each element.

    For -1.0, output is 0.0; for 0.0, output is 0.0; for 1.0, output is 1.0.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    ReLU zeros negatives, keeps positives. [OK]
Hint: ReLU zeros negatives, keeps positives. [OK]
Common Mistakes:
2. In a deep learning model, when is it more appropriate to use Layer Normalization instead of Batch Normalization?
easy
A. When the model is trained on a very large batch size.
B. When the model is trained on a very small batch size or online learning.
C. When the model has a very deep architecture.
D. When the model is trained on a balanced dataset.

Solution

  1. Step 1: Understand the context of normalization techniques.

    Batch Normalization relies on batch statistics, which can be unstable with small batch sizes. Layer Normalization uses layer statistics, making it more stable for small batches or online learning.
  2. Step 2: Eliminate wrong options.

    When the model is trained on a very large batch size. is incorrect because large batch sizes are suitable for Batch Normalization. When the model has a very deep architecture. is incorrect because depth doesn't directly affect the choice between these normalizations. When the model is trained on a balanced dataset. is irrelevant to normalization choice.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Layer Norm for small batches or online learning. [OK]
Hint: Layer Norm for small batches or online learning. [OK]
Common Mistakes:
3. When framing a business problem as an ML problem, which trade-off is most critical to consider?
medium
A. Data volume vs. Model complexity
B. Training time vs. Inference time
C. Accuracy vs. Interpretability
D. Feature engineering vs. Hyperparameter tuning

Solution

  1. Step 1: Identify the key trade-off

    In many business contexts, the trade-off between accuracy and interpretability is crucial because stakeholders need to understand model decisions.
  2. Step 2: Eliminate wrong options

    Data volume vs. Model complexity is incorrect because data volume and model complexity are often complementary. Training time vs. Inference time is incorrect because training and inference times are usually secondary to model performance. Feature engineering vs. Hyperparameter tuning is incorrect because feature engineering and hyperparameter tuning are not directly opposing trade-offs.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Balance accuracy with interpretability for stakeholder trust. [OK]
Hint: Balance accuracy with interpretability for stakeholder trust. [OK]
Common Mistakes:
4. A KNN model is performing poorly on a high-dimensional dataset. What is the most likely cause?
medium
A. The model has too few neighbors.
B. The distance metric is ineffective in high dimensions.
C. The dataset is too small.
D. The model is overfitting due to too many neighbors.

Solution

  1. Step 1: Consider high-dimensional effects

    In high dimensions, distance metrics often become less effective.
  2. Step 2: Eliminate wrong options

    The model has too few neighbors. is incorrect as increasing neighbors may not help. The dataset is too small. is wrong because size isn't the main issue. The model is overfitting due to too many neighbors. is incorrect as overfitting is less likely with many neighbors.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    High dimensions dilute distance metrics. [OK]
Hint: High dimensions dilute distance metrics. [OK]
Common Mistakes:
5. You implemented stratified sampling but notice that the sample still has class imbalance. What is the most likely cause?
medium
A. Data leakage from training set.
B. Using random sampling instead.
C. Incorrectly specified class proportions.
D. Insufficient sample size.

Solution

  1. Step 1: Identify the stratified sampling requirement.

    Stratified sampling requires correct class proportion specification.
  2. Step 2: Eliminate unrelated issues.

    Random Sampling (B) would not be used if stratified was intended. Data leakage (C) affects model performance, not sampling. Sample size (D) affects variability, not imbalance directly.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Check class proportions in stratified sampling [[check]]
Hint: Check class proportions in stratified sampling [[check]]
Common Mistakes:
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