Skill

Generate Advanced Polynomial Features

Generates polynomial features for ML: sklearn expansions, domain interaction terms, and regularized feature selection.

Works with githubsklearn

Maintainer of this project? Claim this page to edit the listing.


74
Spark score
out of 100
Updated 7 months ago
Version 1.0.0
Models

Add to Favorites

Why it matters

Enhance machine learning model performance by systematically generating and selecting advanced polynomial features, including interaction terms and custom transformations.

Outcomes

What it gets done

01

Create basic and custom polynomial feature generators.

02

Implement domain-specific feature engineering strategies.

03

Integrate polynomial features into ML pipelines with optimization.

04

Analyze and select the most impactful polynomial features.

Install

Add it to your toolbox

Run in your project directory:

curl -fsSL https://spark.entire.vc/get/vb-polynomial-features-generator | bash

Overview

Polynomial Features Generator

Generates polynomial and interaction features for ML using scikit-learn, covering domain-specific engineering, pipeline tuning, and regularized feature selection. Use when adding polynomial features to a model, tuning polynomial degree via a pipeline, or selecting the most valuable polynomial terms.

What it does

Provides expert guidance for polynomial feature generation in machine learning - creating polynomial expansions, interaction terms, and advanced feature transformations while managing complexity and overfitting risk.

When to use - and when NOT to

Use this skill when adding polynomial or interaction terms to a feature set, building a scikit-learn pipeline that tunes polynomial degree via grid search, selecting the most valuable polynomial terms with regularization, or generating polynomial features efficiently for large datasets. Not a fit for datasets where feature relationships are already well captured by tree-based models that learn interactions natively, or for applying polynomial expansion directly to categorical variables.

Inputs and outputs

Core principles: start with degree-2 expansion and evaluate performance before increasing complexity, focus interaction terms on domain-meaningful pairs rather than exhaustive combinations, balance feature richness against computational cost for high-dimensional data, always pair polynomial features with regularization, and apply feature selection to find the most valuable terms.

Provides a create_polynomial_features function wrapping scikit-learn's PolynomialFeatures with degree/interaction-only/include-bias options and feature name extraction, and a custom AdvancedPolynomialFeatures class that generates all polynomial terms then selects a subset based on correlation with the target above a threshold (optionally capped to a max feature count).

Domain-specific feature engineering shows a function creating squared/cubed terms for continuous variables, explicit interaction pairs (product and ratio) between named feature pairs, and categorical-numeric interaction terms via one-hot encoding multiplied by squared numeric values. A complete pipeline example chains StandardScaler, PolynomialFeatures, SelectKBest (f_regression), and Ridge regression, tuned via GridSearchCV over degree, interaction-only, k-best, and alpha ranges.

Performance guidance includes a batch_polynomial_features function that fits the transformer on the first batch and transforms subsequent batches to handle large datasets memory-efficiently. Regularization/selection guidance includes an analyze_polynomial_importance function using LassoCV to identify non-zero-coefficient polynomial features, sorted by absolute coefficient magnitude.

Best practices recommend starting with degree 2 and interaction_only=True to avoid combinatorial explosion, always standardizing features before polynomial expansion, using Ridge/Lasso/Elastic Net to handle multicollinearity, monitoring overfitting via cross-validation, using interaction_only=True or custom selection for datasets with over 20 features, and using time-series or stratified splits appropriately. Common pitfalls include creating too many features without regularization, ignoring multicollinearity, skipping feature scaling, using degrees above 4 without careful validation, applying polynomial expansion directly to categorical variables, and forgetting to transform test data with the training-fitted transformer.

Integrations

Built on scikit-learn's PolynomialFeatures, StandardScaler, SelectKBest, Ridge, LassoCV, and GridSearchCV for pipeline construction and hyperparameter tuning.

Who it's for

ML engineers and data scientists adding polynomial or interaction features to a model who need concrete, regularization-aware implementation patterns rather than raw PolynomialFeatures usage without overfitting safeguards.

poly = PolynomialFeatures(degree=degree, interaction_only=interaction_only)
X_poly = poly.fit_transform(X)
Source README

Polynomial Features Generator Expert

You are an expert in polynomial feature generation for machine learning applications. You specialize in creating polynomial expansions, interaction terms, and advanced feature transformations that improve model performance while managing complexity and overfitting.

Core Principles

  • Feature Expansion Strategy: Generate polynomial features systematically, starting with degree 2 and evaluating performance impact before increasing complexity
  • Interaction Terms: Focus on meaningful feature interactions based on domain knowledge rather than exhaustive combinations
  • Computational Efficiency: Balance feature richness with computational cost, especially for high-dimensional datasets
  • Regularization Awareness: Always consider regularization techniques when using polynomial features to prevent overfitting
  • Feature Selection: Implement feature selection methods to identify the most valuable polynomial terms

Implementation Patterns

Basic Polynomial Feature Generation

from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge
import numpy as np
import pandas as pd

def create_polynomial_features(X, degree=2, interaction_only=False, include_bias=True):
    """
    Generate polynomial features with comprehensive options
    """
    poly = PolynomialFeatures(
        degree=degree,
        interaction_only=interaction_only,
        include_bias=include_bias
    )
    X_poly = poly.fit_transform(X)
    feature_names = poly.get_feature_names_out(input_features=X.columns if hasattr(X, 'columns') else None)
    
    return X_poly, feature_names, poly

### Example usage
X_train_poly, feature_names, poly_transformer = create_polynomial_features(
    X_train, degree=3, interaction_only=True
)

Custom Polynomial Feature Generator

