You can download this code by clicking the button below.
This code is now available for download.
This function calculates the feature importance of a LightGBM model and returns it as a DataFrame.
Technology Stack : pandas, numpy, LightGBM
Code Type : Function
Code Difficulty : Intermediate
def random_lightgbm_feature_importance(df, target_column, model):
"""
This function calculates the feature importance of a LightGBM model and returns it as a DataFrame.
"""
import pandas as pd
import numpy as np
# Extract feature importances from the model
feature_importances = model.feature_importances_
# Create a DataFrame with feature names and their importances
feature_importance_df = pd.DataFrame({'Feature': df.columns, 'Importance': feature_importances})
# Sort the DataFrame by importance in descending order
feature_importance_df = feature_importance_df.sort_values(by='Importance', ascending=False)
return feature_importance_df