-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path24_feature_importance.py
234 lines (157 loc) · 6.67 KB
/
24_feature_importance.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# Feature importance refers to a class of techniques for assigning scores
# to input features to a predictive model that indicates the relative
# importance of each feature when making a prediction.
# We will create test dataset with 5 important and 5 unimportant features
# Dataset would be created both for classification as well as regression
from math import perm
from sklearn import feature_selection
from sklearn.datasets import make_classification
# Create a classification dataset
seed = 32
X, Y = make_classification(n_samples=1000, n_features=10, n_informative=5, n_redundant=5, random_state=seed)
# Create a regresion dataset
from sklearn.datasets import make_regression
X_reg, Y_reg = make_regression(n_samples=1000, n_features=10, n_informative=5, random_state=seed)
# Linear regression feature importance
# We can fit a linear regression model on the data, and then get the coefficient values for the
# input features. This assumes that the input features had the same scale before training
from sklearn.linear_model import LinearRegression
from matplotlib import pyplot as plt
model = LinearRegression()
model.fit(X_reg, Y_reg)
importance = model.coef_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Logistic Regresion feature importance
# The same process of retrieval of coefficients after the model is fit can be applied
# on Logistic Regression. This also assumes that the input features had the same scale before training
from sklearn.linear_model import LogisticRegression
model = LogisticRegression()
model.fit(X, Y)
importance = model.coef_[0]
# In case of Logistic Regression, coef_ returns a 2D array, this can be checked by print(model.coef_)
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# We will be able to see that there a negative coefficients too, which does not mean,
# that they are of less importance. A positive coefficient indicates the weight of the
# features towards 1, and negative coefficient indicates towards 0, in a problem where
# 0 and 1 are classes
# Decision Tree Feature Importance
# CART Feature Importance
# Regression
from sklearn.tree import DecisionTreeRegressor
model = DecisionTreeRegressor()
model.fit(X_reg, Y_reg)
importance = model.feature_importances_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classification
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier()
model.fit(X,Y)
importance = model.feature_importances_
for i,v in enumerate(importance):
print('Feature: %0d, Score: %.5f' % (i,v))
# plot feature importance
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Random forest feature importance
# Regression
from sklearn.ensemble import RandomForestRegressor
model = RandomForestRegressor()
model.fit(X_reg, Y_reg)
importance = model.feature_importances_
for i,v in enumerate(importance):
print("Feature: %0d, Score: %.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classfication
from sklearn.ensemble import RandomForestClassifier
model = RandomForestClassifier()
model.fit(X,Y)
importance = model.feature_importances_
for i,v in enumerate(importance):
print("Feature: %0d, Score: %.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# XGBoost feature importance
# XGBoost is a library that provides an efficient and effective implementation of
# the stochastic gradient boosting algorithm.
# Regression
from xgboost import XGBRegressor
model = XGBRegressor()
model.fit(X_reg, Y_reg)
importance = model.feature_importances_
print(importance)
for i,v in enumerate(importance):
print("Feature: %0d, Score: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classification
from xgboost import XGBClassifier
model = XGBClassifier()
model.fit(X,Y)
importance = model.feature_importances_
for i, v in enumerate(importance):
print("Feature: %0d, Score: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Permuation feature importance
# First, a model is fit on the dataset, such as a model that does not support native feature
# importance scores. Then the model is used to make predictions on a dataset, although the
# values of a feature (column) in the dataset are scrambled. This is repeated for each feature
# in the dataset. Then this whole process is repeated 3, 5, 10 or more times. The result is a
# mean importance score for each input feature (and distribution of scores given the repeats).
from sklearn.neighbors import KNeighborsRegressor
from sklearn.inspection import permutation_importance
# Regression
model = KNeighborsRegressor()
model.fit(X_reg, Y_reg)
results = permutation_importance(model, X_reg, Y_reg, scoring='neg_mean_squared_error')
importance = results.importances_mean
for i, v in enumerate(importance):
print("Feature %0d, Scoring: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Classification
from sklearn.neighbors import KNeighborsClassifier
model = KNeighborsClassifier()
model.fit(X,Y)
result = permutation_importance(model,X,Y, scoring='accuracy')
importance = result.importances_mean
for i,v in enumerate(importance):
print("Feature: %0d, Scoring: %0.5f" % (i,v))
plt.bar([x for x in range(len(importance))], importance)
plt.show()
# Feature selection with importance
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.33, random_state=seed)
model = LogisticRegression(solver='liblinear')
model.fit(X_train, Y_train)
yhat = model.predict(X_test)
accuracy = accuracy_score(Y_test, yhat)
print('Accuracy: %.2f' % (accuracy*100))
from sklearn.feature_selection import SelectFromModel
# The first parameter is the model we wish to use
# The second parameter is the maximum number of features to be chosen
feature_selection = SelectFromModel(RandomForestClassifier(n_estimators=200), max_features=5)
# Learn the relationship between input and output
feature_selection.fit(X_train, Y_train)
X_train_fs = feature_selection.transform(X_train)
X_test_fs = feature_selection.transform(X_test)
model = LogisticRegression(solver='liblinear')
model.fit(X_train_fs, Y_train)
# evaluate the model
yhat = model.predict(X_test_fs)
# evaluate predictions
accuracy = accuracy_score(Y_test, yhat)
print('Accuracy: %.2f' % (accuracy*100))