fisher判据分类数据的python代码
时间: 2023-12-04 10:05:46 浏览: 25
Sure, here is the Python code for Fisher's discriminant for classifying data:
```
import numpy as np
def fisher_discriminant(X, y):
"""
Fisher's linear discriminant for binary classification.
Arguments:
X: numpy array of shape (n_samples, n_features)
y: numpy array of shape (n_samples,)
Class labels, assumed to be binary (0 or 1).
Returns:
w: numpy array of shape (n_features,)
The weights for the linear discriminant function.
"""
# compute means of each class
mu0 = np.mean(X[y==0], axis=0)
mu1 = np.mean(X[y==1], axis=0)
# compute between-class scatter matrix
Sb = np.outer(mu1 - mu0, mu1 - mu0)
# compute within-class scatter matrix
Sw = np.zeros((X.shape[1], X.shape[1]))
for i in range(2):
Xi = X[y==i]
si = np.cov(Xi, rowvar=False)
Sw += (Xi.shape[0] - 1) * si
# solve the generalized eigenvalue problem for Sb and Sw
eigvals, eigvecs = np.linalg.eig(np.linalg.inv(Sw).dot(Sb))
# find the eigenvector with the largest eigenvalue
w = eigvecs[:, np.argmax(eigvals)]
return w
```
Hope this helps!