consensus-fs 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- consensus_fs-0.1.1.dist-info/METADATA +26 -0
- consensus_fs-0.1.1.dist-info/RECORD +10 -0
- consensus_fs-0.1.1.dist-info/WHEEL +5 -0
- consensus_fs-0.1.1.dist-info/licenses/LICENSE +7 -0
- consensus_fs-0.1.1.dist-info/top_level.txt +1 -0
- consensusfs/__init__.py +1 -0
- consensusfs/aggregation.py +42 -0
- consensusfs/calculators.py +71 -0
- consensusfs/plotting.py +28 -0
- consensusfs/selector.py +105 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: consensus-fs
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Ensemble Feature Selection Library
|
|
5
|
+
Author: Ulaş Taylan Met
|
|
6
|
+
Author-email: umet9711@gmail.com
|
|
7
|
+
Classifier: Programming Language :: Python :: 3
|
|
8
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
9
|
+
Classifier: Operating System :: OS Independent
|
|
10
|
+
Requires-Python: >=3.8
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: scikit-learn>=1.0.0
|
|
13
|
+
Requires-Dist: pandas>=1.0.0
|
|
14
|
+
Requires-Dist: numpy>=1.18.0
|
|
15
|
+
Requires-Dist: shap>=0.40.0
|
|
16
|
+
Requires-Dist: lofo-importance>=0.3.0
|
|
17
|
+
Requires-Dist: joblib>=1.0.0
|
|
18
|
+
Requires-Dist: seaborn>=0.11.0
|
|
19
|
+
Requires-Dist: matplotlib>=3.3.0
|
|
20
|
+
Dynamic: author
|
|
21
|
+
Dynamic: author-email
|
|
22
|
+
Dynamic: classifier
|
|
23
|
+
Dynamic: license-file
|
|
24
|
+
Dynamic: requires-dist
|
|
25
|
+
Dynamic: requires-python
|
|
26
|
+
Dynamic: summary
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
consensus_fs-0.1.1.dist-info/licenses/LICENSE,sha256=k4bUnpzMBYBEmyhece9y1ALZG8DC41s4OgEGUx7q_FU,1059
|
|
2
|
+
consensusfs/__init__.py,sha256=_lQWcMFbQo8zbpuRtRDsaBFT068unHIiYOntdIgauIQ,39
|
|
3
|
+
consensusfs/aggregation.py,sha256=qXJ1NTqf-14LnRA4v0Ht5MFL2N9F9XNKSxMwDZgOJgo,1956
|
|
4
|
+
consensusfs/calculators.py,sha256=uTMq1-KCUjT4wCvG2xyhsVrGguaNarHrt8LVPZgwMiw,3177
|
|
5
|
+
consensusfs/plotting.py,sha256=KsVTg6Sya1Jc1Ga2cMPup9BHPktAHa1J57RAsfSo1d0,1184
|
|
6
|
+
consensusfs/selector.py,sha256=9KzOwIKKq8ANOj7GsT7QpKBObTGicp_uyOF7GZ5cl6M,4973
|
|
7
|
+
consensus_fs-0.1.1.dist-info/METADATA,sha256=hgzQcakGdt_wPB83XKylAOm8vOSMxDgapS6IYKZ_w7E,746
|
|
8
|
+
consensus_fs-0.1.1.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
|
|
9
|
+
consensus_fs-0.1.1.dist-info/top_level.txt,sha256=Uu5ZIetxqJDxO_eFVWZyW7yTyR5m9pGmF2C7qsfNx6c,12
|
|
10
|
+
consensus_fs-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Copyright (c) 2026 Ulaş Taylan Met
|
|
2
|
+
|
|
3
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
4
|
+
|
|
5
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
6
|
+
|
|
7
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
consensusfs
|
consensusfs/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from .selector import ConsensusSelector
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
def aggregate_scores(results_dict, feature_names, method='rank_mean', weights=None):
|
|
5
|
+
"""
|
|
6
|
+
Farklı algoritmalardan gelen skorları birleştirir.
|
|
7
|
+
Dönen DataFrame EN İYİ özellikten EN KÖTÜ özelliğe doğru sıralanmış olur.
|
|
8
|
+
"""
|
|
9
|
+
# NaN / Inf değerlere karşı koruma (#9)
|
|
10
|
+
df = pd.DataFrame(results_dict, index=feature_names)
|
|
11
|
+
df = df.fillna(0).replace([np.inf, -np.inf], 0)
|
|
12
|
+
|
|
13
|
+
if method == 'rank_mean':
|
|
14
|
+
# Her algoritma için en yüksek skoru alan özelliği 1. sıraya koy (ascending=False)
|
|
15
|
+
rank_df = df.rank(ascending=False, method='min')
|
|
16
|
+
|
|
17
|
+
# Ağırlıklandırma — np.average ile uygun ölçek korunarak uygulanır (#8)
|
|
18
|
+
if weights:
|
|
19
|
+
weight_values = [weights.get(col, 1.0) for col in rank_df.columns]
|
|
20
|
+
df['meta_score'] = np.average(rank_df.values, axis=1, weights=weight_values)
|
|
21
|
+
else:
|
|
22
|
+
df['meta_score'] = rank_df.mean(axis=1)
|
|
23
|
+
|
|
24
|
+
# En düşük puana (en iyi sıraya) göre küçükten büyüğe sırala
|
|
25
|
+
return df.sort_values('meta_score', ascending=True)
|
|
26
|
+
|
|
27
|
+
elif method == 'minmax_mean':
|
|
28
|
+
# (x - min) / (max - min) formülü ile tüm değerleri 0-1 arasına çek
|
|
29
|
+
minmax_df = (df - df.min()) / (df.max() - df.min() + 1e-9)
|
|
30
|
+
|
|
31
|
+
# Ağırlıklandırma — np.average ile uygun ölçek korunarak uygulanır (#8)
|
|
32
|
+
if weights:
|
|
33
|
+
weight_values = [weights.get(col, 1.0) for col in minmax_df.columns]
|
|
34
|
+
df['meta_score'] = np.average(minmax_df.values, axis=1, weights=weight_values)
|
|
35
|
+
else:
|
|
36
|
+
df['meta_score'] = minmax_df.mean(axis=1)
|
|
37
|
+
|
|
38
|
+
# En yüksek puana göre büyükten küçüğe sırala
|
|
39
|
+
return df.sort_values('meta_score', ascending=False)
|
|
40
|
+
|
|
41
|
+
else:
|
|
42
|
+
raise ValueError("Desteklenmeyen birleştirme yöntemi. Lütfen 'rank_mean' veya 'minmax_mean' kullanın.")
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
import shap
|
|
4
|
+
import uuid
|
|
5
|
+
import warnings
|
|
6
|
+
from sklearn.inspection import permutation_importance
|
|
7
|
+
from lofo import Dataset, LOFOImportance
|
|
8
|
+
|
|
9
|
+
def calc_correlation(X, y, **kwargs):
|
|
10
|
+
"""Hedef değişken ile özellikler arasındaki mutlak Pearson korelasyonunu hesaplar."""
|
|
11
|
+
corr = X.apply(lambda col: col.corr(y)).abs()
|
|
12
|
+
corr = corr.fillna(0)
|
|
13
|
+
return corr.values
|
|
14
|
+
|
|
15
|
+
def calc_permutation(estimator, X, y, **kwargs):
|
|
16
|
+
"""Scikit-Learn tabanlı Permutation Importance hesaplar."""
|
|
17
|
+
# joblib çakışmalarını önlemek için n_jobs=1 kullanıyoruz
|
|
18
|
+
result = permutation_importance(estimator, X, y, n_repeats=5, random_state=42, n_jobs=1)
|
|
19
|
+
return result.importances_mean
|
|
20
|
+
|
|
21
|
+
def calc_shap(estimator, X, y, **kwargs):
|
|
22
|
+
"""SHAP değerlerini hesaplar. Modeline göre otomatik Explainer seçer."""
|
|
23
|
+
|
|
24
|
+
with warnings.catch_warnings():
|
|
25
|
+
warnings.simplefilter("ignore") # Sadece bu blok için SHAP uyarılarını gizle
|
|
26
|
+
|
|
27
|
+
try:
|
|
28
|
+
# Ağaç tabanlı modeller için (XGBoost, RandomForest, LightGBM vb.)
|
|
29
|
+
explainer = shap.TreeExplainer(estimator)
|
|
30
|
+
shap_values = explainer.shap_values(X)
|
|
31
|
+
except Exception:
|
|
32
|
+
try:
|
|
33
|
+
# Doğrusal modeller için
|
|
34
|
+
explainer = shap.LinearExplainer(estimator, X)
|
|
35
|
+
shap_values = explainer.shap_values(X)
|
|
36
|
+
except Exception:
|
|
37
|
+
# Diğer tüm modeller için (KernelExplainer yavaş olduğu için sample alıyoruz)
|
|
38
|
+
sample_X = shap.sample(X, 100) if len(X) > 100 else X
|
|
39
|
+
explainer = shap.KernelExplainer(estimator.predict, sample_X)
|
|
40
|
+
shap_values = explainer.shap_values(X)
|
|
41
|
+
|
|
42
|
+
# Eğer çok sınıflı sınıflandırma (multi-class) ise shap_values bir liste döner
|
|
43
|
+
if isinstance(shap_values, list):
|
|
44
|
+
# Tüm sınıfların ortalama mutlak etkisini al
|
|
45
|
+
mean_abs_shap = np.mean([np.abs(sv).mean(axis=0) for sv in shap_values], axis=0)
|
|
46
|
+
else:
|
|
47
|
+
# Tekil çıktı (regresyon veya binary)
|
|
48
|
+
if len(shap_values.shape) == 3: # Yeni SHAP versiyonları için
|
|
49
|
+
mean_abs_shap = np.abs(shap_values).mean(axis=(0, 2))
|
|
50
|
+
else:
|
|
51
|
+
mean_abs_shap = np.abs(shap_values).mean(axis=0)
|
|
52
|
+
|
|
53
|
+
return mean_abs_shap
|
|
54
|
+
|
|
55
|
+
def calc_lofo(estimator, X, y, feature_names, scoring="roc_auc", **kwargs):
|
|
56
|
+
"""LOFO (Leave One Feature Out) Importance hesaplar."""
|
|
57
|
+
df = X.copy()
|
|
58
|
+
# UUID ile benzersiz geçici sütun adı oluştur (X'teki sütunlarla çakışmayı önler)
|
|
59
|
+
target_name = f'__lofo_target_{uuid.uuid4().hex}__'
|
|
60
|
+
df[target_name] = y.values
|
|
61
|
+
|
|
62
|
+
dataset = Dataset(df=df, target=target_name, features=feature_names)
|
|
63
|
+
|
|
64
|
+
# LOFO hesaplama (n_jobs=1 nested paralel çakışmasını önler)
|
|
65
|
+
lofo_imp = LOFOImportance(dataset, model=estimator, scoring=scoring, cv=3, n_jobs=1)
|
|
66
|
+
importance_df = lofo_imp.get_importance()
|
|
67
|
+
|
|
68
|
+
# Skorları orijinal özellik sırasına göre eşleştir ve array olarak dön
|
|
69
|
+
importance_df = importance_df.set_index('feature')
|
|
70
|
+
scores = importance_df.loc[feature_names, 'importance_mean'].values
|
|
71
|
+
return scores
|
consensusfs/plotting.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import matplotlib.pyplot as plt
|
|
2
|
+
import seaborn as sns
|
|
3
|
+
|
|
4
|
+
def plot_consensus_heatmap(importance_df, top_n=15, title="Consensus Feature Selection Heatmap"):
|
|
5
|
+
"""
|
|
6
|
+
Farklı metriklerin özelliklere verdiği önem derecelerini Isı Haritası olarak çizer.
|
|
7
|
+
"""
|
|
8
|
+
# İstenen sayıda en iyi özelliği seç
|
|
9
|
+
plot_df = importance_df.head(top_n).copy()
|
|
10
|
+
|
|
11
|
+
# Sadece algoritma skorlarını görselleştir (meta_score sütununu çıkar)
|
|
12
|
+
if 'meta_score' in plot_df.columns:
|
|
13
|
+
plot_df = plot_df.drop(columns=['meta_score'])
|
|
14
|
+
|
|
15
|
+
# Her sütunu (algoritmayı) kendi içinde 0-1 arasına sıkıştır ki renkler düzgün görünsün
|
|
16
|
+
plot_df_scaled = (plot_df - plot_df.min()) / (plot_df.max() - plot_df.min() + 1e-9)
|
|
17
|
+
|
|
18
|
+
plt.figure(figsize=(10, max(6, top_n * 0.4))) # Özellik sayısına göre dinamik yükseklik
|
|
19
|
+
ax = sns.heatmap(plot_df_scaled, annot=False, cmap='viridis', linewidths=.5)
|
|
20
|
+
|
|
21
|
+
plt.title(title, fontsize=14, pad=20)
|
|
22
|
+
plt.ylabel("Özellikler (En İyiden En Kötüye)", fontsize=12)
|
|
23
|
+
plt.xlabel("Metrikler", fontsize=12)
|
|
24
|
+
|
|
25
|
+
# Eksen etiketlerini döndür
|
|
26
|
+
plt.xticks(rotation=45)
|
|
27
|
+
plt.tight_layout()
|
|
28
|
+
plt.show()
|
consensusfs/selector.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
from sklearn.base import BaseEstimator, TransformerMixin
|
|
4
|
+
from sklearn.utils.validation import check_is_fitted
|
|
5
|
+
from joblib import Parallel, delayed
|
|
6
|
+
|
|
7
|
+
# Kendi modüllerimizi içe aktarıyoruz
|
|
8
|
+
from consensusfs.calculators import calc_correlation, calc_permutation, calc_shap, calc_lofo
|
|
9
|
+
from consensusfs.aggregation import aggregate_scores
|
|
10
|
+
from consensusfs.plotting import plot_consensus_heatmap
|
|
11
|
+
|
|
12
|
+
class ConsensusSelector(BaseEstimator, TransformerMixin):
|
|
13
|
+
"""
|
|
14
|
+
Consensus Feature Selection Kütüphanesi Ana Sınıfı.
|
|
15
|
+
Scikit-Learn uyumlu (fit, transform) çalışır.
|
|
16
|
+
"""
|
|
17
|
+
def __init__(self, estimator, methods=None, aggregation='rank_mean',
|
|
18
|
+
n_features_to_select=None, weights=None, n_jobs=-1, scoring="roc_auc"):
|
|
19
|
+
self.estimator = estimator
|
|
20
|
+
# Varsayılan metodlar (LOFO yavaş olduğu için varsayılanlara eklemedik, istenirse yazılır)
|
|
21
|
+
self.methods = methods if methods is not None else['correlation', 'permutation', 'shap']
|
|
22
|
+
self.aggregation = aggregation
|
|
23
|
+
self.n_features_to_select = n_features_to_select
|
|
24
|
+
self.weights = weights
|
|
25
|
+
self.n_jobs = n_jobs
|
|
26
|
+
self.scoring = scoring
|
|
27
|
+
|
|
28
|
+
def fit(self, X, y):
|
|
29
|
+
"""Özellik önemlerini hesaplar ve meta skor üretir."""
|
|
30
|
+
# 1. Veri Doğrulama ve DataFrame formatına dönüştürme
|
|
31
|
+
if not isinstance(X, pd.DataFrame):
|
|
32
|
+
X = pd.DataFrame(X, columns=[f"feature_{i}" for i in range(X.shape[1])])
|
|
33
|
+
if not isinstance(y, (pd.Series, pd.DataFrame)):
|
|
34
|
+
y = pd.Series(y, name='target')
|
|
35
|
+
|
|
36
|
+
self.feature_names_ = X.columns.tolist()
|
|
37
|
+
|
|
38
|
+
# 2. Modeli eğit (SHAP ve Permutation için eğitilmiş model şarttır)
|
|
39
|
+
self.estimator.fit(X, y)
|
|
40
|
+
|
|
41
|
+
# 3. Hesaplanacak görevleri belirle ve Paralel Çalıştır (standart generator pattern)
|
|
42
|
+
method_names = []
|
|
43
|
+
delayed_tasks = []
|
|
44
|
+
for method in self.methods:
|
|
45
|
+
if method == 'correlation':
|
|
46
|
+
method_names.append(method)
|
|
47
|
+
delayed_tasks.append(delayed(calc_correlation)(X, y))
|
|
48
|
+
elif method == 'permutation':
|
|
49
|
+
method_names.append(method)
|
|
50
|
+
delayed_tasks.append(delayed(calc_permutation)(self.estimator, X, y))
|
|
51
|
+
elif method == 'shap':
|
|
52
|
+
method_names.append(method)
|
|
53
|
+
delayed_tasks.append(delayed(calc_shap)(self.estimator, X, y))
|
|
54
|
+
elif method == 'lofo':
|
|
55
|
+
method_names.append(method)
|
|
56
|
+
delayed_tasks.append(delayed(calc_lofo)(self.estimator, X, y, self.feature_names_, scoring=self.scoring))
|
|
57
|
+
else:
|
|
58
|
+
raise ValueError(f"Geçersiz metod: {method}. Desteklenenler: correlation, permutation, shap, lofo")
|
|
59
|
+
|
|
60
|
+
# 4. Paralel Hesaplama (Joblib) — generator pattern ile doğru kullanım
|
|
61
|
+
results_list = Parallel(n_jobs=self.n_jobs)(t for t in delayed_tasks)
|
|
62
|
+
|
|
63
|
+
# Sonuçları sözlüğe çevir
|
|
64
|
+
results_dict = dict(zip(method_names, results_list))
|
|
65
|
+
|
|
66
|
+
# 5. Skorları Toplulaştırma (Aggregation)
|
|
67
|
+
self.importance_df_ = aggregate_scores(
|
|
68
|
+
results_dict=results_dict,
|
|
69
|
+
feature_names=self.feature_names_,
|
|
70
|
+
method=self.aggregation,
|
|
71
|
+
weights=self.weights
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
# 6. Seçilecek en iyi özelliklerin listesini kaydet
|
|
75
|
+
n_select = self.n_features_to_select if self.n_features_to_select else len(self.feature_names_)
|
|
76
|
+
self.best_features_ = self.importance_df_.head(n_select).index.tolist()
|
|
77
|
+
|
|
78
|
+
# Estimator'ın fit edildiğini işaretlemek için sklearn standartı
|
|
79
|
+
self.is_fitted_ = True
|
|
80
|
+
return self
|
|
81
|
+
|
|
82
|
+
def transform(self, X):
|
|
83
|
+
"""Sadece en iyi özellikleri içeren veri setini filtreler ve döndürür."""
|
|
84
|
+
check_is_fitted(self, 'is_fitted_')
|
|
85
|
+
|
|
86
|
+
if isinstance(X, pd.DataFrame):
|
|
87
|
+
# Eğer DataFrame verildiyse sütun isimlerinden filtrele
|
|
88
|
+
missing_cols = set(self.best_features_) - set(X.columns)
|
|
89
|
+
if missing_cols:
|
|
90
|
+
raise ValueError(f"Transform işlemindeki veride eksik sütunlar var: {missing_cols}")
|
|
91
|
+
return X[self.best_features_]
|
|
92
|
+
else:
|
|
93
|
+
# NumPy array ise, eğitimdeki sütun indekslerini bul ve filtrele
|
|
94
|
+
indices =[self.feature_names_.index(f) for f in self.best_features_]
|
|
95
|
+
return X[:, indices]
|
|
96
|
+
|
|
97
|
+
def fit_transform(self, X, y=None, **fit_params):
|
|
98
|
+
"""Önce fit() sonra transform() çalıştırır."""
|
|
99
|
+
return self.fit(X, y).transform(X)
|
|
100
|
+
|
|
101
|
+
def plot(self, top_n=15, title="Consensus Feature Selection Heatmap"):
|
|
102
|
+
"""Sonuçları ısı haritası olarak gösterir."""
|
|
103
|
+
check_is_fitted(self, 'is_fitted_')
|
|
104
|
+
actual_top_n = min(top_n, len(self.feature_names_))
|
|
105
|
+
plot_consensus_heatmap(self.importance_df_, top_n=actual_top_n, title=title)
|