python实现LDA降维
时间: 2023-07-07 16:34:46 浏览: 94
LDA(Linear Discriminant Analysis)可以用于数据降维,通常用于特征提取和可视化。Python中可以使用Scikit-learn库来实现LDA降维算法。
下面是一个简单的示例代码:
首先需要导入相关的库:
```python
from sklearn.datasets import load_iris
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import matplotlib.pyplot as plt
```
接着加载鸢尾花数据集:
```python
iris = load_iris()
X = iris.data
y = iris.target
```
创建LDA模型并进行降维:
```python
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)
```
可视化降维后的数据:
```python
colors = ['navy', 'turquoise', 'darkorange']
lw = 2
for color, i, target_name in zip(colors, [0, 1, 2], iris.target_names):
plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], color=color, alpha=.8, lw=lw,
label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of IRIS dataset')
plt.show()
```
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
import matplotlib.pyplot as plt
# 加载数据集
iris = load_iris()
X = iris.data
y = iris.target
# LDA降维
lda = LinearDiscriminantAnalysis(n_components=2)
X_r2 = lda.fit(X, y).transform(X)
# 可视化
colors = ['navy', 'turquoise', 'darkorange']
lw = 2
for color, i, target_name in zip(colors, [0, 1, 2], iris.target_names):
plt.scatter(X_r2[y == i, 0], X_r2[y == i, 1], color=color, alpha=.8, lw=lw,
label=target_name)
plt.legend(loc='best', shadow=False, scatterpoints=1)
plt.title('LDA of IRIS dataset')
plt.show()
```
运行代码后可以看到,数据已经降到了二维,同时不同类别的数据点也被可视化在了二维坐标系中。
阅读全文