/ / Comment trouver les arbres / caractéristiques clés d'une forêt aléatoire formée? - scikit-learn

Comment trouver les arbres / caractéristiques clés d'une forêt aléatoire formée? - scikit-learn

J'utilise le classifieur de forêt aléatoire Scikit-Learn et j'essaie d'extraire les arbres / fonctionnalités significatifs afin de mieux comprendre les résultats de la prédiction.

J'ai trouvé cette méthode qui semble pertinente dans la documentation (http://scikit-learn.org/dev/modules/generated/sklearn.ensemble.RandomForestClassifier.html#sklearn.ensemble.RandomForestClassifier.get_params), mais n’a pas pu trouver un exemple d’utilisation.

J'espère aussi pouvoir visualiser ces arbres si possible, tout code pertinent serait génial.

Je vous remercie!

Réponses:

6 pour la réponse № 1

Pour connaître l’importance relative des fonctionnalités, lisez le section pertinente de la documentation avec le code des exemples liés dans cette même section.

Les arbres eux-mêmes sont stockés dans le estimators_ attribut de l'instance de forêt aléatoire (uniquement après l'appel du fit méthode). Maintenant, pour extraire un "arbre de clé", il vous faudrait d’abord définir ce que c’est et ce que vous voulez en faire.

Vous pouvez classer les arbres individuels en calculant leur score sur le jeu de tests tenu, mais je ne sais pas ce qui les attend.

Voulez-vous élaguer la forêt pour la rendre plus rapide à prévoir en réduisant le nombre d'arbres sans diminuer la précision de la forêt globale?


16 pour la réponse № 2

Je pense que vous recherchez Forest.feature_importances_. Cela vous permet de voir l’importance relative de chaque entité en entrée pour votre modèle final. Voici un exemple simple.

import random
import numpy as np
from sklearn.ensemble import RandomForestClassifier


#Lets set up a training dataset.  We"ll make 100 entries, each with 19 features and
#each row classified as either 0 and 1.  We"ll control the first 3 features to artificially
#set the first 3 features of rows classified as "1" to a set value, so that we know these are the "important" features.  If we do it right, the model should point out these three as important.
#The rest of the features will just be noise.
train_data = [] ##must be all floats.
for x in range(100):
line = []
if random.random()>0.5:
line.append(1.0)
#Let"s add 3 features that we know indicate a row classified as "1".
line.append(.77)
line.append(.33)
line.append(.55)
for x in range(16):#fill in the rest with noise
line.append(random.random())
else:
#this is a "0" row, so fill it with noise.
line.append(0.0)
for x in range(19):
line.append(random.random())
train_data.append(line)
train_data = np.array(train_data)


# Create the random forest object which will include all the parameters
# for the fit.  Make sure to set compute_importances=True
Forest = RandomForestClassifier(n_estimators = 100, compute_importances=True)

# Fit the training data to the training output and create the decision
# trees.  This tells the model that the first column in our data is the classification,
# and the rest of the columns are the features.
Forest = Forest.fit(train_data[0::,1::],train_data[0::,0])

#now you can see the importance of each feature in Forest.feature_importances_
# these values will all add up to one.  Let"s call the "important" ones the ones that are above average.
important_features = []
for x,i in enumerate(Forest.feature_importances_):
if i>np.average(Forest.feature_importances_):
important_features.append(str(x))
print "Most important features:",", ".join(important_features)
#we see that the model correctly detected that the first three features are the most important, just as we expected!

0 pour la réponse № 3

Voici comment je visualise l'arbre:

Commencez par créer le modèle après avoir effectué tous les prétraitements, fractionnements, etc.:

# max number of trees = 100
from sklearn.ensemble import RandomForestClassifier
classifier = RandomForestClassifier(n_estimators = 100, criterion = "entropy", random_state = 0)
classifier.fit(X_train, y_train)

Faire des prédictions:

# Predicting the Test set results
y_pred = classifier.predict(X_test)

Ensuite, faites l'intrigue des importances. La variable dataset est le nom du cadre de données d'origine.

# get importances from RF
importances = classifier.feature_importances_

# then sort them descending
indices = np.argsort(importances)

# get the features from the original data set
features = dataset.columns[0:26]

# plot them with a horizontal bar chart
plt.figure(1)
plt.title("Feature Importances")
plt.barh(range(len(indices)), importances[indices], color="b", align="center")
plt.yticks(range(len(indices)), features[indices])
plt.xlabel("Relative Importance")

Cela donne un graphique comme ci-dessous:

entrer la description de l'image ici