from sklearn.linear_model import Lasso from sklearn.ensemble import RandomForestRegressor from sklearn.feature_selection import f_regression from sklearn.preprocessing import MinMaxScaler import numpy as np np.random.seed(0) # Генерация данных size = 500 X = np.random.uniform(0, 1, (size, 15)) 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[:, :5] + np.random.normal(0, .025, (size, 5)) # Имена признаков names = ["x%s" % i for i in range(1, 16)] # Ранги признаков ranks = {} # Функция для расчета рангов def calculate_ranks(method, X, Y): if method == "Lasso": model = Lasso(alpha=0.5) elif method == "Random Forest": model = RandomForestRegressor(n_estimators=100) elif method == "f_regression": f_scores, _ = f_regression(X, Y) return dict(zip(names, f_scores)) model.fit(X, Y) return dict(zip(names, model.coef_ if method == "Lasso" else model.feature_importances_)) # Ранг для каждого метода for method in ["Lasso", "Random Forest", "f_regression"]: ranks[method] = calculate_ranks(method, X, Y) # Нормализация рангов def create_normalized_rank_dict(ranks, names): ranks = np.abs(ranks) minmax = MinMaxScaler() ranks = minmax.fit_transform( np.array(ranks).reshape(15, 1)).ravel() ranks = map(lambda x: round(x, 2), ranks) return dict(zip(names, ranks)) # Среднее значение рангов 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] # Сортируем признаки по среднему значению рангов sorted_mean = sorted(mean.items(), key=lambda x: x[1], reverse=True) # Вывод признаков и их рангов result = {} for item in sorted_mean: result[item[0]] = item[1] print(f'{item[0]}: {item[1]}')