Extracting Feature Importance from LightGBM Models

  • Share this:

Code introduction


This function extracts and returns the feature importance from a trained LightGBM model.


Technology Stack : LightGBM, NumPy

Code Type : Custom function

Code Difficulty : Intermediate


                
                    
def random_feature_importance(lb_model):
    """
    Extracts and returns the feature importance from a trained LightGBM model.
    """
    import lightgbm as lgb
    import numpy as np

    def get_feature_importance(model):
        # Extract feature importance from the model
        importance = model.feature_importances_
        # Normalize feature importance
        total = np.sum(importance)
        normalized_importance = importance / total
        # Return a list of tuples sorted by importance
        return sorted(zip(model.feature_name, normalized_importance), key=lambda x: x[1], reverse=True)

    # Assuming lb_model is a trained LightGBM model
    return get_feature_importance(lb_model)                
              
Tags: