autofeat

repository·main·Indexed 19 days ago

https://github.com/cod3licious/autofeat

A Python library for automatic feature engineering and selection for linear prediction models. It generates non-linear features and selects a robust subset to improve predictive power while maintaining model interpretability. It provides scikit-learn compatible interfaces via AutoFeatRegressor, AutoFeatClassifier, AutoFeatLight, and FeatureSelector.

Tokens
6.9K
Snippets
15
Records
25
Agent score
68%

What's inside autofeat

  1. Overview of Autofeat features and use cases

    main

    Autofeat is a Python library designed to improve linear model performance by automating the generation of non-linear features and selecting a robust subset of them.

    Key Features

    • Automated Feature Generation and Selection: Automatically creates and selects features to enhance linear models.
    • Improved Performance and Interpretability: Increases prediction accuracy while maintaining the transparency of linear models.
    • Seamless Integration: Fully compatible with scikit-learn pipelines.

    Use Cases

    • Supervised learning where model transparency is required.
    • Feature selection in large datasets to automate variable discovery.
    • Non-linear feature discovery to leverage complex relationships without increasing model complexity.
  2. Optimize autofeat performance and memory usage

    main

    Automated feature engineering can generate a very large feature matrix. To manage memory and computational load, use the following strategies:

    • Limit Engineering Scope: Use the feateng_cols parameter to specify only the columns you expect to be most valuable for engineering. This significantly reduces the number of generated features.
    • Restrict Transformations: Limit the transformations parameter to only those specific transformations that are relevant to your data type.
    • Subsample Training Data: Subsample the dataset used during the fit() process to limit memory requirements. Once the model is fit, you can still call transform() on your full dataset to generate only the selected features.
  3. Apply the Pi Theorem using units

    main

    If you provide a units dictionary to AutoFeatModel, the model can use the Pi Theorem to generate physically meaningful dimensionless features.

    Requirements:

    • apply_pi_theorem must be True (default).
    • units must be a dictionary mapping column names to strings compatible with pint (e.g., {'velocity': 'm/s', 'time': 's'}).
    • It is assumed that all features are of comparable magnitude. Scale your variables before passing them to AutoFeat if they differ significantly in scale (e.g., meters vs millimeters).

    Generated features from the Pi Theorem will be prefixed with PT.

    # Example of providing units
    units_config = {
        'speed': 'm/s',
        'time': 's',
        'distance': 'm'
    }
    
    model = AutoFeatModel(units=units_config, apply_pi_theorem=True)
    # The model will now attempt to generate features like distance/time (speed)
  4. How AutoFeat performs feature selection

    main

    AutoFeat's multi-step feature selection process relies on multiple rounds of L1-regularized linear models. To be effective, these models must balance speed with the ability to select reliable features (high precision and high recall).

    For Regression tasks, AutoFeat uses LassoLarsCV because it provides a good trade-off between execution speed and the quality of selected features compared to other models like ElasticNet, Lasso, or OrthogonalMatchingPursuit.

    For Classification tasks, AutoFeat uses sklearn.linear_model.LogisticRegressionCV because it is significantly faster than alternatives like svm.LinearSVC (even when using grid search).

  5. Workflow for integrating AutoFeat with scikit-learn models

    main

    To use AutoFeatClassifier effectively in a machine learning pipeline, follow these steps:

    1. Split your data into training and testing sets.
    2. Apply AutoFeat: Use afreg.fit_transform(X_train, y_train) to generate the augmented feature set for training.
    3. Transform Test Data: Use afreg.transform(X_test) to ensure the test set has the same feature structure as the training set.
    4. Train a downstream model: Use the transformed training features (X_train_tr) to train a standard scikit-learn estimator (e.g., LogisticRegression, RandomForestClassifier, or SVC) using GridSearchCV for hyperparameter optimization.
    5. Evaluate: Predict on the transformed test set (X_test_tr) using the trained downstream model.
    # 1. Generate features
    afreg = AutoFeatClassifier(feateng_steps=1)
    X_train_tr = afreg.fit_transform(X_train, y_train)
    X_test_tr = afreg.transform(X_test)
    
    # 2. Train downstream model (e.g., Logistic Regression)
    rreg = LogisticRegression(class_weight="balanced")
    param_grid = {"C": np.logspace(-4, 4, 10)}
    
    # Use GridSearchCV on the transformed features
    gsmodel = GridSearchCV(rreg, param_grid, cv=5)
    gsmodel.fit(X_train_tr, y_train)
    
    # 3. Evaluate
    print("Acc. on test data:", accuracy_score(y_test, gsmodel.predict(X_test_tr)))
  6. Generate synthetic datasets for AutoFeat benchmarking

    main

    You can use the following patterns to generate synthetic data for testing feature selection performance:

    Regression Problem

    Create a target variable as a linear combination of random features and add normally distributed noise:

    X = np.random.randn(n_train, n_feat_noise + n_feat_true)
    true_features = np.random.permutation(n_feat_noise + n_feat_true)[:n_feat_true]
    y = X[:, true_features].sum(axis=1)
    
    # Add noise
    y -= y.mean()
    y /= y.std()
    y = (1 - noise) * y + noise * np.random.randn(len(y))

    Classification Problem

    Transform a regression problem into a classification problem by thresholding the target and randomly flipping labels to introduce noise:

    y = np.array(y > y.mean(), dtype=int)
    flip_idx = np.random.permutation(len(y))[: int(np.ceil(len(y) * noise))]
    y[flip_idx] -= 1
    y = np.abs(y)
  7. Use AutoFeatLight for efficient feature engineering

    main

    The AutoFeatLight model provides a streamlined version of the feature engineering process. It is designed for faster execution by performing only minimal operations:

    • Feature Selection: Removes zero-variance and redundant features.
    • Feature Engineering: Performs simple product and ratio operations on features.
    • Scaling: Applies a power transform to make features more normally distributed.
  8. Use AutoFeatRegressor and AutoFeatClassifier

    main

    The AutoFeatRegressor and AutoFeatClassifier models follow a scikit-learn compatible interface for automated feature engineering and selection.

    Available Methods

    • fit(X, y): Fits the model parameters. Internally calls fit_transform().
    • predict(X): Predicts the target variable. Accepts either the original dataframe format or an already transformed dataframe.
    • predict_proba(X): Predicts probabilities of the target variable (Classifier only).
    • score(X, y): Calculates the goodness of fit (e.g., $R^2$ for regression or accuracy for classification).
    • fit_transform(X, y): Fits the model and returns the data extended by engineered and selected features.
    • transform(X): Extends the given data with the features engineered and selected during the fit stage. Useful for applying the same transformations to test data.

    Important Usage Notes

    • Handling NaNs: You must call fit() on data without NaN values, as the internal LassoLarsCV model does not support them. However, transform() can handle NaN values (but not np.inf).
    • Efficiency: If you plan to use the transformed data immediately after fitting, call fit_transform() directly instead of calling fit() followed by transform().
    • Overfitting Risk: Because these models can generate complex features, they may overfit to noise, especially on small datasets. It is recommended to inspect the generated features and select those that are domain-appropriate.
  9. Configure AutoFeatModel parameters

    main

    When initializing AutoFeatModel, AutoFeatRegressor, or AutoFeatClassifier, you can tune the following parameters:

    ParameterTypeDescription
    problem_typestr'regression' or 'classification'. Default is 'regression'
    categorical_colslistColumn names to be One-Hot Encoded.
    feateng_colslistSpecific columns to use for feature engineering. If None, all columns are used.
    unitsdict{col_name: unit_string} (e.g., {'x001': 'm'}). Used for Pi Theorem.
    feateng_stepsintNumber of steps in feature engineering. Default is 2
    featsel_runsintNumber of feature selection runs with random data fractions. Default is 5
    max_gbintApproximate maximum GB of memory to use. If exceeded, data is subsampled.
    transformationslist/tupleMath functions to apply. Default: ("1/", "exp", "log", "abs", "sqrt", "^2", "^3"). Additional options: "1+", "1-", "sin", "cos", "exp-", "2^"
    apply_pi_theoremboolWhether to apply the Pi Theorem using provided units. Default is True
    n_jobsintNumber of parallel jobs for feature selection. Default is 1
    verboseintVerbosity level.
    always_return_numpyboolIf True, fit_transform and transform return numpy arrays instead of DataFrames.