datakhanon 0.1.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.
- datakhanon-0.1.0/LICENSE +21 -0
- datakhanon-0.1.0/MANIFEST.in +7 -0
- datakhanon-0.1.0/PKG-INFO +370 -0
- datakhanon-0.1.0/README.md +315 -0
- datakhanon-0.1.0/datakhanon/__init__.py +3 -0
- datakhanon-0.1.0/datakhanon/cli.py +0 -0
- datakhanon-0.1.0/datakhanon/core.py +123 -0
- datakhanon-0.1.0/datakhanon/model/__init__.py +72 -0
- datakhanon-0.1.0/datakhanon/model/auto_trainer.py +142 -0
- datakhanon-0.1.0/datakhanon/model/base.py +58 -0
- datakhanon-0.1.0/datakhanon/model/experiment.py +464 -0
- datakhanon-0.1.0/datakhanon/model/exporter.py +49 -0
- datakhanon-0.1.0/datakhanon/model/metrics.py +269 -0
- datakhanon-0.1.0/datakhanon/model/model_spec.py +31 -0
- datakhanon-0.1.0/datakhanon/model/persistence.py +30 -0
- datakhanon-0.1.0/datakhanon/model/registry.py +24 -0
- datakhanon-0.1.0/datakhanon/model/report.py +128 -0
- datakhanon-0.1.0/datakhanon/model/selector.py +60 -0
- datakhanon-0.1.0/datakhanon/model/trainer.py +55 -0
- datakhanon-0.1.0/datakhanon/model/viz.py +136 -0
- datakhanon-0.1.0/datakhanon/model/wrappers.py +56 -0
- datakhanon-0.1.0/datakhanon/preprocess/__init__.py +27 -0
- datakhanon-0.1.0/datakhanon/preprocess/cleaning.py +80 -0
- datakhanon-0.1.0/datakhanon/preprocess/encoders.py +201 -0
- datakhanon-0.1.0/datakhanon/preprocess/features.py +176 -0
- datakhanon-0.1.0/datakhanon/preprocess/imputers.py +145 -0
- datakhanon-0.1.0/datakhanon/preprocess/preprocessor.py +185 -0
- datakhanon-0.1.0/datakhanon/preprocess/reporter.py +1050 -0
- datakhanon-0.1.0/datakhanon/preprocess/utils.py +195 -0
- datakhanon-0.1.0/datakhanon/visualize/__init__.py +37 -0
- datakhanon-0.1.0/datakhanon/visualize/eda.py +115 -0
- datakhanon-0.1.0/datakhanon/visualize/embeddings.py +45 -0
- datakhanon-0.1.0/datakhanon/visualize/explainability.py +88 -0
- datakhanon-0.1.0/datakhanon/visualize/interactive.py +144 -0
- datakhanon-0.1.0/datakhanon/visualize/plots.py +227 -0
- datakhanon-0.1.0/datakhanon.egg-info/PKG-INFO +370 -0
- datakhanon-0.1.0/datakhanon.egg-info/SOURCES.txt +52 -0
- datakhanon-0.1.0/datakhanon.egg-info/dependency_links.txt +1 -0
- datakhanon-0.1.0/datakhanon.egg-info/entry_points.txt +2 -0
- datakhanon-0.1.0/datakhanon.egg-info/requires.txt +34 -0
- datakhanon-0.1.0/datakhanon.egg-info/top_level.txt +1 -0
- datakhanon-0.1.0/datakhanon_logo.png +0 -0
- datakhanon-0.1.0/examples/quickstart.py +105 -0
- datakhanon-0.1.0/examples/quickstart_Auto.py +27 -0
- datakhanon-0.1.0/examples/test_preprocess_pipeline.py +66 -0
- datakhanon-0.1.0/examples/test_preprocess_profile.py +9 -0
- datakhanon-0.1.0/examples/use_binary_auto.py +19 -0
- datakhanon-0.1.0/examples/use_force_model.py +16 -0
- datakhanon-0.1.0/examples/use_iris_auto.py +11 -0
- datakhanon-0.1.0/examples/use_regression_auto.py +16 -0
- datakhanon-0.1.0/examples/visualize_streamlit_app.py +91 -0
- datakhanon-0.1.0/pyproject.toml +112 -0
- datakhanon-0.1.0/setup.cfg +4 -0
- datakhanon-0.1.0/tests/test_pipeline.py +0 -0
datakhanon-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Seu Nome
|
|
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.
|
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: datakhanon
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Biblioteca para mineração de dados e aprendizado de máquina com fluxo end-to-end.
|
|
5
|
+
Author-email: Vinicius de Souza Santos <vinicius.santos@ifsp.edu.br>
|
|
6
|
+
Maintainer-email: ViniciusKanh <vinicius.santos@ifsp.edu.br>
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/ViniciusKanh/datakhanon
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/ViniciusKanh/datakhanon/issues
|
|
10
|
+
Project-URL: Documentation, https://github.com/ViniciusKanh/datakhanon
|
|
11
|
+
Project-URL: Source, https://github.com/ViniciusKanh/datakhanon
|
|
12
|
+
Keywords: data-mining,machine-learning,feature-engineering,preprocessing,eda,model-selection,datakhanon
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Intended Audience :: Science/Research
|
|
20
|
+
Classifier: Intended Audience :: Developers
|
|
21
|
+
Classifier: Topic :: Scientific/Engineering :: Information Analysis
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Requires-Python: >=3.9
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
License-File: LICENSE
|
|
26
|
+
Requires-Dist: numpy>=1.24
|
|
27
|
+
Requires-Dist: pandas>=2.0
|
|
28
|
+
Requires-Dist: scikit-learn>=1.3
|
|
29
|
+
Requires-Dist: scipy>=1.10
|
|
30
|
+
Requires-Dist: matplotlib>=3.8
|
|
31
|
+
Requires-Dist: seaborn>=0.13
|
|
32
|
+
Requires-Dist: joblib>=1.3
|
|
33
|
+
Requires-Dist: PyYAML>=6.0
|
|
34
|
+
Requires-Dist: imbalanced-learn>=0.12
|
|
35
|
+
Provides-Extra: viz
|
|
36
|
+
Requires-Dist: plotly>=5.0; extra == "viz"
|
|
37
|
+
Requires-Dist: bokeh>=3.0; extra == "viz"
|
|
38
|
+
Provides-Extra: dashboard
|
|
39
|
+
Requires-Dist: streamlit>=1.30; extra == "dashboard"
|
|
40
|
+
Provides-Extra: explainer
|
|
41
|
+
Requires-Dist: shap>=0.44; extra == "explainer"
|
|
42
|
+
Provides-Extra: embed
|
|
43
|
+
Requires-Dist: umap-learn>=0.5; extra == "embed"
|
|
44
|
+
Provides-Extra: ensemble
|
|
45
|
+
Provides-Extra: dev
|
|
46
|
+
Requires-Dist: black>=24.0; extra == "dev"
|
|
47
|
+
Requires-Dist: isort>=5.13; extra == "dev"
|
|
48
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
49
|
+
Requires-Dist: pytest-cov>=5.0; extra == "dev"
|
|
50
|
+
Requires-Dist: mypy>=1.8; extra == "dev"
|
|
51
|
+
Requires-Dist: ipython>=8.0; extra == "dev"
|
|
52
|
+
Requires-Dist: twine>=6.0; extra == "dev"
|
|
53
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
54
|
+
Dynamic: license-file
|
|
55
|
+
|
|
56
|
+
# DataKhanon — Ferramentas para Pré-Processamento, Visualização e Modelagem de Dados
|
|
57
|
+
|
|
58
|
+
[](https://pypi.org/project/datakhanon/) [](https://opensource.org/licenses/MIT) [](https://github.com/seu-usuario/datakhanon/actions)
|
|
59
|
+
|
|
60
|
+
<!-- Tecnologias / “botões” -->
|
|
61
|
+
[](https://www.python.org/)
|
|
62
|
+
[](https://pandas.pydata.org/)
|
|
63
|
+
[](https://scikit-learn.org/)
|
|
64
|
+
[](https://matplotlib.org/)
|
|
65
|
+
[](https://plotly.com/)
|
|
66
|
+
[](https://github.com/slundberg/shap)
|
|
67
|
+
[](https://umap-learn.readthedocs.io/)
|
|
68
|
+
|
|
69
|
+
---
|
|
70
|
+
|
|
71
|
+
## Descrição
|
|
72
|
+
|
|
73
|
+
**DataKhanon** é uma biblioteca Python para construção de pipelines reprodutíveis de ciência de dados. Integra funcionalidades para **pré-processamento** (limpeza, imputação, codificação, engenharia/seleção de features), **visualização / EDA / explainability** (plotagem estática e interativa, relatórios HTML, integração SHAP/UMAP) e **modelagem / experimentação** (wrappers, treinadores, AutoTrainer, persistência de artefatos). O objetivo é facilitar a transição entre protótipo, CI e produção mantendo artefatos auditáveis (`preprocessor.joblib`, `schema.json`, `data_health_report.html`, `model/*.joblib`, `summary.json`).
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Recursos principais:
|
|
78
|
+
|
|
79
|
+
* Normalização de schema (nomes e tipos) e remoção baseada em missingness.
|
|
80
|
+
* Imputação por tipo (numérico / categórico) com opções simples e iterativas.
|
|
81
|
+
* Codificações: One-Hot, Ordinal e Target (com mapeamento persistente).
|
|
82
|
+
* Engenharia de features: escalonadores, `VarianceThreshold`, `SelectKBest`, seleção por importância de modelo.
|
|
83
|
+
* Orquestrador `datakhanon.preprocess.Preprocessor` — interface `fit/transform/save/load`.
|
|
84
|
+
* Geração de relatórios de saúde de dados (`data_health_report.html`) e sumários JSON.
|
|
85
|
+
* Visualizações estáticas (matplotlib/seaborn) e interativas (Plotly/Bokeh) com fallback.
|
|
86
|
+
* Explainability com SHAP e projeções UMAP (quando instalados).
|
|
87
|
+
* `datakhanon.model.AutoTrainer` — CV sobre candidatos, seleção do melhor modelo e export de artefatos.
|
|
88
|
+
* `quick_experiment_from_csv` — atalho end-to-end: CSV → EDA → Preprocess → Treino → Artefatos + `summary.json`.
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Instalação
|
|
93
|
+
|
|
94
|
+
Requisitos mínimos: Python ≥ 3.9.
|
|
95
|
+
|
|
96
|
+
Instalação básica:
|
|
97
|
+
|
|
98
|
+
```bash
|
|
99
|
+
pip install datakhanon
|
|
100
|
+
````
|
|
101
|
+
|
|
102
|
+
Instalação com extras (EDA / interactive / explainability):
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
pip install "datakhanon[viz,interactive,explainer]"
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
Recomenda-se utilizar ambiente virtual (venv / conda).
|
|
109
|
+
|
|
110
|
+
---
|
|
111
|
+
|
|
112
|
+
## Quickstart — 3 passos (exemplo mínimo)
|
|
113
|
+
|
|
114
|
+
```python
|
|
115
|
+
import pandas as pd
|
|
116
|
+
from datakhanon.preprocess import Preprocessor
|
|
117
|
+
from datakhanon.visualize import quick_eda
|
|
118
|
+
from datakhanon.model import AutoTrainer
|
|
119
|
+
|
|
120
|
+
# 1. carregar dados
|
|
121
|
+
df = pd.read_csv("examples/credit_dataset_2000.csv")
|
|
122
|
+
y = (df["loan_status"] == "Default").astype(int)
|
|
123
|
+
|
|
124
|
+
# 2. inspeção rápida
|
|
125
|
+
quick_eda(df, output_dir="artifacts/eda", target=y)
|
|
126
|
+
|
|
127
|
+
# 3. preprocess + treino
|
|
128
|
+
pp = Preprocessor(categorical_columns=["purpose","housing"],
|
|
129
|
+
imputer_config={"num_strategy":"median","cat_strategy":"most_frequent"},
|
|
130
|
+
encoder_config={"ohe":{"drop":"first"}},
|
|
131
|
+
feature_engineer_config={"scaler":"standard","select_k":20})
|
|
132
|
+
X = pp.fit_transform(df, y=y)
|
|
133
|
+
pp.save("artifacts/preprocessor.joblib")
|
|
134
|
+
|
|
135
|
+
trainer = AutoTrainer(output_dir="artifacts/model", cv=3, candidates=["rf","lr","xgb"])
|
|
136
|
+
res = trainer.fit(X, y)
|
|
137
|
+
print(res["metrics"])
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
---
|
|
141
|
+
|
|
142
|
+
## `quick_experiment_from_csv` — documentação completa (copy-paste)
|
|
143
|
+
|
|
144
|
+
**Assinatura (exemplo):**
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
quick_experiment_from_csv(
|
|
148
|
+
csv_path: str,
|
|
149
|
+
target_col: Optional[str] = None,
|
|
150
|
+
out_dir: str = "outputs/quick_experiment",
|
|
151
|
+
preprocess_config: Optional[dict] = None,
|
|
152
|
+
trainer_config: Optional[dict] = None,
|
|
153
|
+
run_eda: bool = True,
|
|
154
|
+
sample_predictions: int = 10,
|
|
155
|
+
random_state: int = 42,
|
|
156
|
+
overwrite: bool = False
|
|
157
|
+
) -> dict
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
**Descrição:** atalho que executa, de forma repetível, o pipeline completo: leitura do CSV, (opcional) EDA via `datakhanon.visualize.quick_eda`, pré-processamento com `datakhanon.preprocess.Preprocessor` (fit e persistência), treinamento e seleção por `datakhanon.model.AutoTrainer`, export de artefatos e construção de `summary.json`.
|
|
161
|
+
|
|
162
|
+
**Parâmetros importantes:**
|
|
163
|
+
|
|
164
|
+
* `csv_path`: caminho para o arquivo CSV de entrada.
|
|
165
|
+
* `target_col`: nome da coluna alvo (se `None`, tentativa de autodetecção).
|
|
166
|
+
* `out_dir`: diretório de saída para todos os artefatos.
|
|
167
|
+
* `preprocess_config`: dicionário com parâmetros para `Preprocessor`.
|
|
168
|
+
* `trainer_config`: dicionário com parâmetros para `AutoTrainer` (candidates, cv, scoring, etc.).
|
|
169
|
+
* `run_eda`: se `True`, gera relatório EDA.
|
|
170
|
+
* `sample_predictions`: número de linhas de predição exemplificativa a salvar.
|
|
171
|
+
|
|
172
|
+
**Fluxo executado internamente (resumido):**
|
|
173
|
+
|
|
174
|
+
1. valida `csv_path` e carrega pandas DataFrame.
|
|
175
|
+
2. detecta `target_col` ou usa o fornecido.
|
|
176
|
+
3. gera EDA (se `run_eda=True`).
|
|
177
|
+
4. inicializa e executa `datakhanon.preprocess.Preprocessor.fit_transform`; salva `preprocessor.joblib` e `schema.json`.
|
|
178
|
+
5. inicializa `datakhanon.model.AutoTrainer` com `trainer_config`, executa CV e seleciona melhor candidato; salva `best_model.joblib`, `best_model_spec.json`, `candidates_cv_results.csv` e `metrics_aggregated.json`.
|
|
179
|
+
6. salva `predictions/sample_predictions.csv` com `id, y_true, y_pred, y_score`.
|
|
180
|
+
7. monta e salva `summary.json` (retornado também como `dict` em memória).
|
|
181
|
+
|
|
182
|
+
**Saída em disco (padrão):**
|
|
183
|
+
|
|
184
|
+
```
|
|
185
|
+
out_dir/
|
|
186
|
+
├─ preprocessor/preprocessor.joblib
|
|
187
|
+
├─ schema.json
|
|
188
|
+
├─ eda/data_health_report.html
|
|
189
|
+
├─ eda/eda_summary.json
|
|
190
|
+
├─ model/best_model.joblib
|
|
191
|
+
├─ model/best_model_spec.json
|
|
192
|
+
├─ model/candidates_cv_results.csv
|
|
193
|
+
├─ model/metrics_aggregated.json
|
|
194
|
+
├─ predictions/sample_predictions.csv
|
|
195
|
+
├─ logs/run.log
|
|
196
|
+
└─ summary.json
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
**Exemplo de uso copy-paste:**
|
|
200
|
+
|
|
201
|
+
```python
|
|
202
|
+
from datakhanon.model.experiment import quick_experiment_from_csv
|
|
203
|
+
|
|
204
|
+
summary = quick_experiment_from_csv(
|
|
205
|
+
csv_path="examples/credit_dataset_2000.csv",
|
|
206
|
+
target_col="loan_status",
|
|
207
|
+
out_dir="outputs/credit_exp1",
|
|
208
|
+
preprocess_config={
|
|
209
|
+
"categorical_columns":["purpose","housing"],
|
|
210
|
+
"imputer_config":{"num_strategy":"median","cat_strategy":"most_frequent"},
|
|
211
|
+
"encoder_config":{"ohe":{"drop":"first"}},
|
|
212
|
+
"feature_engineer_config":{"scaler":"standard","select_k":20}
|
|
213
|
+
},
|
|
214
|
+
trainer_config={
|
|
215
|
+
"cv": 3,
|
|
216
|
+
"candidates": ["rf","xgb","lr"],
|
|
217
|
+
"scoring": "f1"
|
|
218
|
+
},
|
|
219
|
+
run_eda=True,
|
|
220
|
+
sample_predictions=10,
|
|
221
|
+
random_state=42,
|
|
222
|
+
overwrite=True
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
# 'summary' é um dict Python equivalente ao summary.json salvo.
|
|
226
|
+
print(summary["training"]["best_model_name"])
|
|
227
|
+
print("EDA salvo em:", summary["paths"]["eda_report"])
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Formato de `summary.json` (exemplo resumido):**
|
|
231
|
+
|
|
232
|
+
```json
|
|
233
|
+
{
|
|
234
|
+
"config": { "csv_path": "examples/credit_dataset_2000.csv", "target_col": "loan_status", "trainer_config": {...} },
|
|
235
|
+
"data": { "n_rows": 2000, "n_cols": 45, "class_balance": {"NoDefault": 0.84, "Default": 0.16} },
|
|
236
|
+
"paths": { "preprocessor": "preprocessor/preprocessor.joblib", "schema": "schema.json", "eda_report": "eda/data_health_report.html", "model_dir": "model/" },
|
|
237
|
+
"training": { "best_model_name": "RandomForest", "best_model_path": "model/best_model.joblib", "metrics": {"f1": {"mean":0.701,"std":0.028}, "roc_auc": {"mean":0.812,"std":0.014}} },
|
|
238
|
+
"predictions": { "sample_predictions_path": "predictions/sample_predictions.csv" },
|
|
239
|
+
"run_metadata": { "run_id": "credit_exp1_20251129T150312", "created_at": "2025-11-29T15:03:12Z" }
|
|
240
|
+
}
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
**Exemplo de linhas esperadas em `candidates_cv_results.csv`:**
|
|
244
|
+
|
|
245
|
+
```
|
|
246
|
+
candidate,fold,metric_name,metric_value,train_time_s,params
|
|
247
|
+
RandomForest,0,f1,0.694,12.3,"{'n_estimators':200}"
|
|
248
|
+
RandomForest,1,f1,0.702,11.8,"{'n_estimators':200}"
|
|
249
|
+
XGBoost,0,f1,0.681,14.5,"{'max_depth':6}"
|
|
250
|
+
...
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
---
|
|
254
|
+
|
|
255
|
+
## Artefatos gerados (resumo rápido e como usá-los)
|
|
256
|
+
|
|
257
|
+
* `preprocessor.joblib` — carregar em produção com `datakhanon.preprocess.Preprocessor.load(...)` e aplicar `transform(df_new)`.
|
|
258
|
+
* `schema.json` — verificar `retained_columns` e dtypes antes de scoring.
|
|
259
|
+
* `data_health_report.html` — relatório auto-contido para auditoria.
|
|
260
|
+
* `best_model.joblib` + `best_model_spec.json` — carregar com `datakhanon.model.load_model(...)`.
|
|
261
|
+
* `summary.json` — entrada canónica para integração com CI e dashboards.
|
|
262
|
+
|
|
263
|
+
---
|
|
264
|
+
|
|
265
|
+
## Exemplos avançados
|
|
266
|
+
|
|
267
|
+
*Uso em produção — inferência:*
|
|
268
|
+
|
|
269
|
+
```python
|
|
270
|
+
from datakhanon.preprocess import Preprocessor
|
|
271
|
+
from datakhanon.model.persistence import load_model
|
|
272
|
+
import pandas as pd
|
|
273
|
+
|
|
274
|
+
pp = Preprocessor.load("outputs/credit_exp1/preprocessor/preprocessor.joblib")
|
|
275
|
+
model, spec = load_model("outputs/credit_exp1/model/best_model.joblib")
|
|
276
|
+
|
|
277
|
+
df_new = pd.read_csv("incoming/new_batch.csv")
|
|
278
|
+
pp.validate_input(df_new) # checar schema
|
|
279
|
+
X_new = pp.transform(df_new)
|
|
280
|
+
preds = model.predict(X_new)
|
|
281
|
+
```
|
|
282
|
+
|
|
283
|
+
---
|
|
284
|
+
|
|
285
|
+
# `examples/quickstart.py`
|
|
286
|
+
|
|
287
|
+
```python
|
|
288
|
+
#!/usr/bin/env python3
|
|
289
|
+
"""
|
|
290
|
+
examples/quickstart.py
|
|
291
|
+
Exemplo mínimo de uso do DataKhanon:
|
|
292
|
+
- gera EDA
|
|
293
|
+
- treina Preprocessor
|
|
294
|
+
- executa AutoTrainer
|
|
295
|
+
- imprime resumo (summary)
|
|
296
|
+
|
|
297
|
+
Uso:
|
|
298
|
+
python examples/quickstart.py
|
|
299
|
+
"""
|
|
300
|
+
|
|
301
|
+
import json
|
|
302
|
+
from pathlib import Path
|
|
303
|
+
import pandas as pd
|
|
304
|
+
|
|
305
|
+
# Import (API de alto nível)
|
|
306
|
+
from datakhanon.preprocess import Preprocessor
|
|
307
|
+
from datakhanon.visualize import quick_eda
|
|
308
|
+
from datakhanon.model.experiment import quick_experiment_from_csv
|
|
309
|
+
from datakhanon.model import AutoTrainer # opcional, uso direto
|
|
310
|
+
|
|
311
|
+
# Ajuste: caminhos
|
|
312
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
313
|
+
EXAMPLE_CSV = ROOT / "examples" / "credit_dataset_2000.csv"
|
|
314
|
+
OUT_DIR = ROOT / "outputs" / "quickstart_example"
|
|
315
|
+
|
|
316
|
+
def run_quick_example():
|
|
317
|
+
# 1) Carregar dados
|
|
318
|
+
if not EXAMPLE_CSV.exists():
|
|
319
|
+
raise FileNotFoundError(f"Arquivo de exemplo não encontrado: {EXAMPLE_CSV}")
|
|
320
|
+
df = pd.read_csv(EXAMPLE_CSV)
|
|
321
|
+
# Exemplo: converter label para binário
|
|
322
|
+
if "loan_status" not in df.columns:
|
|
323
|
+
raise KeyError("Coluna 'loan_status' esperada no dataset de exemplo.")
|
|
324
|
+
y = (df["loan_status"] == "Default").astype(int)
|
|
325
|
+
|
|
326
|
+
# 2) Quick EDA (gera artifacts/eda)
|
|
327
|
+
print("Gerando EDA rápido...")
|
|
328
|
+
quick_eda(df, output_dir=str(OUT_DIR / "eda"), target=y, use_reporter=True)
|
|
329
|
+
|
|
330
|
+
# 3) Executar quick_experiment_from_csv (end-to-end)
|
|
331
|
+
print("Executando quick_experiment_from_csv (treino completo)...")
|
|
332
|
+
summary = quick_experiment_from_csv(
|
|
333
|
+
csv_path=str(EXAMPLE_CSV),
|
|
334
|
+
target_col="loan_status",
|
|
335
|
+
out_dir=str(OUT_DIR),
|
|
336
|
+
preprocess_config={
|
|
337
|
+
"categorical_columns": ["purpose", "housing"],
|
|
338
|
+
"imputer_config": {"num_strategy": "median", "cat_strategy": "most_frequent"},
|
|
339
|
+
"encoder_config": {"ohe": {"drop": "first"}},
|
|
340
|
+
"feature_engineer_config": {"scaler": "standard", "select_k": 20}
|
|
341
|
+
},
|
|
342
|
+
trainer_config={
|
|
343
|
+
"cv": 3,
|
|
344
|
+
"candidates": ["rf", "xgb", "lr"],
|
|
345
|
+
"scoring": "f1"
|
|
346
|
+
},
|
|
347
|
+
run_eda=False, # já rodamos acima
|
|
348
|
+
sample_predictions=10,
|
|
349
|
+
random_state=42,
|
|
350
|
+
overwrite=True
|
|
351
|
+
)
|
|
352
|
+
|
|
353
|
+
# 4) Salvar e imprimir resumo
|
|
354
|
+
OUT_DIR.mkdir(parents=True, exist_ok=True)
|
|
355
|
+
summary_path = OUT_DIR / "summary_inspect.json"
|
|
356
|
+
summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False))
|
|
357
|
+
print("Resumo do experimento salvo em:", summary_path)
|
|
358
|
+
print("Melhor modelo:", summary["training"].get("best_model_name"))
|
|
359
|
+
print("EDA report:", summary["paths"].get("eda_report"))
|
|
360
|
+
print("Modelo salvo em:", summary["training"].get("best_model_path"))
|
|
361
|
+
|
|
362
|
+
if __name__ == "__main__":
|
|
363
|
+
run_quick_example()
|
|
364
|
+
````
|
|
365
|
+
## Licença e créditos
|
|
366
|
+
|
|
367
|
+
Licença: MIT.
|
|
368
|
+
Autor: **Vinicius de Souza Santos** — Mestrado em Ciências da Computação (UNESP Bauru).
|
|
369
|
+
|
|
370
|
+
|