consensus-fs 0.1.1__tar.gz

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.
@@ -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,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,378 @@
1
+ # ConsensusFS
2
+
3
+ > **Tek bir feature selection metoduna güvenme — hepsini çalıştır, en iyisini seç.**
4
+
5
+ ConsensusFS, makine öğrenmesi projelerinde özellik seçimi (feature selection) için geliştirilmiş bir **ensemble / konsensüs kütüphanesidir**. SHAP, LOFO, Permutation Importance ve Korelasyon gibi farklı metodları **aynı anda paralel** olarak çalıştırır; ardından sonuçları akıllıca birleştirerek güvenilir bir **Meta-Importance skoru** üretir.
6
+
7
+ Scikit-Learn uyumludur: `fit`, `transform`, `fit_transform` ve Pipeline desteği ile gelir.
8
+
9
+ ---
10
+
11
+ ## 📋 İçindekiler
12
+
13
+ - [Neden ConsensusFS?](#neden-consensusfs)
14
+ - [Kurulum](#kurulum)
15
+ - [Hızlı Başlangıç](#hızlı-başlangıç)
16
+ - [Nasıl Çalışır?](#nasıl-çalışır)
17
+ - [API Referansı](#api-referansı)
18
+ - [Desteklenen Metodlar](#desteklenen-metodlar)
19
+ - [Aggregation Stratejileri](#aggregation-stratejileri)
20
+ - [Gelişmiş Kullanım](#gelişmiş-kullanım)
21
+ - [Sklearn Pipeline ile Kullanım](#sklearn-pipeline-ile-kullanım)
22
+ - [Görselleştirme](#görselleştirme)
23
+ - [Bağımlılıklar](#bağımlılıklar)
24
+ - [Sık Sorulan Sorular](#sık-sorulan-sorular)
25
+
26
+ ---
27
+
28
+ ## Neden ConsensusFS?
29
+
30
+ Her feature selection metodu farklı bir şeyi ölçer ve farklı zayıf noktaları vardır:
31
+
32
+ | Metod | Gördüğü Şey | Kör Noktası |
33
+ |-------|------------|------------|
34
+ | Correlation | Lineer ilişkiler | Non-lineer ilişkileri kaçırır |
35
+ | Permutation | Model performansına etkisi | Overfitting modelde yanıltıcı olabilir |
36
+ | SHAP | Her özelliğin tahmine katkısı | Model bağımlıdır |
37
+ | LOFO | CV skoru üzerindeki etkisi | Yavaştır, küçük veride gürültülüdür |
38
+
39
+ **ConsensusFS** bu metodları bir araya getirerek:
40
+ - Hiçbir metodun körü körüne güven açığına düşmez
41
+ - Birden fazla metodun hemfikir olduğu özellikleri seçer
42
+ - Bireysel metodlara göre daha **kararlı (stable)** ve **güvenilir** sonuçlar üretir
43
+
44
+ ---
45
+
46
+ ## Kurulum
47
+
48
+ ```bash
49
+ # Repoyu klonlayın ve dizine girin
50
+ git clone https://github.com/kullanici_adi/consensusfs.git
51
+ cd consensusfs
52
+
53
+ # Yerel olarak kurun
54
+ pip install .
55
+ ```
56
+
57
+ **Tüm bağımlılıkları ayrıca kurmak isterseniz:**
58
+
59
+ ```bash
60
+ pip install scikit-learn>=1.0.0 pandas>=1.0.0 numpy>=1.18.0 shap>=0.40.0 lofo-importance>=0.3.0 joblib>=1.0.0 seaborn>=0.11.0 matplotlib>=3.3.0
61
+ ```
62
+
63
+ > **Python Gereksinimi:** >= 3.8
64
+
65
+ ---
66
+
67
+ ## Hızlı Başlangıç
68
+
69
+ ```python
70
+ import pandas as pd
71
+ from sklearn.ensemble import RandomForestClassifier
72
+ from sklearn.datasets import make_classification
73
+ from consensusfs import ConsensusSelector
74
+
75
+ # Veri hazırla
76
+ X, y = make_classification(n_samples=500, n_features=20, n_informative=5, random_state=42)
77
+ X_df = pd.DataFrame(X, columns=[f"col_{i}" for i in range(20)])
78
+
79
+ # Model ve selector tanımla
80
+ model = RandomForestClassifier(n_estimators=100, random_state=42)
81
+
82
+ selector = ConsensusSelector(
83
+ estimator=model,
84
+ methods=['correlation', 'permutation', 'shap'], # kullanılacak metodlar
85
+ n_features_to_select=10, # kaç özellik seçilsin
86
+ n_jobs=-1 # tüm CPU çekirdeklerini kullan
87
+ )
88
+
89
+ # Eğit ve dönüştür
90
+ X_selected = selector.fit_transform(X_df, y)
91
+
92
+ print("Seçilen özellikler:", selector.best_features_)
93
+ print("Yeni boyut:", X_selected.shape)
94
+
95
+ # Sonuçları görselleştir
96
+ selector.plot(top_n=10)
97
+ ```
98
+
99
+ ---
100
+
101
+ ## Nasıl Çalışır?
102
+
103
+ ```
104
+ Veri (X, y)
105
+
106
+
107
+ ┌─────────────────────────────────────────────────┐
108
+ │ Paralel Hesaplama (joblib) │
109
+ │ │
110
+ │ Correlation │ Permutation │ SHAP │ LOFO │
111
+ │ (opsiyonel) │ (opsiyonel) │(opsy.) │ (opsy.) │
112
+ └──────┬───────┴──────┬──────┴───┬────┴─────┬─────┘
113
+ │ │ │ │
114
+ └──────────────┴────┬─────┘───────────┘
115
+
116
+ Aggregation (rank_mean / minmax_mean)
117
+ + Ağırlıklandırma
118
+
119
+
120
+ Meta-Skor Tablosu (importance_df_)
121
+
122
+
123
+ En İyi N Özellik (best_features_)
124
+ ```
125
+
126
+ ### Aggregation Detayı (`rank_mean`)
127
+
128
+ 1. Her metod kendi skorunu üretir (örn. SHAP değerleri, korelasyon katsayıları)
129
+ 2. Her metod için özellikler **sıralanır** (1 = en önemli, N = en önemsiz)
130
+ 3. Her özelliğin tüm sıraların **ağırlıklı ortalaması** alınır → `meta_score`
131
+ 4. En düşük `meta_score` → en iyi özellik
132
+
133
+ ---
134
+
135
+ ## API Referansı
136
+
137
+ ### `ConsensusSelector(estimator, methods, aggregation, n_features_to_select, weights, n_jobs, scoring)`
138
+
139
+ | Parametre | Tip | Varsayılan | Açıklama |
140
+ |-----------|-----|-----------|----------|
141
+ | `estimator` | sklearn estimator | **Zorunlu** | Kullanılacak ML modeli. SHAP ve Permutation için eğitilir. |
142
+ | `methods` | `list[str]` | `['correlation', 'permutation', 'shap']` | Kullanılacak özellik seçim metodlarının listesi. |
143
+ | `aggregation` | `str` | `'rank_mean'` | Skor birleştirme stratejisi. `'rank_mean'` veya `'minmax_mean'`. |
144
+ | `n_features_to_select` | `int` veya `None` | `None` | Seçilecek özellik sayısı. `None` ise tüm özellikler sıralanır. |
145
+ | `weights` | `dict` veya `None` | `None` | Her metoda verilecek ağırlık. `{'shap': 2.0, 'correlation': 0.5}` gibi. |
146
+ | `n_jobs` | `int` | `-1` | Joblib paralel iş sayısı. `-1` tüm CPU çekirdeklerini kullanır. |
147
+ | `scoring` | `str` | `'roc_auc'` | LOFO metodu için skorlama metriği. |
148
+
149
+ ---
150
+
151
+ ### Metodlar
152
+
153
+ #### `fit(X, y) → self`
154
+ Tüm feature selection hesaplamalarını yapar, `importance_df_` ve `best_features_` atributlarını doldurur.
155
+
156
+ - `X`: `pd.DataFrame` veya `np.ndarray` — girdi özellikleri
157
+ - `y`: `pd.Series` veya `np.ndarray` — hedef değişken
158
+
159
+ #### `transform(X) → pd.DataFrame veya np.ndarray`
160
+ `fit()` ile seçilmiş özellikleri içeren veri setini döndürür.
161
+
162
+ - `X`'in tipi korunur: DataFrame girerse DataFrame döner, ndarray girerse ndarray döner.
163
+
164
+ #### `fit_transform(X, y) → pd.DataFrame veya np.ndarray`
165
+ `fit(X, y)` ardından `transform(X)` çalıştırır.
166
+
167
+ #### `plot(top_n=15, title="Consensus Feature Selection Heatmap")`
168
+ En önemli `top_n` özelliği için her metodun verdiği önemi gösteren Isı Haritası çizer.
169
+
170
+ ---
171
+
172
+ ### Atributlar (fit() sonrası)
173
+
174
+ | Atribut | Tip | Açıklama |
175
+ |---------|-----|----------|
176
+ | `importance_df_` | `pd.DataFrame` | Her metodun ve meta skorun sütun olduğu, özellik sıralı tablo |
177
+ | `best_features_` | `list[str]` | Seçilen en iyi özellik isimleri (sıralanmış) |
178
+ | `feature_names_` | `list[str]` | Eğitim sırasındaki tüm özellik isimleri |
179
+
180
+ ---
181
+
182
+ ## Desteklenen Metodlar
183
+
184
+ ### `'correlation'`
185
+ Hedef değişken ile her özellik arasındaki **mutlak Pearson korelasyonu** hesaplar. Model gerektirmez, çok hızlıdır. Lineer olmayan ilişkileri kaçırabilir.
186
+
187
+ ### `'permutation'`
188
+ Scikit-learn'in `permutation_importance` fonksiyonunu kullanır. Her özelliğin değerleri karıştırıldığında model skoru ne kadar düşüyor? Düşüş fazlaysa özellik önemlidir.
189
+
190
+ ### `'shap'`
191
+ SHAP (SHapley Additive exPlanations) değerlerini hesaplar. Model tipine göre otomatik olarak doğru Explainer seçilir:
192
+ 1. Ağaç tabanlı modeller (XGBoost, LightGBM, RandomForest) → `TreeExplainer`
193
+ 2. Doğrusal modeller → `LinearExplainer`
194
+ 3. Diğer tüm modeller → `KernelExplainer` (100 örnek ile örnekleme yapılır)
195
+
196
+ ### `'lofo'`
197
+ LOFO (Leave One Feature Out) Importance: Her özellik sırası ile veri setinden çıkarıldığında cross-validation skoru ne kadar değişiyor? En yorumlayıcı ama en yavaş metoddur.
198
+
199
+ > ⚠️ LOFO büyük veri setlerinde uzun sürebilir. `scoring` parametresi ile metriği değiştirebilirsiniz.
200
+
201
+ ---
202
+
203
+ ## Aggregation Stratejileri
204
+
205
+ ### `rank_mean` (Önerilen)
206
+ Her metodun sıra bilgisi kullanılır. Ölçek farklılıklarından etkilenmez.
207
+
208
+ ```
209
+ meta_score = weighted_average(rank_per_method)
210
+ ```
211
+
212
+ - **Düşük** `meta_score` → daha iyi özellik
213
+ - Ağırlık verilirse `numpy.average()` ile uygulanır (sıralama bozulmaz)
214
+
215
+ ### `minmax_mean`
216
+ Ham skorlar 0-1 arasına normalize edilip ortalaması alınır.
217
+
218
+ ```
219
+ normalized = (score - min) / (max - min)
220
+ meta_score = weighted_average(normalized)
221
+ ```
222
+
223
+ - **Yüksek** `meta_score` → daha iyi özellik
224
+ - Metodların orijinal skor büyüklükleri önemlidir, aşırı baskın metodlar riski vardır.
225
+
226
+ ---
227
+
228
+ ## Gelişmiş Kullanım
229
+
230
+ ### Özel Ağırlıklar
231
+
232
+ ```python
233
+ # SHAP'a daha fazla güven, korelasyona daha az
234
+ custom_weights = {
235
+ 'shap': 2.0,
236
+ 'lofo': 1.5,
237
+ 'permutation': 1.0,
238
+ 'correlation': 0.5
239
+ }
240
+
241
+ selector = ConsensusSelector(
242
+ estimator=model,
243
+ methods=['correlation', 'permutation', 'shap', 'lofo'],
244
+ weights=custom_weights,
245
+ n_features_to_select=10
246
+ )
247
+ ```
248
+
249
+ ### Sadece Hızlı Metodlar (LOFO Olmadan)
250
+
251
+ ```python
252
+ # Hızlı çalışma için sadece correlation + shap
253
+ selector = ConsensusSelector(
254
+ estimator=model,
255
+ methods=['correlation', 'shap'],
256
+ aggregation='rank_mean',
257
+ n_features_to_select=15,
258
+ n_jobs=-1
259
+ )
260
+ ```
261
+
262
+ ### Tüm Özellikleri Sıralı Almak
263
+
264
+ ```python
265
+ # n_features_to_select=None ile tüm özellikler önem sırasıyla listelenir
266
+ selector = ConsensusSelector(estimator=model)
267
+ selector.fit(X, y)
268
+
269
+ print(selector.importance_df_) # Tam skor tablosu
270
+ print(selector.best_features_) # Tüm özellikler, en iyiden en kötüye
271
+ ```
272
+
273
+ ### Regresyon Problemleri için
274
+
275
+ ```python
276
+ from sklearn.ensemble import GradientBoostingRegressor
277
+
278
+ model = GradientBoostingRegressor(random_state=42)
279
+
280
+ selector = ConsensusSelector(
281
+ estimator=model,
282
+ methods=['correlation', 'permutation', 'shap'],
283
+ scoring='r2', # Regresyon için uygun metrik
284
+ n_features_to_select=8
285
+ )
286
+ selector.fit(X_train, y_train)
287
+ ```
288
+
289
+ ---
290
+
291
+ ## Sklearn Pipeline ile Kullanım
292
+
293
+ `ConsensusSelector`, Scikit-Learn Pipeline ile tam uyumludur:
294
+
295
+ ```python
296
+ from sklearn.pipeline import Pipeline
297
+ from sklearn.preprocessing import StandardScaler
298
+ from sklearn.linear_model import LogisticRegression
299
+ from consensusfs import ConsensusSelector
300
+
301
+ # Not: Pipeline içinde estimator olarak basit bir model kullanın;
302
+ # Pipeline'ın son adımında farklı bir model kullanabilirsiniz.
303
+ inner_model = RandomForestClassifier(n_estimators=50, random_state=42)
304
+
305
+ pipe = Pipeline([
306
+ ('scaler', StandardScaler()),
307
+ ('selector', ConsensusSelector(
308
+ estimator=inner_model,
309
+ methods=['correlation', 'shap'],
310
+ n_features_to_select=10
311
+ )),
312
+ ('classifier', LogisticRegression())
313
+ ])
314
+
315
+ pipe.fit(X_train, y_train)
316
+ print("Test Skoru:", pipe.score(X_test, y_test))
317
+ ```
318
+
319
+ ---
320
+
321
+ ## Görselleştirme
322
+
323
+ ```python
324
+ # fit() çağrısından sonra kullanın
325
+ selector.plot(top_n=15)
326
+
327
+ # Özel başlıkla
328
+ selector.plot(top_n=10, title="Proje X — Özellik Önem Haritası")
329
+ ```
330
+
331
+ Isı haritası, her metodun her özelliğe verdiği önemi **0-1 arasında normalize ederek** gösterir. Koyu renk = daha önemli.
332
+
333
+ ---
334
+
335
+ ## Bağımlılıklar
336
+
337
+ | Kütüphane | Minimum Sürüm | Kullanım Amacı |
338
+ |-----------|--------------|----------------|
339
+ | `scikit-learn` | ≥ 1.0.0 | BaseEstimator, permutation_importance |
340
+ | `pandas` | ≥ 1.0.0 | DataFrame işlemleri |
341
+ | `numpy` | ≥ 1.18.0 | Sayısal hesaplamalar |
342
+ | `shap` | ≥ 0.40.0 | SHAP değerleri |
343
+ | `lofo-importance` | ≥ 0.3.0 | LOFO hesaplaması |
344
+ | `joblib` | ≥ 1.0.0 | Paralel hesaplama |
345
+ | `matplotlib` | ≥ 3.3.0 | Görselleştirme |
346
+ | `seaborn` | ≥ 0.11.0 | Isı haritası |
347
+
348
+ ---
349
+
350
+ ## Sık Sorulan Sorular
351
+
352
+ **LOFO çok yavaş, ne yapmalıyım?**
353
+ `methods` listesinden `'lofo'`'yu çıkarın. Diğer üç metod yeterince güçlüdür.
354
+
355
+ **Model olarak ne kullanmalıyım?**
356
+ SHAP için ağaç tabanlı modeller (RandomForest, XGBoost, LightGBM) hem en hızlı hem en doğru sonucu verir. Ancak herhangi bir Scikit-Learn uyumlu model çalışır.
357
+
358
+ **`n_features_to_select` nasıl seçmeliyim?**
359
+ Önce `None` bırakıp `importance_df_`'e bakın; `meta_score`'un belirgin şekilde arttığı nokta iyi bir kesme noktasıdır.
360
+
361
+ **NumPy array kullanabilir miyim, DataFrame zorunlu mu?**
362
+ Her ikisi de çalışır. NumPy array verildiğinde özellik isimleri otomatik olarak `feature_0`, `feature_1`, ... şeklinde atanır.
363
+
364
+ **`weights` vermediğimde ne olur?**
365
+ Tüm metodlar eşit ağırlıkla (1.0) değerlendirilir; `rank_mean` için basit ortalama sıra hesaplanır.
366
+
367
+ **Pipeline'da `fit` edilmiş modeli tekrar eğitiyor mu?**
368
+ Evet. `ConsensusSelector.fit()` her çağrıldığında estimatoru **yeniden eğitir**. Pipeline içinde bu beklenen davranıştır.
369
+
370
+ ---
371
+
372
+ ## Lisans
373
+
374
+ MIT License — Dilediğiniz gibi kullanın, değiştirin ve dağıtın.
375
+
376
+ ---
377
+
378
+ *Geliştirici: **Ulaş Taylan Met** — umet9711@gmail.com*
@@ -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,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ consensus_fs.egg-info/PKG-INFO
6
+ consensus_fs.egg-info/SOURCES.txt
7
+ consensus_fs.egg-info/dependency_links.txt
8
+ consensus_fs.egg-info/requires.txt
9
+ consensus_fs.egg-info/top_level.txt
10
+ consensusfs/__init__.py
11
+ consensusfs/aggregation.py
12
+ consensusfs/calculators.py
13
+ consensusfs/plotting.py
14
+ consensusfs/selector.py
15
+ tests/test_selector.py
@@ -0,0 +1,8 @@
1
+ scikit-learn>=1.0.0
2
+ pandas>=1.0.0
3
+ numpy>=1.18.0
4
+ shap>=0.40.0
5
+ lofo-importance>=0.3.0
6
+ joblib>=1.0.0
7
+ seaborn>=0.11.0
8
+ matplotlib>=3.3.0
@@ -0,0 +1 @@
1
+ consensusfs
@@ -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
@@ -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()
@@ -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)
@@ -0,0 +1,3 @@
1
+ [build-system]
2
+ requires = ["setuptools>=42", "wheel"]
3
+ build-backend = "setuptools.build_meta"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ setup(
4
+ name='consensus-fs',
5
+ version='0.1.1',
6
+ description='Ensemble Feature Selection Library',
7
+ author='Ulaş Taylan Met',
8
+ author_email='umet9711@gmail.com',
9
+ packages=find_packages(),
10
+ install_requires=[
11
+ 'scikit-learn>=1.0.0',
12
+ 'pandas>=1.0.0',
13
+ 'numpy>=1.18.0',
14
+ 'shap>=0.40.0',
15
+ 'lofo-importance>=0.3.0',
16
+ 'joblib>=1.0.0',
17
+ 'seaborn>=0.11.0',
18
+ 'matplotlib>=3.3.0'
19
+ ],
20
+ python_requires='>=3.8',
21
+ classifiers=[
22
+ 'Programming Language :: Python :: 3',
23
+ 'License :: OSI Approved :: MIT License',
24
+ 'Operating System :: OS Independent',
25
+ ],
26
+ )
@@ -0,0 +1,120 @@
1
+ import sys
2
+ import os
3
+ import pandas as pd
4
+ import numpy as np
5
+ from sklearn.datasets import make_classification
6
+ from sklearn.ensemble import RandomForestClassifier
7
+ from sklearn.model_selection import train_test_split
8
+
9
+ # Proje kök dizinini sisteme ekle (consensusfs klasörünün bulunduğu yer)
10
+ BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
11
+ if BASE_DIR not in sys.path:
12
+ sys.path.insert(0, BASE_DIR)
13
+
14
+ try:
15
+ from consensusfs import ConsensusSelector
16
+ print(">>> ConsensusFS Kütüphanesi Başarıyla Yüklendi.\n")
17
+ except ImportError as e:
18
+ print(f">>> Kütüphane Yükleme Hatası: {e}")
19
+ sys.exit(1)
20
+
21
+ def run_comprehensive_test():
22
+ print("="*60)
23
+ print("CONSENSUS FS: KAPSAMLI SİSTEM TESTİ BAŞLIYOR")
24
+ print("="*60)
25
+
26
+ # 1. VERİ HAZIRLIĞI
27
+ # 20 özellikli bir veri seti (5'i anlamlı, 15'i gürültü/gereksiz)
28
+ X, y = make_classification(
29
+ n_samples=200,
30
+ n_features=20,
31
+ n_informative=5,
32
+ n_redundant=2,
33
+ random_state=42
34
+ )
35
+ feature_names = [f"Özellik_{i:02d}" for i in range(20)]
36
+ X_df = pd.DataFrame(X, columns=feature_names)
37
+ y_series = pd.Series(y)
38
+
39
+ X_train, X_test, y_train, y_test = train_test_split(X_df, y_series, test_size=0.2, random_state=42)
40
+
41
+ # 2. MODEL TANIMLAMA
42
+ model = RandomForestClassifier(n_estimators=50, random_state=42)
43
+
44
+ # 3. KÜTÜPHANE AYARLARI (Tüm Metotlar ve Ağırlıklandırma Testi)
45
+ # SHAP'a 2.0, Korelasyona 0.5 ağırlık veriyoruz.
46
+ # LOFO dahil edildiği için n_jobs=-1 ile paralel çalıştırıyoruz.
47
+ methods_to_test = ['correlation', 'permutation', 'shap', 'lofo']
48
+ custom_weights = {
49
+ 'shap': 2.0,
50
+ 'lofo': 1.5,
51
+ 'permutation': 1.0,
52
+ 'correlation': 0.5
53
+ }
54
+
55
+ selector = ConsensusSelector(
56
+ estimator=model,
57
+ methods=methods_to_test,
58
+ aggregation='rank_mean', # Sıralama tabanlı birleştirme
59
+ n_features_to_select=5, # En iyi 5 özelliği seç
60
+ weights=custom_weights, # Özel ağırlıklar
61
+ n_jobs=-1, # Tüm CPU çekirdeklerini kullan
62
+ scoring='roc_auc' # Metrik tercihi
63
+ )
64
+
65
+ # 4. FIT İŞLEMİ (Eğitim ve Hesaplama)
66
+ print(f"[*] Hesaplamalar başlatıldı: {methods_to_test}")
67
+ print("[*] Paralel işlemci çekirdekleri kullanılıyor (n_jobs=-1)...")
68
+
69
+ try:
70
+ selector.fit(X_train, y_train)
71
+ print("\n[+] Fit işlemi başarıyla tamamlandı.")
72
+ except Exception as e:
73
+ print(f"\n[!] Fit sırasında hata oluştu: {e}")
74
+ return
75
+
76
+ # 5. SONUÇLARIN ANALİZİ
77
+ print("\n" + "-"*30)
78
+ print("META-IMPORTANCE RAPORU (Top 10)")
79
+ print("-"*30)
80
+ print(selector.importance_df_.head(10))
81
+
82
+ print(f"\n[+] Seçilen En İyi 5 Özellik: {selector.best_features_}")
83
+
84
+ # 6. TRANSFORM TESTİ
85
+ print("\n[*] Veri seti dönüştürülüyor (Transform)...")
86
+ X_train_selected = selector.transform(X_train)
87
+ X_test_selected = selector.transform(X_test)
88
+
89
+ print(f"[+] Orijinal Boyut: {X_train.shape}")
90
+ print(f"[+] Yeni Boyut: {X_train_selected.shape}")
91
+
92
+ assert X_train_selected.shape[1] == 5, "Hata: Seçilen özellik sayısı yanlış!"
93
+ assert list(X_train_selected.columns) == selector.best_features_, "Hata: Sütun isimleri eşleşmiyor!"
94
+
95
+ # 7. FARKLI BİR AGGREGATION TESTİ (MinMax Mean)
96
+ print("\n[*] Min-Max Toplulaştırma Testi Yapılıyor...")
97
+ selector_minmax = ConsensusSelector(
98
+ estimator=model,
99
+ methods=['correlation', 'shap'],
100
+ aggregation='minmax_mean'
101
+ )
102
+ selector_minmax.fit(X_train, y_train)
103
+ print("[+] Min-Max Meta Skorları (İlk 3):")
104
+ print(selector_minmax.importance_df_['meta_score'].head(3))
105
+
106
+ # 8. GÖRSELLEŞTİRME TESTİ
107
+ print("\n[*] Görselleştirme Heatmap hazırlanıyor...")
108
+ # Not: Bu satır ekranında bir grafik penceresi açacaktır.
109
+ try:
110
+ selector.plot(top_n=10)
111
+ print("[+] Görselleştirme başarılı.")
112
+ except Exception as e:
113
+ print(f"[!] Görselleştirme hatası (Display kaynaklı olabilir): {e}")
114
+
115
+ print("\n" + "="*60)
116
+ print("TÜM TESTLER BAŞARIYLA TAMAMLANDI!")
117
+ print("="*60)
118
+
119
+ if __name__ == "__main__":
120
+ run_comprehensive_test()