from scipy.stats import multivariate_normal
from scipy.special import logsumexp
import numpy as np
Apéndice B — Código
El objetivo de este apéndice es describir algunas de las clases y métodos de Python utilizadas en el curso.
Paquetes usados
B.1 Clasificador Bayesiano Gausiano
class GaussianBayes(object):
def __init__(self, naive=False) -> None:
self._naive = naive
@property
def naive(self):
return self._naive
@property
def labels(self):
return self._labels
@labels.setter
def labels(self, labels):
self._labels = labels
B.1.1 Estimación de Parámetros
def fit(self, X, y):
self.prior = y
self.likelihood = (X, y)
return self
@property
def prior(self):
return self._prior
@prior.setter
def prior(self, y):
= np.unique(y, return_counts=True)
labels, counts = counts / counts.sum()
prior self.labels = labels
self._prior = np.log(prior)
@property
def likelihood(self):
return self._likelihood
@likelihood.setter
def likelihood(self, D):
= D
X, y = []
likelihood for k in self.labels:
= y == k
mask = np.mean(X[mask], axis=0)
mu if self.naive:
= np.var(X[mask], axis=0, ddof=1)
cov else:
= np.cov(X[mask], rowvar=False)
cov = multivariate_normal(mean=mu,
_ =cov,
cov=True)
allow_singular
likelihood.append(_)self._likelihood = likelihood
B.1.2 Predicción
def predict(self, X):
= self.predict_log_proba(X)
hy = np.argmax(hy, axis=1)
_ return self.labels[_]
def predict_proba(self, X):
= self.predict_log_proba(X)
_ return np.exp(_)
def predict_log_proba(self, X):
= np.vstack([m.logpdf(X)
log_ll for m in self.likelihood]).T
= self.prior
prior = log_ll + prior
posterior = np.atleast_2d(logsumexp(posterior,
evidence =1)).T
axisreturn posterior - evidence
B.1.3 Uso
= GaussianBayes().fit(T, y_t)
bayes = bayes.predict(G) hy