r"""Fisher Discriminant Analysis Parameters ---------- X : ndarray, shape (n, d) Training samples. y : ndarray, shape (n,) Labels for training samples. p : int, optional Size of dimensionality reduction. reg : float, optional Regularization te
(X, y, p=2, reg=1e-16)
| 80 | |
| 81 | |
| 82 | def fda(X, y, p=2, reg=1e-16): |
| 83 | r"""Fisher Discriminant Analysis |
| 84 | |
| 85 | Parameters |
| 86 | ---------- |
| 87 | X : ndarray, shape (n, d) |
| 88 | Training samples. |
| 89 | y : ndarray, shape (n,) |
| 90 | Labels for training samples. |
| 91 | p : int, optional |
| 92 | Size of dimensionality reduction. |
| 93 | reg : float, optional |
| 94 | Regularization term >0 (ridge regularization) |
| 95 | |
| 96 | Returns |
| 97 | ------- |
| 98 | P : ndarray, shape (d, p) |
| 99 | Optimal transportation matrix for the given parameters |
| 100 | proj : callable |
| 101 | projection function including mean centering |
| 102 | """ |
| 103 | |
| 104 | mx = np.mean(X) |
| 105 | X -= mx.reshape((1, -1)) |
| 106 | |
| 107 | # data split between classes |
| 108 | d = X.shape[1] |
| 109 | xc = split_classes(X, y) |
| 110 | nc = len(xc) |
| 111 | |
| 112 | p = min(nc - 1, p) |
| 113 | |
| 114 | Cw = 0 |
| 115 | for x in xc: |
| 116 | Cw += np.cov(x, rowvar=False) |
| 117 | Cw /= nc |
| 118 | |
| 119 | mxc = np.zeros((d, nc)) |
| 120 | |
| 121 | for i in range(nc): |
| 122 | mxc[:, i] = np.mean(xc[i]) |
| 123 | |
| 124 | mx0 = np.mean(mxc, 1) |
| 125 | Cb = 0 |
| 126 | for i in range(nc): |
| 127 | Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * (mxc[:, i] - mx0).reshape((1, -1)) |
| 128 | |
| 129 | w, V = linalg.eig(Cb, Cw + reg * np.eye(d)) |
| 130 | |
| 131 | idx = np.argsort(w.real) |
| 132 | |
| 133 | Popt = V[:, idx[-p:]] |
| 134 | |
| 135 | def proj(X): |
| 136 | return (X - mx.reshape((1, -1))).dot(Popt) |
| 137 | |
| 138 | return Popt, proj |
| 139 |
no test coverage detected