executing-plans
executing-plans
Use when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is available
ds-feature-selection"Selects relevant features using univariate selection, recursive elimination stability selection, and importance-based methods"
Independent GitHub snapshot · Automated classification · Original documentation governs
name: ds-feature-selection compatibility: opencode completeness: 95 content-types:
Comprehensive guide to feature selection in machine learning and data science workflows.
Feature Selection is a critical component of the machine learning workflow. This skill covers:
# BAD: Fitting selector on full dataset before splitting causes data leakage
import pandas as pd
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import train_test_split
X = pd.DataFrame(np.random.randn(100, 10), columns=[f"feat_{i}" for i in range(10)])
y = np.random.randint(0, 2, 100)
selector = SelectKBest(f_classif, k=5)
X_selected = selector.fit_transform(X, y) # Data leakage: information from test set leaks into training
X_train, X_test, y_train, y_test = train_test_split(X_selected, y, random_state=42)
# GOOD: Using Pipeline ensures proper train/test separation and prevents leakage
from sklearn.pipeline import Pipeline
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
pipeline = Pipeline([
('selector', SelectKBest(f_classif, k=5))
('classifier', RandomForestClassifier(n_estimators=100, random_state=42))
])
scores = cross_val_score(pipeline, X, y, cv=5, scoring='accuracy')
print(f"Cross-validated accuracy: {scores.mean():.3f} (+/- {scores.std() * 2:.3f})")
import logging
import pandas as pd
import numpy as np
from typing import Any, Dict, List
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
from sklearn.exceptions import ConvergenceWarning
import warnings
logger = logging.getLogger(__name__)
warnings.filterwarnings("ignore", category=ConvergenceWarning)
class FeatureSelectionPipeline:
"""Production-grade feature selection with importance-based filtering.
Follows SOLID principles for maintainability and testability."""
def __init__(self, threshold: float = 0.01, max_features: int = None) -> None:
self.threshold = threshold
self.max_features = max_features
self.selector = SelectFromModel(
RandomForestClassifier(n_estimators=100, random_state=42, n_jobs=-1)
threshold=threshold
)
self.selected_features: List[str] = []
def execute(self, data: pd.DataFrame, target_col: str) -> Dict[str, Any]:
"""Execute feature selection and return structured results."""
if target_col not in data.columns:
raise ValueError(f"Target column '{target_col}' not found in data.")
X = data.drop(columns=[target_col])
y = data[target_col]
if X.shape[1] == 0:
raise ValueError("No features available for selection.")
self.selector.fit(X, y)
self.selected_features = X.columns[self.selector.get_support()].tolist()
X_selected = self.selector.transform(X)
result = {
'status': 'success'
'original_features': X.shape[1]
'selected_features': len(self.selected_features)
'feature_names': self.selected_features
'transformed_data': X_selected
'importance_scores': dict(zip(X.columns, self.selector.estimator_.feature_importances_))
}
logger.info(f"Selected {len(self.selected_features)} features from {X.shape[1]}")
return result
| Pitfall | Problem | Solution | |
Authoritative documentation links for this skill's domain. The model follows markdown links at load time to resolve external references and inline content.