Bird
Raised Fist0
ML Pythonml~10 mins

Feature importance explanation in ML Python - Interactive Code Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to import the function that calculates feature importance from a trained tree model.

ML Python
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X_train, y_train)
importance = model.[1]
Drag options to blanks, or click blank then click option'
Afit
Bpredict
Cscore
Dfeature_importances_
Attempts:
3 left
💡 Hint
Common Mistakes
Using the method 'predict' instead of the attribute for importance.
Trying to call 'fit' again instead of accessing importance.
Using 'score' which returns accuracy, not feature importance.
2fill in blank
medium

Complete the code to plot the feature importances using matplotlib.

ML Python
import matplotlib.pyplot as plt
features = ['age', 'income', 'score']
importances = model.feature_importances_
plt.bar(features, [1])
plt.show()
Drag options to blanks, or click blank then click option'
Aimportances
Brange(len(features))
Cmodel
Dfeatures
Attempts:
3 left
💡 Hint
Common Mistakes
Using feature names as bar heights instead of importance values.
Passing the model object instead of importance values.
Using range indices instead of actual importance values.
3fill in blank
hard

Fix the error in the code to get feature importance from a trained linear model.

ML Python
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X_train, y_train)
importance = model.[1]
Drag options to blanks, or click blank then click option'
Aintercept_
Bcoef_
Cpredict_proba
Dfeature_importances_
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to use feature_importances_ which is for tree models only.
Using predict_proba which is a method, not importance.
Using intercept_ which is the bias term, not feature importance.
4fill in blank
hard

Fill both blanks to create a dictionary mapping features to their importance scores, filtering only those with importance greater than 0.1.

ML Python
important_features = {feature: importance for feature, importance in zip([1], [2]) if importance > 0.1}
Drag options to blanks, or click blank then click option'
Afeatures
Bimportances
Cmodel
DX_train.columns
Attempts:
3 left
💡 Hint
Common Mistakes
Using the model object instead of feature names or importance values.
Swapping the order of features and importances in zip.
Using dataset columns without matching importance values.
5fill in blank
hard

Fill all three blanks to compute and print the top 3 features by importance from a trained RandomForest model.

ML Python
import numpy as np
indices = np.argsort(model.[1])[::-1]
top_features = [features[i] for i in indices[:[2]]]
top_importances = [model.feature_importances_[i] for i in indices[:[3]]]
for f, imp in zip(top_features, top_importances):
    print(f"Feature: {f}, Importance: {imp:.2f}")
Drag options to blanks, or click blank then click option'
Afeature_importances_
B3
Dcoef_
Attempts:
3 left
💡 Hint
Common Mistakes
Using coef_ which is not available for RandomForest.
Using different numbers for second and third blanks causing mismatch.
Not reversing the sorted indices to get descending order.

Practice

(1/5)
1. What does feature importance tell us in a machine learning model?
easy
A. The time taken to train the model
B. Which features most affect the model's predictions
C. The accuracy of the model on test data
D. The total number of features in the dataset

Solution

  1. Step 1: Understand the meaning of feature importance

    Feature importance measures how much each input feature influences the model's output predictions.
  2. Step 2: Compare options with definition

    Only Which features most affect the model's predictions correctly states that feature importance shows which features most affect predictions.
  3. Final Answer:

    Which features most affect the model's predictions -> Option B
  4. Quick Check:

    Feature importance = Most influential features [OK]
Hint: Feature importance ranks features by prediction impact [OK]
Common Mistakes:
  • Confusing feature count with importance
  • Mixing accuracy with feature importance
  • Thinking it measures training time
2. Which of the following is the correct way to get feature importance from a trained Random Forest model in Python using scikit-learn?
easy
A. model.feature_importances_
B. model.get_feature_importance()
C. model.feature_importance_
D. model.importance_features

Solution

  1. Step 1: Recall scikit-learn Random Forest attribute

    The correct attribute to access feature importance is feature_importances_ with an 's' and underscore at the end.
  2. Step 2: Check each option

    model.feature_importances_ matches the exact attribute name. Others are incorrect or do not exist.
  3. Final Answer:

    model.feature_importances_ -> Option A
  4. Quick Check:

    Random Forest uses feature_importances_ [OK]
Hint: Remember the plural 'importances' with trailing underscore [OK]
Common Mistakes:
  • Using singular 'feature_importance_'
  • Calling a non-existent method
  • Mixing attribute names
3. You have a dataset with features: Age, Income, and Number of Purchases. After training a Random Forest, the feature importances are: Age=0.1, Income=0.7, Number of Purchases=0.2. What does this tell you about your model?
easy
A. Age is the most important feature influencing predictions
B. All features are equally important
C. Number of Purchases has no effect on predictions
D. Income is the most important feature influencing predictions

Solution

  1. Step 1: Interpret feature importance values

    Higher values mean stronger influence on model predictions. Income has 0.7, which is highest.
  2. Step 2: Compare other features

    Age (0.1) and Number of Purchases (0.2) have lower importance, so less influence.
  3. Final Answer:

    Income is the most important feature influencing predictions -> Option D
  4. Quick Check:

    Highest importance = most influential feature [OK]
Hint: Highest importance value shows key feature [OK]
Common Mistakes:
  • Thinking low values mean no effect
  • Assuming equal importance despite values
  • Confusing feature names
4. Given this code snippet:
from sklearn.ensemble import RandomForestClassifier
X = [[1, 2], [3, 4], [5, 6], [7, 8]]
y = [0, 1, 0, 1]
model = RandomForestClassifier(random_state=0)
model.fit(X, y)
importances = model.feature_importances_
print(importances)

What is the expected output?
medium
A. [0.5 0.5]
B. [0.7 0.3]
C. [0.0 1.0]
D. An error because data is too small

Solution

  1. Step 1: Understand the dataset and model

    The dataset has two features with balanced classes. RandomForestClassifier will split importance roughly evenly.
  2. Step 2: Predict feature importance values

    With simple data and no strong bias, feature importance will be close to equal, around 0.5 each.
  3. Final Answer:

    [0.5 0.5] -> Option A
  4. Quick Check:

    Balanced features = equal importance [OK]
Hint: Small balanced data leads to roughly equal importances [OK]
Common Mistakes:
  • Expecting exact 0 or 1 values
  • Assuming error due to small data
  • Thinking importance sums to more than 1
5. You run this code but get an AttributeError:
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.feature_importances_

What is the likely cause?
medium
A. You need to import a different library for feature importance
B. RandomForestClassifier does not have feature_importances_ attribute
C. The model is not trained yet before accessing feature_importances_
D. The attribute name is misspelled

Solution

  1. Step 1: Check model usage

    The model is created but not trained with fit() before accessing feature_importances_.
  2. Step 2: Understand attribute availability

    Feature importance is only available after training. Accessing it before fit causes AttributeError.
  3. Final Answer:

    The model is not trained yet before accessing feature_importances_ -> Option C
  4. Quick Check:

    Train model before feature_importances_ [OK]
Hint: Always call fit() before feature_importances_ [OK]
Common Mistakes:
  • Assuming attribute doesn't exist
  • Thinking import is missing
  • Misspelling attribute name
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard