Feature Importance Chart in neural network using Keras in Python

2024/11/19 19:40:54

I am using python(3.6) anaconda (64 bit) spyder (3.1.2). I already set a neural network model using keras (2.0.6) for a regression problem(one response, 10 variables). I was wondering how can I generate feature importance chart like so:

feature importance chart

def base_model():model = Sequential()model.add(Dense(200, input_dim=10, kernel_initializer='normal', activation='relu'))model.add(Dense(1, kernel_initializer='normal'))model.compile(loss='mean_squared_error', optimizer = 'adam')return modelclf = KerasRegressor(build_fn=base_model, epochs=100, batch_size=5,verbose=0)
clf.fit(X_train,Y_train)
Answer

I was recently looking for the answer to this question and found something that was useful for what I was doing and thought it would be helpful to share. I ended up using a permutation importance module from the eli5 package. It most easily works with a scikit-learn model. Luckily, Keras provides a wrapper for sequential models. As shown in the code below, using it is very straightforward.

from keras.wrappers.scikit_learn import KerasClassifier, KerasRegressor
import eli5
from eli5.sklearn import PermutationImportancedef base_model():model = Sequential()        ...return modelX = ...
y = ...my_model = KerasRegressor(build_fn=base_model, **sk_params)    
my_model.fit(X,y)perm = PermutationImportance(my_model, random_state=1).fit(X,y)
eli5.show_weights(perm, feature_names = X.columns.tolist())
https://en.xdnf.cn/q/26400.html

Related Q&A

numpy.max or max ? Which one is faster?

In python, which one is faster ? numpy.max(), numpy.min()ormax(), min()My list/array length varies from 2 to 600. Which one should I use to save some run time ?

Nested Json to pandas DataFrame with specific format

I need to format the contents of a Json file in a certain format in a pandas DataFrame so that I can run pandassql to transform the data and run it through a scoring model. file = C:\scoring_model\json…

Iterating over dictionary items(), values(), keys() in Python 3

If I understand correctly, in Python 2, iter(d.keys()) was the same as d.iterkeys(). But now, d.keys() is a view, which is in between the list and the iterator. Whats the difference between a view and …

Is there a method that tells my program to quit?

For the "q" (quit) option in my program menu, I have the following code:elif choice == "q":print()That worked all right until I put it in an infinite loop, which kept printing blank…

Hiding Axis Labels

Im trying to hide the axis labels on the first subplot at 211. Id like to label the figure, not just a subplot (reference: "Isub Event Characteristics"). How can I control font properties lik…

Why does Python preemptively hang when trying to calculate a very large number?

Ive asked this question before about killing a process that uses too much memory, and Ive got most of a solution worked out.However, there is one problem: calculating massive numbers seems to be untouc…

Django, name parameter in urlpatterns

Im following a tutorial where my urlpatterns are:urlpatterns = patterns(,url(r^passwords/$, PasswordListView.as_view(), name=passwords_api_root),url(r^passwords/(?P<id>[0-9]+)$, PasswordInstance…

The most Pythonic way of checking if a value in a dictionary is defined/has zero length

Say I have a dictionary, and I want to check if a key is mapped to a nonempty value. One way of doing this would be the len function:mydict = {"key" : "value", "emptykey"…

What does the --pre option in pip signify?

I saw on this page that pip install neo4j-doc-manager --pre was used. What does the --pre flag mean?

Tracing and Returning a Path in Depth First Search

So I have a problem that I want to use depth first search to solve, returning the first path that DFS finds. Here is my (incomplete) DFS function:start = problem.getStartState()stack = Stack()visited =…