python实现LDA线性判别分析
时间: 2023-07-07 14:34:45 浏览: 104
LDA(Linear Discriminant Analysis)是一种常见的分类算法,可以用于数据降维和特征选择。Python中可以使用Scikit-learn库来实现LDA算法。下面是一个简单的示例代码:
首先需要导入相关的库:
```python
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
```
接着生成一些样本数据,使用make_classification函数:
```python
X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=123)
```
将数据集划分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)
```
创建LDA模型并进行训练:
```python
lda = LinearDiscriminantAnalysis()
lda.fit(X_train, y_train)
```
使用模型对测试集进行预测,并计算准确率:
```python
y_pred = lda.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
完整代码如下:
```python
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 生成样本数据
X, y = make_classification(n_samples=1000, n_features=10, n_classes=2, random_state=123)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=123)
# 创建LDA模型并训练
lda = LinearDiscriminantAnalysis()
lda.fit(X_train, y_train)
# 预测测试集并计算准确率
y_pred = lda.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
阅读全文