fkdc 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.
- fkdc-0.1.1/.gitignore +36 -0
- fkdc-0.1.1/LICENSE +21 -0
- fkdc-0.1.1/PKG-INFO +145 -0
- fkdc-0.1.1/README.md +115 -0
- fkdc-0.1.1/fkdc/__init__.py +51 -0
- fkdc-0.1.1/fkdc/fermat.py +400 -0
- fkdc-0.1.1/pyproject.toml +111 -0
fkdc-0.1.1/.gitignore
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
**/.DS_store
|
|
2
|
+
.ipynb_checkpoints
|
|
3
|
+
.venv
|
|
4
|
+
# Bibliografía local (PDFs, notas, etc.)
|
|
5
|
+
bib/
|
|
6
|
+
# caches
|
|
7
|
+
.cache
|
|
8
|
+
_cache
|
|
9
|
+
__pycache__
|
|
10
|
+
# Data files
|
|
11
|
+
*.pkl
|
|
12
|
+
*.pyc
|
|
13
|
+
# LaTeX
|
|
14
|
+
*.aux
|
|
15
|
+
*.fdb_latexmk
|
|
16
|
+
*.fls
|
|
17
|
+
*.log
|
|
18
|
+
*.out
|
|
19
|
+
*.synctex.gz
|
|
20
|
+
*.toc
|
|
21
|
+
*.lyx~
|
|
22
|
+
# Directorios de trabajo
|
|
23
|
+
datasets
|
|
24
|
+
configs
|
|
25
|
+
infos
|
|
26
|
+
runs
|
|
27
|
+
**/sandbox/*
|
|
28
|
+
admin
|
|
29
|
+
jurado
|
|
30
|
+
# Bulk output from fkdc/viz.py (root-level scratch folders)
|
|
31
|
+
/img/
|
|
32
|
+
/data/
|
|
33
|
+
# Viz stamp file
|
|
34
|
+
docs/.viz-stamp
|
|
35
|
+
# Credenciales locales
|
|
36
|
+
.env
|
fkdc-0.1.1/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022 Gonzalo Barrera Borla
|
|
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.
|
fkdc-0.1.1/PKG-INFO
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: fkdc
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Distancia de Fermat en Clasificadores de Densidad por Núcleos
|
|
5
|
+
Project-URL: Homepage, https://github.com/capitantoto/fermat
|
|
6
|
+
Project-URL: Repository, https://github.com/capitantoto/fermat
|
|
7
|
+
Project-URL: Issues, https://github.com/capitantoto/fermat/issues
|
|
8
|
+
Author-email: Gonzalo Barrera Borla <gonzalobb@gmail.com>
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: fermat distance,k-nearest neighbors,kernel density classifier,kernel density estimation,manifold learning,scikit-learn
|
|
12
|
+
Classifier: Development Status :: 3 - Alpha
|
|
13
|
+
Classifier: Intended Audience :: Science/Research
|
|
14
|
+
Classifier: Natural Language :: Spanish
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
22
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Mathematics
|
|
24
|
+
Requires-Python: >=3.11
|
|
25
|
+
Requires-Dist: joblib>=1.2.0
|
|
26
|
+
Requires-Dist: numpy>=1.26.4
|
|
27
|
+
Requires-Dist: scikit-learn>=1.4.1.post1
|
|
28
|
+
Requires-Dist: scipy>=1.12.0
|
|
29
|
+
Description-Content-Type: text/markdown
|
|
30
|
+
|
|
31
|
+
# `fkdc`: Distancia de Fermat en Clasificadores de Densidad por Núcleos
|
|
32
|
+
Lic. Gonzalo Barrera Borla
|
|
33
|
+
|
|
34
|
+
Dir.: Dr. Pablo Groisman
|
|
35
|
+
|
|
36
|
+
Tesis de Maestría en Estadística Matemática, FCEN-UBA, 2026. El código se distribuye bajo licencia MIT.
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
## Biblioteca
|
|
40
|
+
|
|
41
|
+
El núcleo de la tesis, `fkdc.fermat`, se publica como biblioteca compatible con scikit-learn: la distancia de Fermat muestral (`SampleFermatDistance`), el estimador de densidad por núcleos con esa distancia (`FermatKDE`), su par euclídeo exacto (`EuclideanKDE`) y los clasificadores `KDClassifier` y `FermatKNeighborsClassifier`. La teoría y los experimentos están en [la tesis](https://github.com/capitantoto/fermat/blob/main/docs/tesis.pdf).
|
|
42
|
+
|
|
43
|
+
```bash
|
|
44
|
+
pip install fkdc
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
```python
|
|
48
|
+
from sklearn.datasets import make_moons
|
|
49
|
+
from fkdc import KDClassifier
|
|
50
|
+
|
|
51
|
+
X, y = make_moons(n_samples=200, noise=0.2, random_state=0)
|
|
52
|
+
clf = KDClassifier(metric="fermat", alpha=2.0, bandwidth=0.3).fit(X, y)
|
|
53
|
+
probas = clf.predict_proba(X[:5])
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`metric` acepta `"fermat"` (con su `alpha`), `"euclidea_exacta"` y las métricas de `sklearn.neighbors.KernelDensity` que no requieren parámetros propios, ya que `metric_params` no se transmite. Para densidades euclídeas exactas conviene `metric="euclidea_exacta"`: el valor por defecto, `"euclidean"`, pasa por `KernelDensity`, cuyo recorrido del árbol devuelve log-densidades erróneas en la cola profunda.
|
|
57
|
+
|
|
58
|
+
Instalada así, la biblioteca no escribe caché en disco. Para memorizar las distancias entre corridas, basta definir la variable de entorno `FKDC_CACHE` con un directorio; se lee al importar `fkdc`, así que debe definirse antes del primer `import fkdc`.
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
## Reproducir la tesis
|
|
62
|
+
|
|
63
|
+
### Instalación
|
|
64
|
+
|
|
65
|
+
#### Requisitos previos
|
|
66
|
+
- [uv](https://docs.astral.sh/uv/) (gestor de paquetes Python)
|
|
67
|
+
- [Typst](https://typst.app/) (para compilar los documentos)
|
|
68
|
+
- GNU Make
|
|
69
|
+
|
|
70
|
+
#### Instalar Typst
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
# macOS
|
|
74
|
+
brew install typst
|
|
75
|
+
|
|
76
|
+
# o con cargo
|
|
77
|
+
cargo install typst-cli
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Alternativamente, instalar la extensión [Tinymist](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) en VS Code para compilación integrada y vista previa.
|
|
81
|
+
|
|
82
|
+
#### Configuración del entorno
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
# Clonar el repositorio
|
|
86
|
+
git clone https://github.com/capitantoto/fermat.git
|
|
87
|
+
cd fermat
|
|
88
|
+
|
|
89
|
+
# Crear entorno virtual e instalar dependencias
|
|
90
|
+
uv sync
|
|
91
|
+
|
|
92
|
+
# Instalar hooks de pre-commit y filtro de notebooks
|
|
93
|
+
uv run pre-commit install
|
|
94
|
+
uv run nbstripout --install
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### Compilar documentos
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
# Compilar todos los .typ → .pdf (tesis, plan, poster)
|
|
101
|
+
make docs
|
|
102
|
+
|
|
103
|
+
# Compilar solo la tesis
|
|
104
|
+
typst compile docs/tesis.typ
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Para compilación continua durante la edición:
|
|
108
|
+
|
|
109
|
+
```bash
|
|
110
|
+
typst watch docs/tesis.typ
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
Ver `make help` para la lista completa de targets disponibles.
|
|
114
|
+
|
|
115
|
+
### Bibliografía
|
|
116
|
+
|
|
117
|
+
#### Zotero
|
|
118
|
+
|
|
119
|
+
Este proyecto usa [Zotero](https://www.zotero.org/) para gestionar las referencias bibliográficas.
|
|
120
|
+
|
|
121
|
+
#### Better BibTeX
|
|
122
|
+
|
|
123
|
+
Para exportar las referencias en formato compatible con Typst, se requiere la extensión [Better BibTeX for Zotero](https://retorque.re/zotero-better-bibtex/).
|
|
124
|
+
|
|
125
|
+
Descarga e instalación: https://retorque.re/zotero-better-bibtex/installation/
|
|
126
|
+
|
|
127
|
+
De ser necesario, una copia de la extensión está disponible en [src/zotero-better-bibtex-6.7.240.xpi](https://github.com/capitantoto/fermat/blob/main/src/zotero-better-bibtex-6.7.240.xpi).
|
|
128
|
+
|
|
129
|
+
#### Exportar referencias
|
|
130
|
+
|
|
131
|
+
Para generar o actualizar `docs/references.bib`:
|
|
132
|
+
|
|
133
|
+
1. En Zotero, seleccionar la colección correspondiente a la tesis
|
|
134
|
+
2. Clic derecho → "Export Collection..."
|
|
135
|
+
3. Formato: "Better BibLaTeX" o "Better BibTeX"
|
|
136
|
+
4. Guardar como `docs/references.bib`
|
|
137
|
+
|
|
138
|
+
Alternativamente, configurar una exportación automática:
|
|
139
|
+
1. Clic derecho en la colección → "Export Collection..."
|
|
140
|
+
2. Marcar "Keep updated"
|
|
141
|
+
3. Seleccionar la ruta `docs/references.bib`
|
|
142
|
+
|
|
143
|
+
## Uso de IA
|
|
144
|
+
|
|
145
|
+
Este proyecto utiliza herramientas de IA (Claude, de Anthropic) para tareas de revisión y formato. El contenido intelectual es enteramente del autor. Ver [CLAUDE.md](https://github.com/capitantoto/fermat/blob/main/CLAUDE.md) para más detalles sobre los principios y límites de este uso.
|
fkdc-0.1.1/README.md
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# `fkdc`: Distancia de Fermat en Clasificadores de Densidad por Núcleos
|
|
2
|
+
Lic. Gonzalo Barrera Borla
|
|
3
|
+
|
|
4
|
+
Dir.: Dr. Pablo Groisman
|
|
5
|
+
|
|
6
|
+
Tesis de Maestría en Estadística Matemática, FCEN-UBA, 2026. El código se distribuye bajo licencia MIT.
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
## Biblioteca
|
|
10
|
+
|
|
11
|
+
El núcleo de la tesis, `fkdc.fermat`, se publica como biblioteca compatible con scikit-learn: la distancia de Fermat muestral (`SampleFermatDistance`), el estimador de densidad por núcleos con esa distancia (`FermatKDE`), su par euclídeo exacto (`EuclideanKDE`) y los clasificadores `KDClassifier` y `FermatKNeighborsClassifier`. La teoría y los experimentos están en [la tesis](https://github.com/capitantoto/fermat/blob/main/docs/tesis.pdf).
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install fkdc
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from sklearn.datasets import make_moons
|
|
19
|
+
from fkdc import KDClassifier
|
|
20
|
+
|
|
21
|
+
X, y = make_moons(n_samples=200, noise=0.2, random_state=0)
|
|
22
|
+
clf = KDClassifier(metric="fermat", alpha=2.0, bandwidth=0.3).fit(X, y)
|
|
23
|
+
probas = clf.predict_proba(X[:5])
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
`metric` acepta `"fermat"` (con su `alpha`), `"euclidea_exacta"` y las métricas de `sklearn.neighbors.KernelDensity` que no requieren parámetros propios, ya que `metric_params` no se transmite. Para densidades euclídeas exactas conviene `metric="euclidea_exacta"`: el valor por defecto, `"euclidean"`, pasa por `KernelDensity`, cuyo recorrido del árbol devuelve log-densidades erróneas en la cola profunda.
|
|
27
|
+
|
|
28
|
+
Instalada así, la biblioteca no escribe caché en disco. Para memorizar las distancias entre corridas, basta definir la variable de entorno `FKDC_CACHE` con un directorio; se lee al importar `fkdc`, así que debe definirse antes del primer `import fkdc`.
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
## Reproducir la tesis
|
|
32
|
+
|
|
33
|
+
### Instalación
|
|
34
|
+
|
|
35
|
+
#### Requisitos previos
|
|
36
|
+
- [uv](https://docs.astral.sh/uv/) (gestor de paquetes Python)
|
|
37
|
+
- [Typst](https://typst.app/) (para compilar los documentos)
|
|
38
|
+
- GNU Make
|
|
39
|
+
|
|
40
|
+
#### Instalar Typst
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
# macOS
|
|
44
|
+
brew install typst
|
|
45
|
+
|
|
46
|
+
# o con cargo
|
|
47
|
+
cargo install typst-cli
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
Alternativamente, instalar la extensión [Tinymist](https://marketplace.visualstudio.com/items?itemName=myriad-dreamin.tinymist) en VS Code para compilación integrada y vista previa.
|
|
51
|
+
|
|
52
|
+
#### Configuración del entorno
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
# Clonar el repositorio
|
|
56
|
+
git clone https://github.com/capitantoto/fermat.git
|
|
57
|
+
cd fermat
|
|
58
|
+
|
|
59
|
+
# Crear entorno virtual e instalar dependencias
|
|
60
|
+
uv sync
|
|
61
|
+
|
|
62
|
+
# Instalar hooks de pre-commit y filtro de notebooks
|
|
63
|
+
uv run pre-commit install
|
|
64
|
+
uv run nbstripout --install
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Compilar documentos
|
|
68
|
+
|
|
69
|
+
```bash
|
|
70
|
+
# Compilar todos los .typ → .pdf (tesis, plan, poster)
|
|
71
|
+
make docs
|
|
72
|
+
|
|
73
|
+
# Compilar solo la tesis
|
|
74
|
+
typst compile docs/tesis.typ
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Para compilación continua durante la edición:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
typst watch docs/tesis.typ
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Ver `make help` para la lista completa de targets disponibles.
|
|
84
|
+
|
|
85
|
+
### Bibliografía
|
|
86
|
+
|
|
87
|
+
#### Zotero
|
|
88
|
+
|
|
89
|
+
Este proyecto usa [Zotero](https://www.zotero.org/) para gestionar las referencias bibliográficas.
|
|
90
|
+
|
|
91
|
+
#### Better BibTeX
|
|
92
|
+
|
|
93
|
+
Para exportar las referencias en formato compatible con Typst, se requiere la extensión [Better BibTeX for Zotero](https://retorque.re/zotero-better-bibtex/).
|
|
94
|
+
|
|
95
|
+
Descarga e instalación: https://retorque.re/zotero-better-bibtex/installation/
|
|
96
|
+
|
|
97
|
+
De ser necesario, una copia de la extensión está disponible en [src/zotero-better-bibtex-6.7.240.xpi](https://github.com/capitantoto/fermat/blob/main/src/zotero-better-bibtex-6.7.240.xpi).
|
|
98
|
+
|
|
99
|
+
#### Exportar referencias
|
|
100
|
+
|
|
101
|
+
Para generar o actualizar `docs/references.bib`:
|
|
102
|
+
|
|
103
|
+
1. En Zotero, seleccionar la colección correspondiente a la tesis
|
|
104
|
+
2. Clic derecho → "Export Collection..."
|
|
105
|
+
3. Formato: "Better BibLaTeX" o "Better BibTeX"
|
|
106
|
+
4. Guardar como `docs/references.bib`
|
|
107
|
+
|
|
108
|
+
Alternativamente, configurar una exportación automática:
|
|
109
|
+
1. Clic derecho en la colección → "Export Collection..."
|
|
110
|
+
2. Marcar "Keep updated"
|
|
111
|
+
3. Seleccionar la ruta `docs/references.bib`
|
|
112
|
+
|
|
113
|
+
## Uso de IA
|
|
114
|
+
|
|
115
|
+
Este proyecto utiliza herramientas de IA (Claude, de Anthropic) para tareas de revisión y formato. El contenido intelectual es enteramente del autor. Ver [CLAUDE.md](https://github.com/capitantoto/fermat/blob/main/CLAUDE.md) para más detalles sobre los principios y límites de este uso.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import os
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from typing import TYPE_CHECKING
|
|
4
|
+
|
|
5
|
+
dir_raiz = Path(__file__).parent.parent.absolute()
|
|
6
|
+
# Sobreescribible por entorno (lo heredan también los workers de loky): campañas o
|
|
7
|
+
# experimentos con un caché propio no inflan el global. Sin la variable, `.cache` en la
|
|
8
|
+
# raíz del repositorio; instalado como biblioteca, sin caché en disco: `None` y `fermat`
|
|
9
|
+
# no escribe nada. El repositorio se reconoce por su `pyproject.toml` y por un módulo de
|
|
10
|
+
# la investigación que el wheel excluye (copiado o instalado con `--target`, no está).
|
|
11
|
+
_en_repositorio = (dir_raiz / "pyproject.toml").is_file() and (
|
|
12
|
+
dir_raiz / "fkdc" / "campanias.py"
|
|
13
|
+
).is_file()
|
|
14
|
+
dir_cache = (
|
|
15
|
+
Path(os.environ["FKDC_CACHE"])
|
|
16
|
+
if os.environ.get("FKDC_CACHE")
|
|
17
|
+
else (dir_raiz / ".cache" if _en_repositorio else None)
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
# API pública de la biblioteca, cargada a demanda: `import fkdc` (y con él cada módulo
|
|
21
|
+
# de la investigación que importa `fkdc.config` o `dir_raiz`) no arrastra numpy ni
|
|
22
|
+
# sklearn
|
|
23
|
+
__all__ = [
|
|
24
|
+
"EuclideanKDE",
|
|
25
|
+
"FermatKDE",
|
|
26
|
+
"FermatKNeighborsClassifier",
|
|
27
|
+
"KDClassifier",
|
|
28
|
+
"SampleFermatDistance",
|
|
29
|
+
]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
if TYPE_CHECKING: # para los verificadores de tipos; en ejecución, `__getattr__`
|
|
33
|
+
from fkdc.fermat import (
|
|
34
|
+
EuclideanKDE,
|
|
35
|
+
FermatKDE,
|
|
36
|
+
FermatKNeighborsClassifier,
|
|
37
|
+
KDClassifier,
|
|
38
|
+
SampleFermatDistance,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def __getattr__(nombre):
|
|
43
|
+
if nombre in __all__:
|
|
44
|
+
from fkdc import fermat
|
|
45
|
+
|
|
46
|
+
return getattr(fermat, nombre)
|
|
47
|
+
raise AttributeError(f"module {__name__!r} has no attribute {nombre!r}")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def __dir__():
|
|
51
|
+
return sorted(set(globals()) | set(__all__))
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
from functools import partial
|
|
2
|
+
|
|
3
|
+
import numpy as np
|
|
4
|
+
from joblib import Memory
|
|
5
|
+
from scipy.sparse.csgraph import csgraph_from_dense, shortest_path
|
|
6
|
+
from scipy.spatial.distance import cdist, pdist, squareform
|
|
7
|
+
from sklearn.base import BaseEstimator, ClassifierMixin, DensityMixin
|
|
8
|
+
from sklearn.neighbors import KernelDensity, KNeighborsClassifier
|
|
9
|
+
from sklearn.utils.multiclass import unique_labels
|
|
10
|
+
from sklearn.utils.validation import check_array, check_is_fitted, check_X_y
|
|
11
|
+
|
|
12
|
+
from fkdc import dir_cache
|
|
13
|
+
|
|
14
|
+
# Con `dir_cache` en None (biblioteca instalada, sin `FKDC_CACHE`) no memoriza en disco
|
|
15
|
+
memoria = Memory(dir_cache, verbose=0)
|
|
16
|
+
|
|
17
|
+
MIN_PUNTAJE_LOG = np.log(1e-323) # Para numpy, 1e-324 == 0 y 1e-323 != 0
|
|
18
|
+
MAX_PUNTAJE_LOG = np.log(np.finfo("float64").max)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _validar_prediccion(estimador, X):
|
|
22
|
+
"""Valida X contra un estimador ajustado, con los mensajes de scikit-learn."""
|
|
23
|
+
check_is_fitted(estimador)
|
|
24
|
+
X = check_array(X)
|
|
25
|
+
if X.shape[1] != estimador.n_features_in_:
|
|
26
|
+
raise ValueError(
|
|
27
|
+
f"X has {X.shape[1]} features, but {type(estimador).__name__} "
|
|
28
|
+
f"is expecting {estimador.n_features_in_} features as input"
|
|
29
|
+
)
|
|
30
|
+
return X
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@memoria.cache
|
|
34
|
+
def euclidean(X, Y=None):
|
|
35
|
+
"""Matriz de distancias euclideans."""
|
|
36
|
+
if Y is None:
|
|
37
|
+
return squareform(pdist(X, metric="euclidean"))
|
|
38
|
+
else:
|
|
39
|
+
return cdist(X, Y, metric="euclidean")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@memoria.cache
|
|
43
|
+
def fermat_muestral(Q, alpha=1, valor_relleno=np.inf):
|
|
44
|
+
"""Distancia de Fermat muestral sobre el grafo completo de Q."""
|
|
45
|
+
adyacencias = np.ma.masked_array(
|
|
46
|
+
euclidean(Q) ** alpha,
|
|
47
|
+
np.diag([True] * Q.shape[0]),
|
|
48
|
+
fill_value=valor_relleno,
|
|
49
|
+
)
|
|
50
|
+
return shortest_path(csgraph_from_dense(adyacencias, valor_relleno), directed=False)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class SampleFermatDistance:
|
|
54
|
+
"""Distancia de Fermat muestral con soporte para grupos.
|
|
55
|
+
|
|
56
|
+
Al construirse, calcula la distancia de Fermat muestral entre las observaciones
|
|
57
|
+
de Q (dentro de cada grupo, si los hay). Invocada como `distancia(X)`, devuelve
|
|
58
|
+
la distancia de cada fila de X a cada observación de Q, de forma
|
|
59
|
+
`(len(X), len(Q))`; como `distancia(X, Y)`, la distancia entre cada fila de X y
|
|
60
|
+
cada fila de Y.
|
|
61
|
+
|
|
62
|
+
Parámetros
|
|
63
|
+
----------
|
|
64
|
+
Q : ndarray de forma (N, D)
|
|
65
|
+
Muestra que define la distancia.
|
|
66
|
+
alpha : float, por defecto 1
|
|
67
|
+
Exponente aplicado a las distancias euclídeas entre observaciones.
|
|
68
|
+
grupos : array de largo N o None, por defecto None
|
|
69
|
+
Etiqueta de grupo de cada observación; las trayectorias no cruzan de un
|
|
70
|
+
grupo a otro. Con None, un solo grupo.
|
|
71
|
+
"""
|
|
72
|
+
|
|
73
|
+
def __init__(self, Q, alpha: float = 1, grupos=None):
|
|
74
|
+
self.Q = Q
|
|
75
|
+
self.N, self.D = Q.shape
|
|
76
|
+
self.grupos = np.array(np.zeros(self.N) if grupos is None else grupos)
|
|
77
|
+
self.etiquetas = unique_labels(self.grupos)
|
|
78
|
+
if len(self.grupos) != self.N:
|
|
79
|
+
raise ValueError(
|
|
80
|
+
"`grupos` debe ser None, o de igual número que las filas de Q"
|
|
81
|
+
)
|
|
82
|
+
self.alpha = alpha
|
|
83
|
+
self.A = {
|
|
84
|
+
lbl: fermat_muestral(Q[self.grupos == lbl], alpha) for lbl in self.etiquetas
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
def __setstate__(self, state):
|
|
88
|
+
# Compatibilidad con pickles anteriores a la traducción al español
|
|
89
|
+
if "groups" in state and "grupos" not in state:
|
|
90
|
+
state["grupos"] = state.pop("groups")
|
|
91
|
+
if "labels" in state and "etiquetas" not in state:
|
|
92
|
+
state["etiquetas"] = state.pop("labels")
|
|
93
|
+
self.__dict__.update(state)
|
|
94
|
+
|
|
95
|
+
def _distancia_muestral(self, X):
|
|
96
|
+
"""Distancia de cada punto en X a cada punto en Q, vía la muestra."""
|
|
97
|
+
distancias_muestrales = -np.ones((X.shape[0], self.N))
|
|
98
|
+
|
|
99
|
+
for lbl in self.etiquetas:
|
|
100
|
+
mascara_grupo = self.grupos == lbl
|
|
101
|
+
a_Q_lbl = euclidean(X, self.Q[mascara_grupo]) ** self.alpha
|
|
102
|
+
for i in range(len(X)):
|
|
103
|
+
distancias_muestrales[i, mascara_grupo] = np.min(
|
|
104
|
+
a_Q_lbl[i].T + self.A[lbl], axis=1
|
|
105
|
+
)
|
|
106
|
+
assert np.all(distancias_muestrales >= 0)
|
|
107
|
+
return distancias_muestrales
|
|
108
|
+
|
|
109
|
+
def _distancia(self, X, Y):
|
|
110
|
+
"""Distancia de Fermat muestral entre cada par (x, y) en X × Y."""
|
|
111
|
+
dfs_XQ = self._distancia_muestral(X)
|
|
112
|
+
dfs_YQ = self._distancia_muestral(Y)
|
|
113
|
+
euc_XY = euclidean(X, Y)
|
|
114
|
+
nX, nY = X.shape[0], Y.shape[0]
|
|
115
|
+
distancias = -np.ones((nX, nY))
|
|
116
|
+
for i in range(nX):
|
|
117
|
+
for j in range(nY):
|
|
118
|
+
bypass_dfs = euc_XY[i, j] ** self.alpha
|
|
119
|
+
cruce_dfs = np.min(dfs_XQ[i] + dfs_YQ[j])
|
|
120
|
+
distancias[i, j] = np.min([bypass_dfs, cruce_dfs])
|
|
121
|
+
assert np.all(distancias >= 0)
|
|
122
|
+
return distancias
|
|
123
|
+
|
|
124
|
+
def __call__(self, X, Y=None):
|
|
125
|
+
if X.ndim == 1: # en caso de que lo llamen con una sola observación en X
|
|
126
|
+
X = X.reshape(1, self.D)
|
|
127
|
+
if Y is None:
|
|
128
|
+
return self._distancia_muestral(X)
|
|
129
|
+
else:
|
|
130
|
+
if Y.ndim == 1: # en caso de que lo llamen con una sola observación en Y
|
|
131
|
+
Y = Y.reshape(1, self.D)
|
|
132
|
+
return self._distancia(X, Y)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
class FermatKNeighborsClassifier(ClassifierMixin, BaseEstimator):
|
|
136
|
+
"""Clasificador de k vecinos más cercanos con distancia de Fermat muestral.
|
|
137
|
+
|
|
138
|
+
Las distancias se calculan con `SampleFermatDistance` sobre la muestra de
|
|
139
|
+
entrenamiento de cada clase por separado y se pasan precalculadas a
|
|
140
|
+
`sklearn.neighbors.KNeighborsClassifier`.
|
|
141
|
+
|
|
142
|
+
Parámetros
|
|
143
|
+
----------
|
|
144
|
+
n_neighbors : int, por defecto 5
|
|
145
|
+
Cantidad de vecinos.
|
|
146
|
+
alpha : float, por defecto 1
|
|
147
|
+
Exponente de la distancia de Fermat muestral; con `alpha=1` coincide con la
|
|
148
|
+
euclídea.
|
|
149
|
+
weights : {"uniform", "distance"} o invocable, por defecto "uniform"
|
|
150
|
+
Pesos de los vecinos, como en `KNeighborsClassifier`.
|
|
151
|
+
n_jobs : int, por defecto -1
|
|
152
|
+
Procesos para la búsqueda de vecinos, como en `KNeighborsClassifier`.
|
|
153
|
+
|
|
154
|
+
Atributos
|
|
155
|
+
---------
|
|
156
|
+
classes_ : ndarray
|
|
157
|
+
Etiquetas de clase.
|
|
158
|
+
n_features_in_ : int
|
|
159
|
+
Cantidad de variables vistas en `fit`.
|
|
160
|
+
distance_ : SampleFermatDistance
|
|
161
|
+
Distancia ajustada a la muestra de entrenamiento.
|
|
162
|
+
classifier_ : KNeighborsClassifier
|
|
163
|
+
Clasificador subyacente, ajustado sobre las distancias precalculadas.
|
|
164
|
+
"""
|
|
165
|
+
|
|
166
|
+
def __init__(self, n_neighbors=5, alpha=1, weights="uniform", n_jobs=-1):
|
|
167
|
+
self.n_neighbors = n_neighbors
|
|
168
|
+
self.alpha = alpha
|
|
169
|
+
self.weights = weights
|
|
170
|
+
self.n_jobs = n_jobs
|
|
171
|
+
|
|
172
|
+
def fit(self, X, y):
|
|
173
|
+
X, y = check_X_y(X, y)
|
|
174
|
+
self.classes_ = unique_labels(y)
|
|
175
|
+
self.n_features_in_ = X.shape[1]
|
|
176
|
+
self.distance_ = SampleFermatDistance(Q=X, alpha=self.alpha, grupos=y)
|
|
177
|
+
self.classifier_ = KNeighborsClassifier(
|
|
178
|
+
n_neighbors=self.n_neighbors,
|
|
179
|
+
weights=self.weights,
|
|
180
|
+
metric="precomputed",
|
|
181
|
+
n_jobs=self.n_jobs,
|
|
182
|
+
)
|
|
183
|
+
self.classifier_.fit(self.distance_(X), y)
|
|
184
|
+
return self
|
|
185
|
+
|
|
186
|
+
def predict(self, X):
|
|
187
|
+
X = _validar_prediccion(self, X)
|
|
188
|
+
return self.classifier_.predict(self.distance_(X))
|
|
189
|
+
|
|
190
|
+
def predict_proba(self, X):
|
|
191
|
+
X = _validar_prediccion(self, X)
|
|
192
|
+
return self.classifier_.predict_proba(self.distance_(X))
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
class FermatKDE(DensityMixin, BaseEstimator):
|
|
196
|
+
"""Estimador de densidad por núcleos con distancia de Fermat muestral.
|
|
197
|
+
|
|
198
|
+
Núcleo gaussiano evaluado sobre la distancia de Fermat muestral a cada
|
|
199
|
+
observación de entrenamiento, con la normalización de la KDE euclídea en
|
|
200
|
+
dimensión `d`.
|
|
201
|
+
|
|
202
|
+
Parámetros
|
|
203
|
+
----------
|
|
204
|
+
alpha : float, por defecto 1
|
|
205
|
+
Exponente de la distancia de Fermat muestral.
|
|
206
|
+
bandwidth : float, por defecto 1
|
|
207
|
+
Ancho de banda del núcleo.
|
|
208
|
+
d : int, por defecto -1
|
|
209
|
+
Dimensión usada en la normalización; con -1, la cantidad de variables de X.
|
|
210
|
+
|
|
211
|
+
Atributos
|
|
212
|
+
---------
|
|
213
|
+
n_features_in_ : int
|
|
214
|
+
Cantidad de variables vistas en `fit`.
|
|
215
|
+
d_ : int
|
|
216
|
+
Dimensión efectiva de la normalización.
|
|
217
|
+
distance_ : SampleFermatDistance
|
|
218
|
+
Distancia ajustada a la muestra de entrenamiento.
|
|
219
|
+
"""
|
|
220
|
+
|
|
221
|
+
def __init__(self, alpha: float = 1, bandwidth: float = 1, d: int = -1):
|
|
222
|
+
self.bandwidth = bandwidth
|
|
223
|
+
self.alpha = alpha
|
|
224
|
+
self.d = d # TODO: ¿Evitar completamente? Quitando el h^-d del score?
|
|
225
|
+
|
|
226
|
+
def fit(self, X, y=None):
|
|
227
|
+
X = check_array(X)
|
|
228
|
+
self.n_features_in_ = X.shape[1]
|
|
229
|
+
self.distance_ = SampleFermatDistance(Q=X, alpha=self.alpha)
|
|
230
|
+
# `d` queda como lo pasó el usuario; la dimensión efectiva va en `d_`
|
|
231
|
+
self.d_ = self.distance_.D if self.d == -1 else self.d
|
|
232
|
+
return self
|
|
233
|
+
|
|
234
|
+
def __setstate__(self, state):
|
|
235
|
+
# Los pickles anteriores a `d_` guardaban la dimensión efectiva en `d`
|
|
236
|
+
if "distance_" in state and "d_" not in state:
|
|
237
|
+
state["d_"] = state["d"]
|
|
238
|
+
super().__setstate__(state)
|
|
239
|
+
|
|
240
|
+
def score_samples(self, X=None, log=True):
|
|
241
|
+
"""Log-densidad (o densidad, con `log=False`) en cada fila de X.
|
|
242
|
+
|
|
243
|
+
Sin X, evalúa en la propia muestra de entrenamiento.
|
|
244
|
+
"""
|
|
245
|
+
if X is None:
|
|
246
|
+
check_is_fitted(self)
|
|
247
|
+
distancias = self.distance_.A[0]
|
|
248
|
+
else:
|
|
249
|
+
distancias = self.distance_(_validar_prediccion(self, X))
|
|
250
|
+
puntaje = np.exp(-0.5 * (distancias / self.bandwidth) ** 2).sum(1)
|
|
251
|
+
if log:
|
|
252
|
+
# En la cola profunda `puntaje` es 0: log(0) = -inf, que recorta el máximo
|
|
253
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
254
|
+
return (
|
|
255
|
+
-np.log(self.distance_.N)
|
|
256
|
+
- self.d_ * np.log(self.bandwidth)
|
|
257
|
+
- self.d_ / 2 * np.log(2 * np.pi)
|
|
258
|
+
+ np.maximum(np.log(puntaje), MIN_PUNTAJE_LOG)
|
|
259
|
+
)
|
|
260
|
+
else:
|
|
261
|
+
return (
|
|
262
|
+
self.distance_.N**-1
|
|
263
|
+
* (self.bandwidth**-self.d_)
|
|
264
|
+
* (2 * np.pi) ** (-self.d_ / 2)
|
|
265
|
+
* puntaje
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def score(self, X=None, y=None):
|
|
269
|
+
"""Log-verosimilitud total de X (o de la muestra de entrenamiento)."""
|
|
270
|
+
return self.score_samples(X).sum()
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class DistanciaEuclidea:
|
|
274
|
+
"""Distancia euclídea con la interfaz mínima de `SampleFermatDistance`.
|
|
275
|
+
|
|
276
|
+
Usa `euclidean.func`, el cómputo exacto con `cdist`/`pdist` sin el caché en disco:
|
|
277
|
+
los valores son bit a bit los que se cachean y `dir_cache` no crece.
|
|
278
|
+
"""
|
|
279
|
+
|
|
280
|
+
def __init__(self, Q):
|
|
281
|
+
self.Q = Q
|
|
282
|
+
self.N, self.D = Q.shape
|
|
283
|
+
|
|
284
|
+
@property
|
|
285
|
+
def A(self):
|
|
286
|
+
# Solo para `score_samples(X=None)`: distancias de Q contra sí misma
|
|
287
|
+
return {0: euclidean.func(self.Q)}
|
|
288
|
+
|
|
289
|
+
def __call__(self, X, Y=None):
|
|
290
|
+
if X.ndim == 1: # en caso de que lo llamen con una sola observación
|
|
291
|
+
X = X.reshape(1, self.D)
|
|
292
|
+
return euclidean.func(X, self.Q if Y is None else Y)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
class EuclideanKDE(FermatKDE):
|
|
296
|
+
"""Estimador de densidad por núcleos euclídeo exacto (fuerza bruta).
|
|
297
|
+
|
|
298
|
+
Alternativa a `sklearn.neighbors.KernelDensity`, cuyo recorrido del árbol
|
|
299
|
+
(KDTree/BallTree) devuelve log-densidades erróneas en la cola profunda: puntos
|
|
300
|
+
dentro de la caja que envuelve a una clase pero lejos de todas sus observaciones.
|
|
301
|
+
Hereda `score_samples` de `FermatKDE` (la suma exacta de núcleos sobre la matriz de
|
|
302
|
+
distancias, con la misma normalización y el mismo recorte), de modo que
|
|
303
|
+
`KDClassifier(metric="euclidea_exacta")` coincide bit a bit con
|
|
304
|
+
`KDClassifier(metric="fermat", alpha=1)`.
|
|
305
|
+
|
|
306
|
+
Parámetros
|
|
307
|
+
----------
|
|
308
|
+
bandwidth : float, por defecto 1
|
|
309
|
+
Ancho de banda del núcleo.
|
|
310
|
+
d : int, por defecto -1
|
|
311
|
+
Dimensión usada en la normalización; con -1, la cantidad de variables de X.
|
|
312
|
+
"""
|
|
313
|
+
|
|
314
|
+
def __init__(self, bandwidth: float = 1, d: int = -1):
|
|
315
|
+
# Sin `alpha`: no es parámetro de este estimador
|
|
316
|
+
self.bandwidth = bandwidth
|
|
317
|
+
self.d = d
|
|
318
|
+
|
|
319
|
+
def fit(self, X, y=None):
|
|
320
|
+
X = check_array(X)
|
|
321
|
+
self.n_features_in_ = X.shape[1]
|
|
322
|
+
self.distance_ = DistanciaEuclidea(X)
|
|
323
|
+
self.d_ = self.distance_.D if self.d == -1 else self.d
|
|
324
|
+
return self
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
class KDClassifier(ClassifierMixin, BaseEstimator):
|
|
328
|
+
"""Clasificador por densidad de núcleos: regla de Bayes con una KDE por clase.
|
|
329
|
+
|
|
330
|
+
Estima la densidad de cada clase con una KDE y asigna la clase de máxima
|
|
331
|
+
probabilidad a posteriori, con las proporciones de entrenamiento como previas.
|
|
332
|
+
|
|
333
|
+
Parámetros
|
|
334
|
+
----------
|
|
335
|
+
bandwidth : float, por defecto 1.0
|
|
336
|
+
Ancho de banda común a todas las clases.
|
|
337
|
+
metric : str, por defecto "euclidean"
|
|
338
|
+
`"fermat"` usa `FermatKDE` con `alpha`; `"euclidea_exacta"` usa
|
|
339
|
+
`EuclideanKDE`; cualquier otro valor se pasa a
|
|
340
|
+
`sklearn.neighbors.KernelDensity`, sin `metric_params`.
|
|
341
|
+
alpha : float, por defecto 1.0
|
|
342
|
+
Exponente de la distancia de Fermat; solo se usa con `metric="fermat"`.
|
|
343
|
+
|
|
344
|
+
Atributos
|
|
345
|
+
---------
|
|
346
|
+
classes_ : ndarray
|
|
347
|
+
Etiquetas de clase.
|
|
348
|
+
n_features_in_ : int
|
|
349
|
+
Cantidad de variables vistas en `fit`.
|
|
350
|
+
models_ : list
|
|
351
|
+
Una KDE ajustada por clase, en el orden de `classes_`.
|
|
352
|
+
logpriors_ : list of float
|
|
353
|
+
Logaritmo de la proporción de cada clase en el entrenamiento.
|
|
354
|
+
"""
|
|
355
|
+
|
|
356
|
+
def __init__(self, bandwidth=1.0, metric="euclidean", alpha=1.0):
|
|
357
|
+
self.bandwidth = bandwidth
|
|
358
|
+
self.metric = metric
|
|
359
|
+
self.alpha = alpha
|
|
360
|
+
|
|
361
|
+
def fit(self, X, y):
|
|
362
|
+
X, y = check_X_y(X, y)
|
|
363
|
+
self.classes_ = unique_labels(y)
|
|
364
|
+
self.n_features_in_ = X.shape[1]
|
|
365
|
+
conjuntos_entrenamiento = [X[y == yi] for yi in self.classes_]
|
|
366
|
+
if self.metric == "fermat":
|
|
367
|
+
fabrica_densidad = partial(FermatKDE, alpha=self.alpha)
|
|
368
|
+
elif self.metric == "euclidea_exacta":
|
|
369
|
+
# KDE euclídea exacta; "euclidean" sigue usando `KernelDensity`, como en la
|
|
370
|
+
# tesis, para que sus números y figuras se reproduzcan tal cual
|
|
371
|
+
fabrica_densidad = EuclideanKDE
|
|
372
|
+
else:
|
|
373
|
+
fabrica_densidad = partial(KernelDensity, metric=self.metric)
|
|
374
|
+
self.models_ = [
|
|
375
|
+
fabrica_densidad(bandwidth=self.bandwidth).fit(Xi)
|
|
376
|
+
for Xi in conjuntos_entrenamiento
|
|
377
|
+
]
|
|
378
|
+
self.logpriors_ = [
|
|
379
|
+
np.log(Xi.shape[0] / X.shape[0]) for Xi in conjuntos_entrenamiento
|
|
380
|
+
]
|
|
381
|
+
return self
|
|
382
|
+
|
|
383
|
+
def predict_proba(self, X):
|
|
384
|
+
X = _validar_prediccion(self, X)
|
|
385
|
+
# Las log-densidades pueden ser -inf (cola profunda); el recorte las acota
|
|
386
|
+
with np.errstate(divide="ignore", invalid="ignore"):
|
|
387
|
+
logpuntajes = np.array(
|
|
388
|
+
[modelo.score_samples(X) for modelo in self.models_]
|
|
389
|
+
).T
|
|
390
|
+
logprobs = (logpuntajes + self.logpriors_).clip(
|
|
391
|
+
MIN_PUNTAJE_LOG, MAX_PUNTAJE_LOG
|
|
392
|
+
)
|
|
393
|
+
# Tomo factor común de la máxima logprob para evitar problemas numéricos
|
|
394
|
+
deltas = logprobs - logprobs.max(axis=1, keepdims=True)
|
|
395
|
+
resultado = np.exp(deltas)
|
|
396
|
+
return resultado / resultado.sum(axis=1, keepdims=True)
|
|
397
|
+
|
|
398
|
+
def predict(self, X):
|
|
399
|
+
probas = self.predict_proba(X) # antes que `classes_`: valida que esté ajustado
|
|
400
|
+
return self.classes_[np.argmax(probas, 1)]
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "fkdc"
|
|
3
|
+
version = "0.1.1"
|
|
4
|
+
description = "Distancia de Fermat en Clasificadores de Densidad por Núcleos"
|
|
5
|
+
authors = [{name = "Gonzalo Barrera Borla", email = "gonzalobb@gmail.com"}]
|
|
6
|
+
license = "MIT"
|
|
7
|
+
license-files = ["LICENSE"]
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
keywords = [
|
|
11
|
+
"fermat distance",
|
|
12
|
+
"kernel density estimation",
|
|
13
|
+
"kernel density classifier",
|
|
14
|
+
"k-nearest neighbors",
|
|
15
|
+
"manifold learning",
|
|
16
|
+
"scikit-learn",
|
|
17
|
+
]
|
|
18
|
+
classifiers = [
|
|
19
|
+
"Development Status :: 3 - Alpha",
|
|
20
|
+
"Intended Audience :: Science/Research",
|
|
21
|
+
"Natural Language :: Spanish",
|
|
22
|
+
"Operating System :: OS Independent",
|
|
23
|
+
"Programming Language :: Python :: 3",
|
|
24
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
25
|
+
"Programming Language :: Python :: 3.11",
|
|
26
|
+
"Programming Language :: Python :: 3.12",
|
|
27
|
+
"Programming Language :: Python :: 3.13",
|
|
28
|
+
"Programming Language :: Python :: 3.14",
|
|
29
|
+
"Topic :: Scientific/Engineering :: Mathematics",
|
|
30
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
31
|
+
]
|
|
32
|
+
dependencies = [
|
|
33
|
+
"joblib>=1.2.0",
|
|
34
|
+
"numpy>=1.26.4",
|
|
35
|
+
"scipy>=1.12.0",
|
|
36
|
+
"scikit-learn>=1.4.1.post1",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/capitantoto/fermat"
|
|
41
|
+
Repository = "https://github.com/capitantoto/fermat"
|
|
42
|
+
Issues = "https://github.com/capitantoto/fermat/issues"
|
|
43
|
+
|
|
44
|
+
[dependency-groups]
|
|
45
|
+
clasicos = [
|
|
46
|
+
"stochtree>=0.4.5",
|
|
47
|
+
]
|
|
48
|
+
dev = [
|
|
49
|
+
"ruff>=0.1.0",
|
|
50
|
+
"pre-commit>=3.6.2",
|
|
51
|
+
"ipykernel>=6.29.3",
|
|
52
|
+
"matplotlib>=3.10.7",
|
|
53
|
+
"nbstripout>=0.9.1",
|
|
54
|
+
]
|
|
55
|
+
fundacionales = [
|
|
56
|
+
"gliner2>=2.0.0",
|
|
57
|
+
"laya>=0.3.22",
|
|
58
|
+
"peft>=0.21.2",
|
|
59
|
+
"tabpfn>=9.0.0",
|
|
60
|
+
"tabpfn-client>=0.6.1",
|
|
61
|
+
]
|
|
62
|
+
investigacion = [
|
|
63
|
+
"pandas>=2.2.1",
|
|
64
|
+
"seaborn>=0.13.2",
|
|
65
|
+
"ucimlrepo>=0.0.7",
|
|
66
|
+
"tabulate>=0.9.0",
|
|
67
|
+
"click>=8.1.7",
|
|
68
|
+
"typer>=0.12.5",
|
|
69
|
+
]
|
|
70
|
+
profundos = [
|
|
71
|
+
"pytabkit>=1.7.3",
|
|
72
|
+
"tabdpt>=1.3.1",
|
|
73
|
+
"tabicl>=2.2.0",
|
|
74
|
+
]
|
|
75
|
+
|
|
76
|
+
[tool.uv]
|
|
77
|
+
# `uv sync` instala también lo que usa la investigación (campañas, figuras, scripts)
|
|
78
|
+
default-groups = ["dev", "investigacion"]
|
|
79
|
+
|
|
80
|
+
[build-system]
|
|
81
|
+
requires = ["hatchling>=1.27"]
|
|
82
|
+
build-backend = "hatchling.build"
|
|
83
|
+
|
|
84
|
+
# La biblioteca publicada es solo el núcleo (`fkdc.fermat`); el resto del paquete es
|
|
85
|
+
# código de la tesis y se usa desde el repositorio (instalación editable de `uv sync`)
|
|
86
|
+
[tool.hatch.build.targets.wheel]
|
|
87
|
+
only-include = ["fkdc/__init__.py", "fkdc/fermat.py"]
|
|
88
|
+
|
|
89
|
+
[tool.hatch.build.targets.sdist]
|
|
90
|
+
only-include = [
|
|
91
|
+
"fkdc/__init__.py",
|
|
92
|
+
"fkdc/fermat.py",
|
|
93
|
+
"LICENSE",
|
|
94
|
+
"README.md",
|
|
95
|
+
"pyproject.toml",
|
|
96
|
+
]
|
|
97
|
+
|
|
98
|
+
[tool.ruff]
|
|
99
|
+
target-version = "py311"
|
|
100
|
+
extend-include = ["*.ipynb"]
|
|
101
|
+
|
|
102
|
+
[tool.ruff.lint]
|
|
103
|
+
select = [
|
|
104
|
+
"E", # pycodestyle errors
|
|
105
|
+
"W", # pycodestyle warnings
|
|
106
|
+
"F", # pyflakes
|
|
107
|
+
"I", # isort
|
|
108
|
+
"B", # flake8-bugbear
|
|
109
|
+
"C4", # flake8-comprehensions
|
|
110
|
+
"UP", # pyupgrade
|
|
111
|
+
]
|