Bird
Raised Fist0

Feature Selection - Filter, Wrapper, Embedded Methods

THEORYintermediateInterview freq: medium
Choose your preparation mode6 modes available
▶
Execution Trace
Step 1/4
Filter Methods

Features ranked by correlation with target; top 5 selected.

🎯 Filter methods are fast and independent of the model.
from sklearn.feature_selection import SelectKBest, f_classif
X_new = SelectKBest(f_classif, k=5).fit_transform(X, y)
Wrapper Methods

Recursive feature elimination reduces features from 10 to 3.

🎯 Wrapper methods evaluate feature subsets using model performance.
from sklearn.feature_selection import RFE
from sklearn.linear_model import LogisticRegression
rfe = RFE(estimator=LogisticRegression(), n_features_to_select=3)
X_rfe = rfe.fit_transform(X, y)
Embedded Methods

LASSO regression zeroes out coefficients of 2 features.

🎯 Embedded methods perform feature selection during model training.
from sklearn.linear_model import Lasso
lasso = Lasso(alpha=0.1)
lasso.fit(X, y)
selected_features = lasso.coef_ != 0
Comparison

Filter methods selected features in 0.1s, Wrapper in 2s, Embedded in 1s.

🎯 Trade-offs between speed and accuracy in feature selection methods.
# Timing code omitted for brevity
import time
start = time.time()
# Run feature selection
end = time.time()
print('Time taken:', end - start)
📊
Diagram
Diagram
┌───────────────────────────────┐
│        Feature Selection      │
├─────────────┬─────────────────┤
│   Filter    │   Wrapper       │
│   Methods   │   Methods       │
│             │                 │
│ ┌─────────┐ │ ┌─────────────┐ │
│ │ Ranking │ │ │ Search      │ │
│ │ Metrics │ │ │ Algorithms  │ │
│ └─────────┘ │ └─────────────┘ │
│             │                 │
├─────────────┴─────────────────┤
│         Embedded Methods      │
│ ┌───────────────────────────┐ │
│ │ Model-Based Selection     │ │
│ │ (e.g., LASSO)             │ │
│ └───────────────────────────┘ │
└───────────────────────────────┘
  • Filter Methods: Use statistical tests to rank features.
  • Wrapper Methods: Use search algorithms to evaluate feature subsets.
  • Embedded Methods: Integrate feature selection within model training.
🔑
Key Moments
▲
Q: Why might one choose filter methods over wrapper methods?
A: Filter methods are computationally cheaper and faster, making them suitable for large datasets.
Q: How do embedded methods differ from wrapper methods?
A: Embedded methods integrate feature selection into the model training process, while wrapper methods evaluate feature subsets externally.
Q: What is a potential downside of using wrapper methods?
A: Wrapper methods can be computationally expensive as they involve training multiple models to evaluate feature subsets.

This diagram and trace explain the three primary feature selection methods: Filter, Wrapper, and Embedded. Filter methods rank features based on statistical tests, making them fast and model-independent. Wrapper methods use search algorithms to evaluate feature subsets, offering higher accuracy at the cost of computational expense. Embedded methods integrate feature selection within the model training process, balancing speed and accuracy. Understanding these methods helps in choosing the right approach based on dataset size and computational resources.

Primary Focus

✓ Feature Selection Methods

Practice

(1/5)
1. In the context of A/B testing for ML models, which method is best suited for ensuring that temporal trends do not bias the results?
easy
A. Holdout method
B. Interleaving method
C. Causal inference
D. Cross-validation

Solution

  1. Step 1: Understand the methods

    Interleaving method allows for simultaneous comparison, reducing temporal bias.
  2. Step 2: Eliminate wrong options

    Holdout and cross-validation do not address temporal trends. Causal inference is more about understanding causality than handling temporal trends.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Interleaving reduces temporal bias. [OK]
Hint: Interleaving reduces temporal bias. [OK]
Common Mistakes:
2. Given the following Python code snippet, what will be the output if the dataset contains data leakage?
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score

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)
y_pred = model.predict(X_test)
print(accuracy_score(y_test, y_pred))
easy
A. The accuracy will be lower than expected.
B. The code will throw an error due to data leakage.
C. The accuracy will be exactly as expected.
D. The accuracy will be higher than expected.

Solution

  1. Step 1: Understand the impact of data leakage

    Data leakage often results in overly optimistic performance metrics.
  2. Step 2: Analyze the code behavior

    The code will execute without errors, but if leakage exists, the model will perform better than it should.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Leakage inflates accuracy [OK]
Hint: Leakage inflates accuracy [OK]
Common Mistakes:
3.
import torch
optimizer = torch.optim.SGD(model.parameters(), lr=0.1)
for epoch in range(10):
    for data, target in dataloader:
        optimizer.zero_grad()
        output = model(data)
        loss = loss_fn(output, target)
        loss.backward()
        optimizer.step()
print(optimizer.param_groups[0]['lr'])
What will be printed after the loop?
easy
A. 0.0
B. 0.01
C. 0.1
D. Error

Solution

  1. Step 1: Understand the code.

    The learning rate is set to 0.1 and not changed in the loop.
  2. Step 2: Check for learning rate updates.

    SGD without a scheduler keeps the learning rate constant.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    SGD without scheduler keeps lr constant. [check]
Hint: SGD without scheduler keeps lr constant. [check]
Common Mistakes:
4.
import numpy as np
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier

X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]])
y = np.array([0, 1, 0, 1])

model = DecisionTreeClassifier()
scores = cross_val_score(model, X, y, cv=2)
print(scores)
What does this code output?
easy
A. An array of two accuracy scores, each representing a fold.
B. An error because the dataset is too small for cross-validation.
C. A single accuracy score for the entire dataset.
D. An array of four accuracy scores, one for each data point.

Solution

  1. Step 1: Understand cross-validation output

    Cross-validation with cv=2 splits the data into two folds, returning an array of two scores.
  2. Step 2: Eliminate wrong options

    An error because the dataset is too small for cross-validation. is incorrect because the code runs without error. A single accuracy score for the entire dataset. is incorrect because cross-validation returns multiple scores. An array of four accuracy scores, one for each data point. is incorrect because the number of scores equals the number of folds, not data points.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Cross-validation returns scores per fold. [OK]
Hint: Cross-validation returns scores per fold. [OK]
Common Mistakes:
5. When deciding between Few-Shot and Chain-of-Thought prompting, which scenario is best suited for Chain-of-Thought?
medium
A. When the task involves simple factual recall.
B. When the task requires understanding complex reasoning.
C. When the model needs to be fine-tuned with a few examples.
D. When the task requires generating creative content.

Solution

  1. Step 1: Understand Chain-of-Thought

    Chain-of-Thought is best for tasks requiring complex reasoning.
  2. Step 2: Eliminate wrong options

    When the task involves simple factual recall. is incorrect as factual recall doesn't need reasoning. When the model needs to be fine-tuned with a few examples. is about Few-Shot, not Chain-of-Thought. When the task requires generating creative content. is unrelated to reasoning.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Use Chain-of-Thought for complex reasoning tasks. [OK]
Hint: Use Chain-of-Thought for complex reasoning tasks. [OK]
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