|
| 1 | +import numpy as np |
| 2 | + |
| 3 | + |
| 4 | +class GaussianNBClassifier: |
| 5 | + def __init__(self, eps=1e-6): |
| 6 | + r""" |
| 7 | + A naive Bayes classifier for real-valued data. |
| 8 | +
|
| 9 | + Notes |
| 10 | + ----- |
| 11 | + The naive Bayes model assumes the features of each training example |
| 12 | + :math:`\mathbf{x}` are mutually independent given the example label |
| 13 | + :math:`y`: |
| 14 | +
|
| 15 | + .. math:: |
| 16 | +
|
| 17 | + P(\mathbf{x}_i \mid y_i) = \prod_{j=1}^M P(x_{i,j} \mid y_i) |
| 18 | +
|
| 19 | + where :math:`M` is the rank of the `i`th example :math:`\mathbf{x}_i` |
| 20 | + and :math:`y_i` is the label associated with the `i`th example. |
| 21 | +
|
| 22 | + Combining the conditional independence assumption with a simple |
| 23 | + application of Bayes' theorem gives the naive Bayes classification |
| 24 | + rule: |
| 25 | +
|
| 26 | + .. math:: |
| 27 | +
|
| 28 | + \hat{y} &= \arg \max_y P(y \mid \mathbf{x}) \\ |
| 29 | + &= \arg \max_y P(y) P(\mathbf{x} \mid y) \\ |
| 30 | + &= \arg \max_y P(y) \prod_{j=1}^M P(x_j \mid y) |
| 31 | +
|
| 32 | + In the final expression, the prior class probability :math:`P(y)` can |
| 33 | + be specified in advance or estimated empirically from the training |
| 34 | + data. |
| 35 | +
|
| 36 | + In the Gaussian version of the naive Bayes model, the feature |
| 37 | + likelihood is assumed to be normally distributed for each class: |
| 38 | +
|
| 39 | + .. math:: |
| 40 | +
|
| 41 | + \mathbf{x}_i \mid y_i = c, \theta \sim \mathcal{N}(\mu_c, \Sigma_c) |
| 42 | +
|
| 43 | + where :math:`\theta` is the set of model parameters: :math:`\{\mu_1, |
| 44 | + \Sigma_1, \ldots, \mu_K, \Sigma_K\}`, :math:`K` is the total number of |
| 45 | + unique classes present in the data, and the parameters for the Gaussian |
| 46 | + associated with class :math:`c`, :math:`\mu_c` and :math:`\Sigma_c` |
| 47 | + (where :math:`1 \leq c \leq K`), are estimated via MLE from the set of |
| 48 | + training examples with label :math:`c`. |
| 49 | +
|
| 50 | + Parameters |
| 51 | + ---------- |
| 52 | + eps : float |
| 53 | + A value added to the variance to prevent numerical error. Default |
| 54 | + is 1e-6. |
| 55 | +
|
| 56 | + Attributes |
| 57 | + ---------- |
| 58 | + parameters : dict |
| 59 | + Dictionary of model parameters: "mean", the `(K, M)` array of |
| 60 | + feature means under each class, "sigma", the `(K, M)` array of |
| 61 | + feature variances under each class, and "prior", the `(K,)` array of |
| 62 | + empirical prior probabilities for each class label. |
| 63 | + hyperparameters : dict |
| 64 | + Dictionary of model hyperparameters |
| 65 | + labels : :py:class:`ndarray <numpy.ndarray>` of shape `(K,)` |
| 66 | + An array containing the unique class labels for the training |
| 67 | + examples. |
| 68 | + """ |
| 69 | + self.labels = None |
| 70 | + self.hyperparameters = {"eps": eps} |
| 71 | + self.parameters = { |
| 72 | + "mean": None, # shape: (K, M) |
| 73 | + "sigma": None, # shape: (K, M) |
| 74 | + "prior": None, # shape: (K,) |
| 75 | + } |
| 76 | + |
| 77 | + def fit(self, X, y): |
| 78 | + """ |
| 79 | + Fit the model parameters via maximum likelihood. |
| 80 | +
|
| 81 | + Notes |
| 82 | + ----- |
| 83 | + The model parameters are stored in the :py:attr:`parameters` attribute. |
| 84 | + The following keys are present: |
| 85 | +
|
| 86 | + mean: :py:class:`ndarray <numpy.ndarray>` of shape `(K, M)` |
| 87 | + Feature means for each of the `K` label classes |
| 88 | + sigma: :py:class:`ndarray <numpy.ndarray>` of shape `(K, M)` |
| 89 | + Feature variances for each of the `K` label classes |
| 90 | + prior : :py:class:`ndarray <numpy.ndarray>` of shape `(K,)` |
| 91 | + Prior probability of each of the `K` label classes, estimated |
| 92 | + empirically from the training data |
| 93 | +
|
| 94 | + Parameters |
| 95 | + ---------- |
| 96 | + X : :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)` |
| 97 | + A dataset consisting of `N` examples, each of dimension `M` |
| 98 | + y: :py:class:`ndarray <numpy.ndarray>` of shape `(N,)` |
| 99 | + The class label for each of the `N` examples in `X` |
| 100 | +
|
| 101 | + Returns |
| 102 | + ------- |
| 103 | + self: object |
| 104 | + """ |
| 105 | + P = self.parameters |
| 106 | + H = self.hyperparameters |
| 107 | + |
| 108 | + self.labels = np.unique(y) |
| 109 | + |
| 110 | + K = len(self.labels) |
| 111 | + N, M = X.shape |
| 112 | + |
| 113 | + P["mean"] = np.zeros((K, M)) |
| 114 | + P["sigma"] = np.zeros((K, M)) |
| 115 | + P["prior"] = np.zeros((K,)) |
| 116 | + |
| 117 | + for i, c in enumerate(self.labels): |
| 118 | + X_c = X[y == c, :] |
| 119 | + |
| 120 | + P["mean"][i, :] = np.mean(X_c, axis=0) |
| 121 | + P["sigma"][i, :] = np.var(X_c, axis=0) + H["eps"] |
| 122 | + P["prior"][i] = X_c.shape[0] / N |
| 123 | + return self |
| 124 | + |
| 125 | + def predict(self, X): |
| 126 | + """ |
| 127 | + Use the trained classifier to predict the class label for each example |
| 128 | + in **X**. |
| 129 | +
|
| 130 | + Parameters |
| 131 | + ---------- |
| 132 | + X: :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)` |
| 133 | + A dataset of `N` examples, each of dimension `M` |
| 134 | +
|
| 135 | + Returns |
| 136 | + ------- |
| 137 | + labels : :py:class:`ndarray <numpy.ndarray>` of shape `(N)` |
| 138 | + The predicted class labels for each example in `X` |
| 139 | + """ |
| 140 | + return self.labels[self._log_posterior(X).argmax(axis=1)] |
| 141 | + |
| 142 | + def _log_posterior(self, X): |
| 143 | + r""" |
| 144 | + Compute the (unnormalized) log posterior for each class. |
| 145 | +
|
| 146 | + Parameters |
| 147 | + ---------- |
| 148 | + X: :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)` |
| 149 | + A dataset of `N` examples, each of dimension `M` |
| 150 | +
|
| 151 | + Returns |
| 152 | + ------- |
| 153 | + log_posterior : :py:class:`ndarray <numpy.ndarray>` of shape `(N, K)` |
| 154 | + Unnormalized log posterior probability of each class for each |
| 155 | + example in `X` |
| 156 | + """ |
| 157 | + K = len(self.labels) |
| 158 | + log_posterior = np.zeros((X.shape[0], K)) |
| 159 | + for i in range(K): |
| 160 | + log_posterior[:, i] = self._log_class_posterior(X, i) |
| 161 | + return log_posterior |
| 162 | + |
| 163 | + def _log_class_posterior(self, X, class_idx): |
| 164 | + r""" |
| 165 | + Compute the (unnormalized) log posterior for the label at index |
| 166 | + `class_idx` in :py:attr:`labels`. |
| 167 | +
|
| 168 | + Notes |
| 169 | + ----- |
| 170 | + Unnormalized log posterior for example :math:`\mathbf{x}_i` and class |
| 171 | + :math:`c` is:: |
| 172 | +
|
| 173 | + .. math:: |
| 174 | +
|
| 175 | + \log P(y_i = c \mid \mathbf{x}_i, \theta) |
| 176 | + &\propto \log P(y=c \mid \theta) + |
| 177 | + \log P(\mathbf{x}_i \mid y_i = c, \theta) \\ |
| 178 | + &\propto \log P(y=c \mid \theta) |
| 179 | + \sum{j=1}^M \log P(x_j \mid y_i = c, \theta) |
| 180 | +
|
| 181 | + In the Gaussian naive Bayes model, the feature likelihood for class |
| 182 | + :math:`c`, :math:`P(\mathbf{x}_i \mid y_i = c, \theta)` is assumed to |
| 183 | + be normally distributed |
| 184 | +
|
| 185 | + .. math:: |
| 186 | +
|
| 187 | + \mathbf{x}_i \mid y_i = c, \theta \sim \mathcal{N}(\mu_c, \Sigma_c) |
| 188 | +
|
| 189 | +
|
| 190 | + Parameters |
| 191 | + ---------- |
| 192 | + X: :py:class:`ndarray <numpy.ndarray>` of shape `(N, M)` |
| 193 | + A dataset of `N` examples, each of dimension `M` |
| 194 | + class_idx : int |
| 195 | + The index of the current class in :py:attr:`labels` |
| 196 | +
|
| 197 | + Returns |
| 198 | + ------- |
| 199 | + log_class_posterior : :py:class:`ndarray <numpy.ndarray>` of shape `(N,)` |
| 200 | + Unnormalized log probability of the label at index `class_idx` |
| 201 | + in :py:attr:`labels` for each example in `X` |
| 202 | + """ |
| 203 | + P = self.parameters |
| 204 | + mu = P["mean"][class_idx] |
| 205 | + prior = P["prior"][class_idx] |
| 206 | + sigsq = P["sigma"][class_idx] |
| 207 | + |
| 208 | + # log likelihood = log X | N(mu, sigsq) |
| 209 | + log_likelihood = -0.5 * np.sum(np.log(2 * np.pi * sigsq)) |
| 210 | + log_likelihood -= 0.5 * np.sum(((X - mu) ** 2) / sigsq, axis=1) |
| 211 | + return log_likelihood + np.log(prior) |
0 commit comments