fbtseg 0.2.0__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.
fbtseg-0.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Roberto Angelo Fernandes Santos
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
fbtseg-0.2.0/PKG-INFO ADDED
@@ -0,0 +1,216 @@
1
+ Metadata-Version: 2.4
2
+ Name: fbtseg
3
+ Version: 0.2.0
4
+ Summary: Find Best Tree Segmentation — estimador de segmentação binária fiel ao Capítulo 4 da tese (Santos, UFPE 2010)
5
+ Author-email: Roberto Angelo Fernandes Santos <rafss@hotmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/RobertoASantos/FBT-Segmentation
8
+ Project-URL: Source, https://github.com/RobertoASantos/FBT-Segmentation
9
+ Keywords: machine-learning,segmentation,model-tree,binary-classification,risk-modeling,credit-scoring,fbtseg,riskseg
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Intended Audience :: Financial and Insurance Industry
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3.10
15
+ Classifier: Programming Language :: Python :: 3.11
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
19
+ Requires-Python: >=3.10
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ Requires-Dist: numpy
23
+ Requires-Dist: pandas
24
+ Requires-Dist: scipy
25
+ Requires-Dist: scikit-learn
26
+ Requires-Dist: requests
27
+ Provides-Extra: test
28
+ Requires-Dist: pytest; extra == "test"
29
+ Dynamic: license-file
30
+
31
+ # fbtseg
32
+
33
+ [![PyPI version](https://img.shields.io/pypi/v/fbtseg.svg)](https://pypi.org/project/fbtseg/)
34
+ [![Python](https://img.shields.io/pypi/pyversions/fbtseg.svg)](https://pypi.org/project/fbtseg/)
35
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
36
+
37
+ Implementação em Python do método **FBTSeg** (*Find Best Tree
38
+ Segmentation*, originalmente nomeado RISKSEG) proposto na tese de
39
+ Roberto Angelo Fernandes Santos (UFPE, 2010) e nos artigos
40
+ [ICAI 2012](docs/reference/ICAI2012-rafs-proceed.pdf) e
41
+ [ICTAI 2012](docs/reference/ICTAI2012-Submitted-140-FBTSeg.pdf).
42
+ Estimador sklearn-compatível, focado em alvo binário e reprodução fiel
43
+ dos resultados publicados.
44
+
45
+ ## Instalação
46
+
47
+ ```bash
48
+ pip install fbtseg
49
+ ```
50
+
51
+ ou em modo desenvolvimento:
52
+
53
+ ```bash
54
+ pip install -e .[test]
55
+ ```
56
+
57
+ ## Uso rápido
58
+
59
+ ```python
60
+ from fbtseg import FBTSeg, article_uci_preset
61
+
62
+ model = article_uci_preset(categorical_features=("workclass", "education"))
63
+ model.fit(X_train, y_train)
64
+ proba = model.predict_proba(X_test)[:, 1]
65
+ print(model.plot_model_tree())
66
+ summary = model.get_summary()
67
+ ```
68
+
69
+ Custom:
70
+
71
+ ```python
72
+ from fbtseg import FBTSeg
73
+
74
+ model = FBTSeg(
75
+ max_depth=3,
76
+ min_samples_leaf=0.05,
77
+ metric="error",
78
+ top_k_variables=1, # rQtdeVarTeste
79
+ n_numeric_bins=4, # rQtdeDivisoes
80
+ grouping_features=("education",), # rUsaBlocos
81
+ max_group_size=2, # rQtdeBlocos
82
+ combiner_method="stacking", # ou 'marginal_odds'
83
+ prediction_mode="leaf", # 'leaf' | 'pair_combiner' | 'cascade' | 'global_stacking'
84
+ drop_split_feature_in_children=True,
85
+ )
86
+ model.fit(X_train, y_train)
87
+ ```
88
+
89
+ ## Como funciona
90
+
91
+ Em cada nó terminal o método:
92
+
93
+ 1. Faz **screening fatorial** — uma regressão por variável candidata,
94
+ incluindo dummies da variável, efeitos principais e interações.
95
+ 2. Para a(s) melhor(es) variável(eis), testa **segmentações binárias**
96
+ (categoria-vs-complemento ou grupo de categorias).
97
+ 3. Treina **especialistas** para cada segmento e os combina por
98
+ `Stacking` ou `Marginal Odds`.
99
+ 4. **Aceita a divisão** se ela melhora a métrica D em validação interna
100
+ (com tolerância configurável de ganho mínimo / perda máxima).
101
+ 5. Recorre nos filhos até atingir profundidade máxima ou esgotar
102
+ candidatos.
103
+
104
+ A predição é vetorizada por folha (1 chamada a `predict_proba` por
105
+ folha, não 1 por linha) — 50× a 3000× mais rápida que implementações
106
+ ingênuas.
107
+
108
+ ## CLI
109
+
110
+ ```bash
111
+ # Treinar e salvar
112
+ fbtseg fit --dataset chess --preset article_uci --output-dir runs/chess
113
+
114
+ # CSV próprio
115
+ fbtseg fit --csv data.csv --target y --preset thesis \
116
+ --categorical cat_col_1 cat_col_2
117
+
118
+ # Predição com modelo salvo
119
+ fbtseg predict --model runs/chess/model.pkl --csv new_data.csv --output preds.csv
120
+ ```
121
+
122
+ ## Reprodução do paper ICAI 2012
123
+
124
+ ```bash
125
+ # Tabela 1 do paper — Linear/Logistic/MLP × bases UCI
126
+ python scripts/run_paper_table_replication.py --datasets chess magic spambase german \
127
+ --n-splits 3 --output-dir artifacts/paper_table
128
+
129
+ # Datasets sintéticos do ICTAI 2012
130
+ python scripts/validate_ictai_synthetic.py --datasets 1 2 3 4 \
131
+ --sizes 1000 3000 5000 --n-replications 10
132
+ ```
133
+
134
+ ### Destaques de fidelidade
135
+
136
+ | Dataset | Base | Paper Simple | Paper FBTSeg | fbtseg Simple | fbtseg |
137
+ |---|---|---:|---:|---:|---:|
138
+ | Chess | Logistic | 2.60% | 1.02% | 2.41% | **1.41%** |
139
+ | Magic | Logistic | 20.98% | 18.69% | 20.96% | **16.07%** |
140
+ | Magic | Linear | 32.03% | 16.06% | 21.61% | **16.93%** |
141
+ | Spambase | Linear | 14.89% | 13.51% | 11.15% | **10.45%** |
142
+
143
+ Detalhes em [docs/paper_table_replicated.md](docs/paper_table_replicated.md).
144
+
145
+ ## Estrutura do repositório
146
+
147
+ ```
148
+ fbtseg/ # pacote (estimator, views, tree, combiners, metrics, base_learners, datasets, CLI)
149
+ tests/ # testes (33 cobrindo fit, predict, presets, base learners, métricas)
150
+ scripts/ # scripts de reprodução dos experimentos
151
+ docs/ # documentação + reference (tese + 2 PDFs)
152
+ artifacts/ # resultados de execuções
153
+ trash/v1/ # implementação anterior (V1), preservada para auditoria histórica
154
+ ```
155
+
156
+ ## Documentação
157
+
158
+ - [docs/fbtseg.md](docs/fbtseg.md): API completa + mapeamento parâmetros tese ↔ código.
159
+ - [docs/paper_table_replicated.md](docs/paper_table_replicated.md): replicação da Tabela 1 do ICAI 2012.
160
+ - [docs/benchmark_final.md](docs/benchmark_final.md): benchmark fbtseg vs LR.
161
+ - [docs/examples/quickstart.py](docs/examples/quickstart.py): notebook linear executável.
162
+ - [CHANGELOG.md](CHANGELOG.md): histórico de versões.
163
+
164
+ ## Licença
165
+
166
+ [MIT](LICENSE). Use, copie, modifique e distribua livremente.
167
+
168
+ ## Citação
169
+
170
+ Se você usa este pacote em pesquisa, cite a tese e/ou os artigos:
171
+
172
+ ```bibtex
173
+ @phdthesis{santos2010metodo,
174
+ author = {Santos, Roberto Angelo Fernandes},
175
+ title = {Um Método para Segmentação de Preditores},
176
+ school = {Universidade Federal de Pernambuco},
177
+ year = {2010},
178
+ url = {http://www.cin.ufpe.br/~roberto/AlunosPG/Teses/2010-PhD-Roberto.zip},
179
+ }
180
+
181
+ @inproceedings{santos2012comparing,
182
+ author = {Santos, Roberto Angelo Fernandes and Barros, Roberto Souto Maior de},
183
+ title = {Comparing Segmentation Methods with Different Base Classifiers},
184
+ booktitle = {Proceedings of the 2012 International Conference on Artificial Intelligence (ICAI 2012)},
185
+ year = {2012},
186
+ }
187
+
188
+ @inproceedings{santos2012fbtseg,
189
+ author = {Santos, Roberto Angelo Fernandes and Barros, Roberto Souto Maior de},
190
+ title = {Comparing FBTSeg and NNTree Implementations with Established Ensemble Methods},
191
+ booktitle = {Proceedings of the 24th IEEE International Conference on Tools with Artificial Intelligence (ICTAI 2012)},
192
+ year = {2012},
193
+ }
194
+ ```
195
+
196
+ ## Referências
197
+
198
+ - **SANTOS, R. A. F.** *Um Método para Segmentação de Preditores.* Tese
199
+ (Doutorado em Ciência da Computação) — Centro de Informática, UFPE,
200
+ Recife, 2010. Orientador: Prof. Dr. Roberto Souto Maior de Barros.
201
+ ([docx](docs/reference/Tese_Roberto_Final_Biblioteca.docx))
202
+ - **SANTOS, R. A. F.; BARROS, R. S. M.** Comparing Segmentation Methods
203
+ with Different Base Classifiers. *In:* Proceedings of the
204
+ International Conference on Artificial Intelligence (ICAI), Las
205
+ Vegas, USA, 2012.
206
+ ([PDF](docs/reference/ICAI2012-rafs-proceed.pdf))
207
+ - **SANTOS, R. A. F.; BARROS, R. S. M.** Comparing FBTSeg and NNTree
208
+ Implementations with Established Ensemble Methods. *In:* Proceedings
209
+ of the IEEE International Conference on Tools with Artificial
210
+ Intelligence (ICTAI), Athens, Greece, 2012.
211
+ ([PDF](docs/reference/ICTAI2012-Submitted-140-FBTSeg.pdf))
212
+
213
+ Para citações completas (BibTeX) e referências secundárias citadas
214
+ pelos artigos (Wolpert 1992 — Stacking, Thomas et al. 2002 — Marginal
215
+ Odds, Maji 2008 — NNTree, etc.), veja
216
+ [docs/references.md](docs/references.md).
fbtseg-0.2.0/README.md ADDED
@@ -0,0 +1,186 @@
1
+ # fbtseg
2
+
3
+ [![PyPI version](https://img.shields.io/pypi/v/fbtseg.svg)](https://pypi.org/project/fbtseg/)
4
+ [![Python](https://img.shields.io/pypi/pyversions/fbtseg.svg)](https://pypi.org/project/fbtseg/)
5
+ [![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
6
+
7
+ Implementação em Python do método **FBTSeg** (*Find Best Tree
8
+ Segmentation*, originalmente nomeado RISKSEG) proposto na tese de
9
+ Roberto Angelo Fernandes Santos (UFPE, 2010) e nos artigos
10
+ [ICAI 2012](docs/reference/ICAI2012-rafs-proceed.pdf) e
11
+ [ICTAI 2012](docs/reference/ICTAI2012-Submitted-140-FBTSeg.pdf).
12
+ Estimador sklearn-compatível, focado em alvo binário e reprodução fiel
13
+ dos resultados publicados.
14
+
15
+ ## Instalação
16
+
17
+ ```bash
18
+ pip install fbtseg
19
+ ```
20
+
21
+ ou em modo desenvolvimento:
22
+
23
+ ```bash
24
+ pip install -e .[test]
25
+ ```
26
+
27
+ ## Uso rápido
28
+
29
+ ```python
30
+ from fbtseg import FBTSeg, article_uci_preset
31
+
32
+ model = article_uci_preset(categorical_features=("workclass", "education"))
33
+ model.fit(X_train, y_train)
34
+ proba = model.predict_proba(X_test)[:, 1]
35
+ print(model.plot_model_tree())
36
+ summary = model.get_summary()
37
+ ```
38
+
39
+ Custom:
40
+
41
+ ```python
42
+ from fbtseg import FBTSeg
43
+
44
+ model = FBTSeg(
45
+ max_depth=3,
46
+ min_samples_leaf=0.05,
47
+ metric="error",
48
+ top_k_variables=1, # rQtdeVarTeste
49
+ n_numeric_bins=4, # rQtdeDivisoes
50
+ grouping_features=("education",), # rUsaBlocos
51
+ max_group_size=2, # rQtdeBlocos
52
+ combiner_method="stacking", # ou 'marginal_odds'
53
+ prediction_mode="leaf", # 'leaf' | 'pair_combiner' | 'cascade' | 'global_stacking'
54
+ drop_split_feature_in_children=True,
55
+ )
56
+ model.fit(X_train, y_train)
57
+ ```
58
+
59
+ ## Como funciona
60
+
61
+ Em cada nó terminal o método:
62
+
63
+ 1. Faz **screening fatorial** — uma regressão por variável candidata,
64
+ incluindo dummies da variável, efeitos principais e interações.
65
+ 2. Para a(s) melhor(es) variável(eis), testa **segmentações binárias**
66
+ (categoria-vs-complemento ou grupo de categorias).
67
+ 3. Treina **especialistas** para cada segmento e os combina por
68
+ `Stacking` ou `Marginal Odds`.
69
+ 4. **Aceita a divisão** se ela melhora a métrica D em validação interna
70
+ (com tolerância configurável de ganho mínimo / perda máxima).
71
+ 5. Recorre nos filhos até atingir profundidade máxima ou esgotar
72
+ candidatos.
73
+
74
+ A predição é vetorizada por folha (1 chamada a `predict_proba` por
75
+ folha, não 1 por linha) — 50× a 3000× mais rápida que implementações
76
+ ingênuas.
77
+
78
+ ## CLI
79
+
80
+ ```bash
81
+ # Treinar e salvar
82
+ fbtseg fit --dataset chess --preset article_uci --output-dir runs/chess
83
+
84
+ # CSV próprio
85
+ fbtseg fit --csv data.csv --target y --preset thesis \
86
+ --categorical cat_col_1 cat_col_2
87
+
88
+ # Predição com modelo salvo
89
+ fbtseg predict --model runs/chess/model.pkl --csv new_data.csv --output preds.csv
90
+ ```
91
+
92
+ ## Reprodução do paper ICAI 2012
93
+
94
+ ```bash
95
+ # Tabela 1 do paper — Linear/Logistic/MLP × bases UCI
96
+ python scripts/run_paper_table_replication.py --datasets chess magic spambase german \
97
+ --n-splits 3 --output-dir artifacts/paper_table
98
+
99
+ # Datasets sintéticos do ICTAI 2012
100
+ python scripts/validate_ictai_synthetic.py --datasets 1 2 3 4 \
101
+ --sizes 1000 3000 5000 --n-replications 10
102
+ ```
103
+
104
+ ### Destaques de fidelidade
105
+
106
+ | Dataset | Base | Paper Simple | Paper FBTSeg | fbtseg Simple | fbtseg |
107
+ |---|---|---:|---:|---:|---:|
108
+ | Chess | Logistic | 2.60% | 1.02% | 2.41% | **1.41%** |
109
+ | Magic | Logistic | 20.98% | 18.69% | 20.96% | **16.07%** |
110
+ | Magic | Linear | 32.03% | 16.06% | 21.61% | **16.93%** |
111
+ | Spambase | Linear | 14.89% | 13.51% | 11.15% | **10.45%** |
112
+
113
+ Detalhes em [docs/paper_table_replicated.md](docs/paper_table_replicated.md).
114
+
115
+ ## Estrutura do repositório
116
+
117
+ ```
118
+ fbtseg/ # pacote (estimator, views, tree, combiners, metrics, base_learners, datasets, CLI)
119
+ tests/ # testes (33 cobrindo fit, predict, presets, base learners, métricas)
120
+ scripts/ # scripts de reprodução dos experimentos
121
+ docs/ # documentação + reference (tese + 2 PDFs)
122
+ artifacts/ # resultados de execuções
123
+ trash/v1/ # implementação anterior (V1), preservada para auditoria histórica
124
+ ```
125
+
126
+ ## Documentação
127
+
128
+ - [docs/fbtseg.md](docs/fbtseg.md): API completa + mapeamento parâmetros tese ↔ código.
129
+ - [docs/paper_table_replicated.md](docs/paper_table_replicated.md): replicação da Tabela 1 do ICAI 2012.
130
+ - [docs/benchmark_final.md](docs/benchmark_final.md): benchmark fbtseg vs LR.
131
+ - [docs/examples/quickstart.py](docs/examples/quickstart.py): notebook linear executável.
132
+ - [CHANGELOG.md](CHANGELOG.md): histórico de versões.
133
+
134
+ ## Licença
135
+
136
+ [MIT](LICENSE). Use, copie, modifique e distribua livremente.
137
+
138
+ ## Citação
139
+
140
+ Se você usa este pacote em pesquisa, cite a tese e/ou os artigos:
141
+
142
+ ```bibtex
143
+ @phdthesis{santos2010metodo,
144
+ author = {Santos, Roberto Angelo Fernandes},
145
+ title = {Um Método para Segmentação de Preditores},
146
+ school = {Universidade Federal de Pernambuco},
147
+ year = {2010},
148
+ url = {http://www.cin.ufpe.br/~roberto/AlunosPG/Teses/2010-PhD-Roberto.zip},
149
+ }
150
+
151
+ @inproceedings{santos2012comparing,
152
+ author = {Santos, Roberto Angelo Fernandes and Barros, Roberto Souto Maior de},
153
+ title = {Comparing Segmentation Methods with Different Base Classifiers},
154
+ booktitle = {Proceedings of the 2012 International Conference on Artificial Intelligence (ICAI 2012)},
155
+ year = {2012},
156
+ }
157
+
158
+ @inproceedings{santos2012fbtseg,
159
+ author = {Santos, Roberto Angelo Fernandes and Barros, Roberto Souto Maior de},
160
+ title = {Comparing FBTSeg and NNTree Implementations with Established Ensemble Methods},
161
+ booktitle = {Proceedings of the 24th IEEE International Conference on Tools with Artificial Intelligence (ICTAI 2012)},
162
+ year = {2012},
163
+ }
164
+ ```
165
+
166
+ ## Referências
167
+
168
+ - **SANTOS, R. A. F.** *Um Método para Segmentação de Preditores.* Tese
169
+ (Doutorado em Ciência da Computação) — Centro de Informática, UFPE,
170
+ Recife, 2010. Orientador: Prof. Dr. Roberto Souto Maior de Barros.
171
+ ([docx](docs/reference/Tese_Roberto_Final_Biblioteca.docx))
172
+ - **SANTOS, R. A. F.; BARROS, R. S. M.** Comparing Segmentation Methods
173
+ with Different Base Classifiers. *In:* Proceedings of the
174
+ International Conference on Artificial Intelligence (ICAI), Las
175
+ Vegas, USA, 2012.
176
+ ([PDF](docs/reference/ICAI2012-rafs-proceed.pdf))
177
+ - **SANTOS, R. A. F.; BARROS, R. S. M.** Comparing FBTSeg and NNTree
178
+ Implementations with Established Ensemble Methods. *In:* Proceedings
179
+ of the IEEE International Conference on Tools with Artificial
180
+ Intelligence (ICTAI), Athens, Greece, 2012.
181
+ ([PDF](docs/reference/ICTAI2012-Submitted-140-FBTSeg.pdf))
182
+
183
+ Para citações completas (BibTeX) e referências secundárias citadas
184
+ pelos artigos (Wolpert 1992 — Stacking, Thomas et al. 2002 — Marginal
185
+ Odds, Maji 2008 — NNTree, etc.), veja
186
+ [docs/references.md](docs/references.md).
@@ -0,0 +1,68 @@
1
+ """fbtseg — Find Best Tree Segmentation.
2
+
3
+ Implementacao do metodo de segmentacao binaria recursiva descrito por
4
+ Roberto Santos & Roberto Barros (UFPE, ICAI 2012 e ICTAI 2012). A
5
+ estrategia em cada no terminal e:
6
+
7
+ 1. Screening fatorial das variaveis candidatas (regressao com interacoes).
8
+ 2. Teste de cada categoria/grupo da variavel escolhida.
9
+ 3. Treino de classificadores especialistas para cada segmento.
10
+ 4. Combinacao por Stacking ou Marginal Odds.
11
+ 5. Aceitacao do split conforme ganho minimo / perda maxima.
12
+
13
+ Estimador binario, sklearn-compativel, com predicao vetorizada.
14
+
15
+ Importacoes principais:
16
+
17
+ - `FBTSeg` (alias `RiskSegV2` por compatibilidade): estimador principal.
18
+ - `thesis_preset`, `article_uci_preset`, `article_synthetic_preset`:
19
+ presets fieis a tese, ICAI 2012 e ICTAI 2012 respectivamente.
20
+ - `LinearProbabilityClassifier`: base learner usado para replicar a
21
+ config "Linear" do paper.
22
+ - `load_article_dataset`, `article_specs`, `get_spec`: loaders das 5
23
+ bases UCI usadas pelo paper.
24
+ """
25
+
26
+ from .base_learners import LinearProbabilityClassifier
27
+ from .combiners import MarginalOddsCombiner, StackingCombiner, build_combiner
28
+ from .datasets import DatasetSpec, article_specs, get_spec, load_article_dataset
29
+ from .estimator import (
30
+ RiskSegV2,
31
+ article_synthetic_preset,
32
+ article_uci_preset,
33
+ thesis_preset,
34
+ )
35
+ from .metrics import all_metrics, metric_score
36
+ from .tree import Node, collect_leaves, collect_nodes, route_observations, route_pair_parent
37
+ from .views import ModelView, SegView
38
+
39
+ # Alias publico (FBTSeg = nome do paper; RiskSegV2 = nome herdado da V2)
40
+ FBTSeg = RiskSegV2
41
+
42
+ __version__ = "0.2.0"
43
+
44
+ __all__ = [
45
+ "FBTSeg",
46
+ "RiskSegV2",
47
+ "thesis_preset",
48
+ "article_uci_preset",
49
+ "article_synthetic_preset",
50
+ "LinearProbabilityClassifier",
51
+ "DatasetSpec",
52
+ "article_specs",
53
+ "get_spec",
54
+ "load_article_dataset",
55
+ "SegView",
56
+ "ModelView",
57
+ "StackingCombiner",
58
+ "MarginalOddsCombiner",
59
+ "build_combiner",
60
+ "metric_score",
61
+ "all_metrics",
62
+ "Node",
63
+ "collect_leaves",
64
+ "collect_nodes",
65
+ "route_observations",
66
+ "route_pair_parent",
67
+ "__version__",
68
+ ]
@@ -0,0 +1,5 @@
1
+ """Entry-point para `python -m fbtseg`."""
2
+ from .cli import main
3
+
4
+ if __name__ == "__main__":
5
+ main()
@@ -0,0 +1,87 @@
1
+ """Base learners adicionais para uso no `FBTSeg`.
2
+
3
+ O paper ICAI 2012 (Santos & Barros, 2012a) compara FBTSeg cruzado com
4
+ **três** base learners diferentes:
5
+
6
+ - **Regressão Logística** (LR sem regularização) — disponível
7
+ diretamente via `sklearn.linear_model.LogisticRegression(penalty=None)`.
8
+ - **Regressão Linear** (probabilidade linear, com clip em [0, 1]) —
9
+ exportada aqui como `LinearProbabilityClassifier`.
10
+ - **MLP Neural Network** — usar `sklearn.neural_network.MLPClassifier`
11
+ diretamente. O `FBTSeg._fit_clone` tolera estimadores que não
12
+ aceitam `sample_weight` (cai no caminho sem peso).
13
+
14
+ A intuição por trás de oferecer Regressão Linear como base: é o pior
15
+ classificador entre os três no agregado, MAS é exatamente onde o
16
+ FBTSeg mostra os ganhos mais dramáticos (Magic 32% → 16% no paper,
17
+ porque a segmentação compensa a incapacidade da regressão linear de
18
+ modelar interações).
19
+
20
+ Referências (`docs/references.md`):
21
+ - SANTOS & BARROS, 2012 (ICAI) — Seção 2, Seção 3 (base learners).
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import numpy as np
27
+ from sklearn.base import BaseEstimator, ClassifierMixin
28
+ from sklearn.linear_model import LinearRegression
29
+
30
+
31
+ class LinearProbabilityClassifier(ClassifierMixin, BaseEstimator):
32
+ """Regressão linear ajustada contra `y` em {0, 1}, com escore truncado.
33
+
34
+ Replica a configuração "Linear Regression" do artigo ICAI 2012,
35
+ onde o alvo dicotômico é tratado como contínuo num modelo linear
36
+ e a probabilidade prevista é o output cru, **truncado em [0, 1]**
37
+ para virar uma probabilidade válida (modelo de probabilidade
38
+ linear, MPL).
39
+
40
+ Limitações conhecidas:
41
+ - extrapola para fora de [0, 1] sem o clip;
42
+ - heterocedástico por construção;
43
+ - mas é o que o paper usou e é por isso que está aqui.
44
+
45
+ Compatível com a API sklearn: `fit`, `predict_proba`, `predict`,
46
+ `decision_function`, suporta `clone()`.
47
+ """
48
+
49
+ def __init__(self):
50
+ # Sem hiperparâmetros — manter `__init__` vazio é importante
51
+ # para que `sklearn.base.clone()` funcione sem warning.
52
+ pass
53
+
54
+ def fit(self, X, y, sample_weight=None):
55
+ X = np.asarray(X, dtype=float)
56
+ y = np.asarray(y, dtype=float)
57
+ # Convenção sklearn: `classes_` ordenado.
58
+ self.classes_ = np.array(sorted(np.unique(y).astype(int)))
59
+ if self.classes_.size < 2:
60
+ # Caso degenerado: só uma classe. Vira "classificador constante".
61
+ self.constant_ = float(y.mean()) if y.size else 0.5
62
+ self._fitted = "constant"
63
+ return self
64
+ self.model_ = LinearRegression()
65
+ if sample_weight is not None:
66
+ self.model_.fit(X, y, sample_weight=sample_weight)
67
+ else:
68
+ self.model_.fit(X, y)
69
+ self._fitted = "linear"
70
+ return self
71
+
72
+ def predict_proba(self, X):
73
+ """Devolve `[1-p, p]` com `p = clip(linear(X), 0, 1)`."""
74
+ X = np.asarray(X, dtype=float)
75
+ if self._fitted == "constant":
76
+ n = X.shape[0]
77
+ return np.full((n, 2), [1 - self.constant_, self.constant_], dtype=float)
78
+ # Escore cru da regressão linear, truncado em [0, 1].
79
+ p1 = np.clip(self.model_.predict(X), 0.0, 1.0)
80
+ return np.column_stack([1.0 - p1, p1])
81
+
82
+ def predict(self, X):
83
+ return (self.predict_proba(X)[:, 1] >= 0.5).astype(int)
84
+
85
+ def decision_function(self, X):
86
+ """Escore (probabilidade da classe positiva) — sem truncamento explícito."""
87
+ return self.predict_proba(X)[:, 1]