Skip to content

Commit

Permalink
Merge pull request #64 from INGEOTEC/develop
Browse files Browse the repository at this point in the history
Rendimiento (Actividad)
  • Loading branch information
mgraffg authored Jan 14, 2025
2 parents b453855 + 75673df commit f29b612
Show file tree
Hide file tree
Showing 6 changed files with 48 additions and 9 deletions.
6 changes: 3 additions & 3 deletions .devcontainer/devcontainer.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"ghcr.io/rocker-org/devcontainer-features/quarto-cli:1":
{"installChromium": true, "installTinyTex": true, "version": "prerelease"},
"ghcr.io/rocker-org/devcontainer-features/apt-packages:1":
{"packages": "libnss3,libxss1,libasound2,libxshmfence-dev"}
},
"postCreateCommand": "pip install cython && pip install ingeoml seaborn evomsa wordcloud pandas jupyterlab umap-learn jax optax"
{"packages": "libnss3,libxss1,libasound2,libxshmfence-dev"},
"ghcr.io/devcontainers/features/conda:1": {}
}
}
1 change: 0 additions & 1 deletion _quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ book:
- capitulos/17Referencias.qmd
appendices:
- capitulos/14Estadistica.qmd
- capitulos/15Codigo.qmd
- capitulos/16ConjuntosDatos.qmd
site-url: https://ingeotec.github.io/AprendizajeComputacional
repo-url: https://github.com/INGEOTEC/AprendizajeComputacional
Expand Down
4 changes: 2 additions & 2 deletions capitulos/03Parametricos.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -416,7 +416,7 @@ El error estándar calculado con los datos mostrados en la figura anterior es `{
:::


## Clasificador Bayesiano Ingenuo
## Clasificador Bayesiano Ingenuo {#sec-cl-bayesiano-ingenuo}

Uno de los clasificadores mas utilizados, sencillo de implementar y competitivo, es el clasificador Bayesiano Ingenuo. En la @sec-model-clasificacion se asumió que la variable aleatoria $\mathcal X = (\mathcal X_1, \mathcal X_2, \ldots, \mathcal X_d)$ dado $\mathcal Y$ ($\mathcal X_{\mid \mathcal Y}$) es $\mathcal X_{\mid \mathcal Y} \sim \mathcal N(\mu_{\mathcal Y}, \Sigma_{\mathcal Y}),$ donde $\mu_{\mathcal Y} \in \mathbb R^d$, $\Sigma_{\mathcal Y} \in \mathbb R^{d \times d}$ y $f(\mathcal X_1, \mathcal X_2, \ldots, \mathcal X_d)$ es la función de densidad de probabilidad conjunta.

Expand Down Expand Up @@ -507,7 +507,7 @@ T, G, y_t, y_g = train_test_split(X, y, test_size=0.2,

### Entrenamiento

Los dos modelos que se utilizarán será el clasificador de Análisis Discriminante Cuadrático y Bayesiano Ingenuo, utilizando las clases `QuadraticDiscriminantAnalysis` y `GaussianNB` que se explica en el @sec-clasificador-bayesiano-gausiano. Las siguientes dos instrucciones inicializan estos dos clasificadores.
Los dos modelos que se utilizarán será el clasificador de Análisis Discriminante Cuadrático y Bayesiano Ingenuo, utilizando las clases `QuadraticDiscriminantAnalysis` y `GaussianNB`. Las siguientes dos instrucciones inicializan estos dos clasificadores.

```{python}
#| echo: true
Expand Down
43 changes: 42 additions & 1 deletion capitulos/04Rendimiento.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ f1 = metrics.f1_score(y_g, hy_gaussian,
#| label: tbl-performance
#| tbl-cap: Rendimiento
#| echo: false
headers = '| |$\mathcal Y=0$ | $\mathcal Y=1$|Macro|'
headers = '| |$\\mathcal Y=0$ | $\\mathcal Y=1$|Macro|'
linea = '|----------------------|----------------------|----------------------|----------------------|'
recall_f = ' | '.join([f'${x:0.4f}$' for x in recall.tolist() + [np.mean(recall)]])
precision_f = ' | '.join([f'${x:0.4f}$' for x in precision.tolist() + [np.mean(precision)]])
Expand Down Expand Up @@ -253,6 +253,47 @@ Teniendo un valor de área bajo la curva (`auc_score`) de `{python} auc_score_f`
auc_score = metrics.roc_auc_score(y_g, prob[:, 1])
```
::: {.callout-tip collapse="true"}
### Actividad
Medir el rendimiento del Clasificador Gausiano Ingenuo (@sec-cl-bayesiano-ingenuo) en el problema del del Iris (ver @sec-iris) utilizando la función $F_\beta$ (@sec-f1) variando $\beta$ entre $[0, 1],$ tal y como se muestra en la @fig-actividad-fbeta
```{python}
#| label: fig-actividad-fbeta
#| fig-cap: "Rendimiento de un Clasificador Bayesiano Ingenuo en el problema del Iris estimado mediante una validación cruzada estratificada."
#| echo: false
from sklearn.datasets import load_iris
from sklearn.metrics import recall_score, precision_score
from sklearn.model_selection import StratifiedKFold
import seaborn as sns
import pandas as pd
X, y = load_iris(return_X_y=True)
hy = np.empty_like(y)
skf = StratifiedKFold()
for tr, vs in skf.split(X, y):
gaussian = GaussianBayes().fit(X[tr], y[tr])
hy[vs] = gaussian.predict(X[vs])
beta = np.linspace(0, 1, 10)**2
pre = precision_score(y, hy, average=None)
recall = recall_score(y, hy, average=None)
num = np.atleast_2d(1 + beta).T * pre * recall
den = np.atleast_2d(beta).T * pre + recall
f1_beta = num / den
data = load_iris()
df = pd.DataFrame(np.c_[f1_beta, beta],
columns=data.target_names.tolist() + ['Beta^2'])
df.set_index('Beta^2', inplace=True)
df2 = df.melt(value_name='F-Beta', ignore_index=False,
var_name='Clase')
sns.relplot(df2.reset_index(), kind='line', x='Beta^2', hue='Clase', y='F-Beta')
```
:::
## Regresión {#sec-rendimiento-regresion}
Con respecto a regresión las siguientes funciones son utilizadas como medidas de rendimiento.
Expand Down
2 changes: 1 addition & 1 deletion capitulos/09Lineal.qmd
Original file line number Diff line number Diff line change
Expand Up @@ -475,7 +475,7 @@ En clasificación binaria (@sec-binaria) se describió que la función discrimin
$$
\begin{split}
\log \frac{\mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)}{\mathbb P(\mathcal Y=2 \mid \mathcal X=\mathbf x)} &= \frac{\mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)}{1 - \mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)}\\
\log \frac{\mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)}{\mathbb P(\mathcal Y=2 \mid \mathcal X=\mathbf x)} &= \log \frac{\mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)}{1 - \mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)}\\
&= \textsf{logit}(\mathbb P(\mathcal Y=1 \mid \mathcal X=\mathbf x)),
\end{split}
$$
Expand Down
1 change: 0 additions & 1 deletion environment.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
name: codespaces
channels:
- conda-forge
- defaults
dependencies:
- IngeoML
- seaborn
Expand Down

0 comments on commit f29b612

Please sign in to comment.