{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Feature importances with a forest of trees\n\nThis example shows the use of a forest of trees to evaluate the importance of\nfeatures on an artificial classification task. The blue bars are the feature\nimportances of the forest, along with their inter-trees variability represented\nby the error bars.\n\nAs expected, the plot suggests that 3 features are informative, while the\nremaining are not.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# Authors: The scikit-learn developers\n# SPDX-License-Identifier: BSD-3-Clause\n\nimport matplotlib.pyplot as plt" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data generation and model fitting\nWe generate a synthetic dataset with only 3 informative features. We will\nexplicitly not shuffle the dataset to ensure that the informative features\nwill correspond to the three first columns of X. In addition, we will split\nour dataset into training and testing subsets.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.datasets import make_classification\nfrom sklearn.model_selection import train_test_split\n\nX, y = make_classification(\n n_samples=1000,\n n_features=10,\n n_informative=3,\n n_redundant=0,\n n_repeated=0,\n n_classes=2,\n random_state=0,\n shuffle=False,\n)\nX_train, X_test, y_train, y_test = train_test_split(X, y, stratify=y, random_state=42)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A random forest classifier will be fitted to compute the feature importances.\n\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "from sklearn.ensemble import RandomForestClassifier\n\nfeature_names = [f\"feature {i}\" for i in range(X.shape[1])]\nforest = RandomForestClassifier(random_state=0)\nforest.fit(X_train, y_train)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Feature importance based on mean decrease in impurity\nFeature importances are provided by the fitted attribute\n`feature_importances_` and they are computed as the mean and standard\ndeviation of accumulation of the impurity decrease within each tree.\n\n
Impurity-based feature importances can be misleading for **high\n cardinality** features (many unique values). See\n `permutation_importance` as an alternative below.