IIS_2023_1/alexandrov_dmitrii_lab_2/lab2.py

83 lines
2.2 KiB
Python

from sklearn.linear_model import LinearRegression, RandomizedLasso
from sklearn.feature_selection import RFE
from sklearn.preprocessing import MinMaxScaler
from matplotlib import pyplot as plt
import numpy as np
import random as rand
figure = plt.figure(1, figsize=(16, 9))
axis = figure.subplots(1, 4)
col = 0
y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
def rank_to_dict(ranks, names, n_features):
ranks = np.abs(ranks)
minmax = MinMaxScaler()
ranks = minmax.fit_transform(np.array(ranks).reshape(n_features, 1)).ravel()
ranks = map(lambda x: round(x, 2), ranks)
return dict(zip(names, ranks))
def createView(key, val):
global figure
global axis
global col
global y
axis[col].bar(y, list(val.values()), label=key)
axis[col].set_title(key)
col = col + 1
def start():
np.random.seed(rand.randint(0, 50))
size = 750
n_features = 14
X = np.random.uniform(0, 1, (size, n_features))
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))
lr = LinearRegression()
rl = RandomizedLasso()
rfe = RFE(estimator=LinearRegression(), n_features_to_select=1)
lr.fit(X, Y)
rl.fit(X, Y)
rfe.fit(X, Y)
names = ["x%s" % i for i in range(1, n_features + 1)]
rfe_res = rfe.ranking_
for i in range(rfe_res.size):
rfe_res[i] = 14 - rfe_res[i]
ranks = {"Linear regression": rank_to_dict(lr.coef_, names, n_features),
"Random lasso": rank_to_dict(rl.scores_, names, n_features),
"RFE": rank_to_dict(rfe_res, names, n_features)}
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)
ranks["Mean"] = mean
for key, value in ranks.items():
createView(key, value)
ranks[key] = sorted(value.items(), key=lambda y: y[1], reverse=True)
for key, value in ranks.items():
print(key)
print(value)
start()
plt.show()