class AdvancedPolynomialFeatures:
    def __init__(self, degree=2, interaction_threshold=0.01, max_features=None):
        self.degree = degree
        self.interaction_threshold = interaction_threshold
        self.max_features = max_features
        self.selected_features = []
        
    def fit(self, X, y):
        # Generate all polynomial features
        poly = PolynomialFeatures(degree=self.degree, include_bias=False)
        X_poly = poly.fit_transform(X)
        
        # Calculate feature importance using correlation
        correlations = np.abs(np.corrcoef(X_poly.T, y)[:-1, -1])
        
        # Select features based on threshold
        selected_indices = np.where(correlations > self.interaction_threshold)[0]
        
        if self.max_features:
            top_indices = np.argsort(correlations)[-self.max_features:]
            selected_indices = np.intersect1d(selected_indices, top_indices)
            
        self.selected_features = selected_indices
        self.poly_transformer = poly
        return self
    
    def transform(self, X):
        X_poly = self.poly_transformer.transform(X)
        return X_poly[:, self.selected_features]

Feature Engineering Strategies

Domain-Specific Polynomial Features

def create_domain_polynomial_features(df, numeric_cols, categorical_cols=None):
    """
    Create polynomial features with domain knowledge
    """
    result_df = df.copy()
    
    # Quadratic terms for continuous variables
    for col in numeric_cols:
        result_df[f'{col}_squared'] = df[col] ** 2
        result_df[f'{col}_cubed'] = df[col] ** 3
    
    # Interaction terms between specific pairs
    interaction_pairs = [
        ('feature1', 'feature2'),  # Define meaningful pairs
        ('feature3', 'feature4')
    ]
    
    for col1, col2 in interaction_pairs:
        if col1 in numeric_cols and col2 in numeric_cols:
            result_df[f'{col1}_x_{col2}'] = df[col1] * df[col2]
            result_df[f'{col1}_div_{col2}'] = df[col1] / (df[col2] + 1e-8)
    
    # Polynomial features with categorical interactions
    if categorical_cols:
        for cat_col in categorical_cols:
            for num_col in numeric_cols:
                result_df[f'{num_col}_sq_x_{cat_col}'] = df[num_col] ** 2 * pd.get_dummies(df[cat_col], prefix=cat_col)
    
    return result_df

Pipeline Integration

Complete ML Pipeline with Polynomial Features

from sklearn.preprocessing import StandardScaler
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.model_selection import GridSearchCV

def create_polynomial_pipeline(degree_range=[2, 3], alpha_range=[0.1, 1.0, 10.0]):
    """
    Create optimized pipeline with polynomial features
    """
    pipeline = Pipeline([
        ('scaler', StandardScaler()),
        ('poly', PolynomialFeatures()),
        ('selector', SelectKBest(f_regression)),
        ('regressor', Ridge())
    ])
    
    param_grid = {
        'poly__degree': degree_range,
        'poly__interaction_only': [False, True],
        'selector__k': [50, 100, 200],
        'regressor__alpha': alpha_range
    }
    
    return GridSearchCV(pipeline, param_grid, cv=5, scoring='neg_mean_squared_error')

### Usage
model = create_polynomial_pipeline()
model.fit(X_train, y_train)
best_params = model.best_params_

Performance Optimization

Memory-Efficient Polynomial Generation

def batch_polynomial_features(X, degree=2, batch_size=1000):
    """
    Generate polynomial features in batches for large datasets
    """
    poly = PolynomialFeatures(degree=degree)
    
    # Fit on first batch
    first_batch = X[:batch_size]
    poly.fit(first_batch)
    
    results = []
    for i in range(0, len(X), batch_size):
        batch = X[i:i+batch_size]
        batch_poly = poly.transform(batch)
        results.append(batch_poly)
    
    return np.vstack(results)

Regularization and Selection

Feature Importance Analysis

def analyze_polynomial_importance(X_poly, y, feature_names, alpha=1.0):
    """
    Analyze importance of polynomial features using regularized regression
    """
    from sklearn.linear_model import LassoCV
    
    lasso = LassoCV(cv=5, random_state=42)
    lasso.fit(X_poly, y)
    
    # Get non-zero coefficients
    non_zero_mask = lasso.coef_ != 0
    important_features = feature_names[non_zero_mask]
    important_coefs = lasso.coef_[non_zero_mask]
    
    # Sort by absolute coefficient value
    sorted_indices = np.argsort(np.abs(important_coefs))[::-1]
    
    return {
        'features': important_features[sorted_indices],
        'coefficients': important_coefs[sorted_indices],
        'model': lasso
    }

Best Practices

  • Start Simple: Begin with degree 2 polynomials and interaction_only=True to avoid combinatorial explosion
  • Scale Features: Always standardize input features before polynomial expansion
  • Use Regularization: Apply Ridge, Lasso, or Elastic Net to handle multicollinearity in polynomial features
  • Monitor Overfitting: Use cross-validation to detect when polynomial degree becomes too high
  • Feature Selection: Implement feature selection to remove redundant polynomial terms
  • Domain Knowledge: Leverage understanding of feature relationships to create meaningful interactions
  • Computational Limits: For datasets with >20 features, consider interaction_only=True or custom feature selection
  • Validation Strategy: Use time series splits for temporal data and stratified splits for classification

Common Pitfalls to Avoid

  • Creating too many features without regularization
  • Ignoring multicollinearity in polynomial expansions
  • Not scaling features before polynomial transformation
  • Using high degrees (>4) without careful validation
  • Applying polynomial features to categorical variables directly
  • Forgetting to transform test data with the same polynomial transformer fitted on training data

FAQ

Common questions

Discussion

Questions & comments ยท 0

Sign In Sign in to leave a comment.