68 lines
1.9 KiB
Python
68 lines
1.9 KiB
Python
|
from sklearn.ensemble import RandomForestRegressor
|
||
|
from sklearn.preprocessing import MinMaxScaler
|
||
|
from RandomizedLasso import RandomizedLasso
|
||
|
from sklearn.linear_model import Ridge
|
||
|
from matplotlib import pyplot as plt
|
||
|
import numpy as np
|
||
|
|
||
|
np.random.seed(0)
|
||
|
size = 1000
|
||
|
X = np.random.uniform(0, 1, (size, 14))
|
||
|
Y = (10 * np.sin(np.pi * X[:, 0] * X[:, 1]) + 20 * (X[:, 2] - .5) ** 2 + 10 * X[:, 3] + 5 * X[:, 4] ** 5 + np.random.normal(0, 1))
|
||
|
X[:, 10:] = X[:, :4] + np.random.normal(0, .025, (size, 4))
|
||
|
|
||
|
ridge = Ridge(alpha=1.0)
|
||
|
ridge.fit(X, Y)
|
||
|
|
||
|
lasso = RandomizedLasso(alpha=0.007)
|
||
|
lasso.fit(X, Y)
|
||
|
|
||
|
randForestRegression = RandomForestRegressor(max_depth=4, min_samples_leaf=1, min_impurity_decrease=0, ccp_alpha=0)
|
||
|
randForestRegression.fit(X, Y)
|
||
|
|
||
|
|
||
|
def rank_to_dict(ranks, names):
|
||
|
ranks = np.abs(ranks)
|
||
|
minmax = MinMaxScaler()
|
||
|
ranks = minmax.fit_transform(np.array(ranks).reshape(14, 1)).ravel()
|
||
|
ranks = map(lambda x: round(x, 2), ranks)
|
||
|
return dict(zip(names, ranks))
|
||
|
|
||
|
|
||
|
ranks = {'Ridge': {}, 'RandomizedLasso': {}, 'RandomForestRegressor': {}}
|
||
|
names = ["x%s" % i for i in range(1, 15)]
|
||
|
|
||
|
ranks["Ridge"] = rank_to_dict(ridge.coef_, names)
|
||
|
ranks["RandomizedLasso"] = rank_to_dict(lasso.coef_, names)
|
||
|
ranks["RandomForestRegressor"] = rank_to_dict(randForestRegression.feature_importances_, names)
|
||
|
|
||
|
mean = {}
|
||
|
|
||
|
for key, value in ranks.items():
|
||
|
for item in value.items():
|
||
|
if item[0] not in mean:
|
||
|
mean[item[0]] = 0
|
||
|
mean[item[0]] += item[1]
|
||
|
|
||
|
for key, value in mean.items():
|
||
|
res = value / len(ranks)
|
||
|
mean[key] = round(res, 2)
|
||
|
|
||
|
print('VALUES')
|
||
|
|
||
|
for r in ranks.items():
|
||
|
print(r)
|
||
|
print('MEAN')
|
||
|
print(mean)
|
||
|
|
||
|
for i, (model_name, features) in enumerate(ranks.items()):
|
||
|
subplot = plt.subplot(2, 2, i + 1)
|
||
|
subplot.set_title(model_name)
|
||
|
subplot.bar(list(features.keys()), list(features.values()))
|
||
|
|
||
|
subplot = plt.subplot(2, 2, 4)
|
||
|
subplot.set_title('Mean')
|
||
|
subplot.bar(list(mean.keys()), list(mean.values()))
|
||
|
|
||
|
plt.show()
|