Feature importance helps us understand which input factors affect the prediction the most. It shows what matters in the data for the model.
Feature importance in regression in ML Python
from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() model.fit(X_train, y_train) importances = model.feature_importances_
feature_importances_ is an attribute that gives importance scores for each feature after training.
This example uses a Random Forest model, which naturally provides feature importance.
from sklearn.linear_model import LinearRegression model = LinearRegression() model.fit(X_train, y_train) coefficients = model.coef_
from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor(n_estimators=100) model.fit(X_train, y_train) importances = model.feature_importances_
import matplotlib.pyplot as plt plt.bar(feature_names, importances) plt.title('Feature Importance') plt.show()
This code trains a Random Forest regressor on the Boston housing dataset and prints the importance of each feature.
from sklearn.datasets import load_boston from sklearn.ensemble import RandomForestRegressor from sklearn.model_selection import train_test_split import numpy as np # Load data boston = load_boston() X, y = boston.data, boston.target feature_names = boston.feature_names # Split data X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # Train model model = RandomForestRegressor(random_state=42) model.fit(X_train, y_train) # Get feature importance importances = model.feature_importances_ # Print feature importance for name, importance in zip(feature_names, importances): print(f"{name}: {importance:.3f}")
Feature importance values are relative and sum to 1.
Different models calculate importance differently; Random Forest uses how much each feature reduces error.
High importance means the feature strongly influences predictions.
Feature importance shows which inputs affect the model most.
Random Forest models provide easy access to feature importance.
Use feature importance to explain, simplify, or improve models.
Practice
feature importance tell us in a regression model?Solution
Step 1: Understand feature importance meaning
Feature importance measures how much each input feature affects the model's output.Step 2: Compare options to definition
Only Which input features most influence the model's predictions correctly describes this concept as the influence of input features on predictions.Final Answer:
Which input features most influence the model's predictions -> Option CQuick Check:
Feature importance = input influence [OK]
- Confusing feature importance with model accuracy
- Thinking it shows model speed or size
- Mixing it up with number of model layers
Solution
Step 1: Recall Random Forest attribute for feature importance
Random Forest regression models in scikit-learn provide feature importance via the attributefeature_importances_.Step 2: Eliminate other options
predict()makes predictions,fit()trains the model, andscore()evaluates performance, none return feature importance.Final Answer:
model.feature_importances_ -> Option DQuick Check:
Feature importance attribute = feature_importances_ [OK]
- Using predict() instead of feature_importances_
- Confusing fit() with importance retrieval
- Trying to get importance from score()
from sklearn.ensemble import RandomForestRegressor import numpy as np X = np.array([[1, 2], [3, 4], [5, 6], [7, 8]]) y = np.array([10, 20, 30, 40]) model = RandomForestRegressor(random_state=0) model.fit(X, y) print(model.feature_importances_)
Solution
Step 1: Understand the dataset and model
The features are two columns with increasing values, but the first feature has a slightly stronger linear relationship with the target.Step 2: Interpret feature importance output
Random Forest will assign higher importance to the feature with stronger influence, which is the first feature here.Final Answer:
[0.7 0.3] -> Option BQuick Check:
Feature 1 stronger -> higher importance [OK]
- Assuming equal importance without checking data
- Expecting exact 0.5 values
- Confusing feature importance with coefficients
from sklearn.ensemble import RandomForestRegressor model = RandomForestRegressor() print(model.feature_importances_)What is the problem?
Solution
Step 1: Identify cause of error
Accessingfeature_importances_before training causes an AttributeError because the model has no learned features yet.Step 2: Correct usage
Callfit()on training data before accessingfeature_importances_.Final Answer:
The model must be trained with fit() before accessing feature_importances_ -> Option AQuick Check:
Train model first, then get feature importance [OK]
- Trying to access feature_importances_ before fit()
- Thinking feature_importances_ needs separate import
- Believing it's only for classification
Solution
Step 1: Interpret low feature importance meaning
Features with near-zero importance contribute little to predictions and may add noise or complexity.Step 2: Decide action based on importance
Removing unimportant features simplifies the model and can improve performance and interpretability.Final Answer:
Remove those low-importance features and retrain the model -> Option AQuick Check:
Drop low-importance features to simplify model [OK]
- Adding more similar low-importance features
- Ignoring importance and keeping all features
- Only increasing trees without feature selection
Ready to prove it?
Pass the test and this pattern moves unknown
