You can download this code by clicking the button below.
This code is now available for download.
This function calculates the feature importance from a LightGBM model and returns a DataFrame with the importance scores.
Technology Stack : pandas, lightgbm
Code Type : Function
Code Difficulty : Intermediate
def random_lightgbm_feature_importance(df, target_column, model):
"""
This function calculates the feature importance from a LightGBM model and returns a DataFrame with the importance scores.
:param df: pandas DataFrame containing the features and the target variable.
:param target_column: string, the name of the target variable column.
:param model: trained LightGBM model.
:return: pandas DataFrame with feature importance scores.
"""
import pandas as pd
from lightgbm import train, LGBMRegressor
# Extract feature names from the DataFrame
feature_names = [col for col in df.columns if col != target_column]
# Get feature importance from the model
importance = model.feature_importances_
# Create a DataFrame with feature importance
feature_importance_df = pd.DataFrame({'Feature': feature_names, 'Importance': importance})
return feature_importance_df