You can download this code by clicking the button below.
This code is now available for download.
This function calculates the importance of each feature in a LightGBM model and returns a dictionary containing feature names and their importance scores.
Technology Stack : LightGBM, NumPy
Code Type : Function
Code Difficulty : Intermediate
def random_feature_importance(lgbm_model, feature_names):
"""
This function calculates the importance of each feature in a LightGBM model.
"""
import lightgbm as lgb
import numpy as np
# Get the feature importance from the model
importance = lgb_model.feature_importances_
# Normalize the importance values
normalized_importance = importance / np.sum(importance)
# Sort the features based on their importance
sorted_idx = np.argsort(normalized_importance)[::-1]
# Create a feature importance dictionary
feature_importance_dict = {feature_names[i]: normalized_importance[i] for i in sorted_idx}
return feature_importance_dict