from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
# 加载示例数据库 # 修正:变量名应为iris,不是irs
iris = load_iris()
X, y = iris.data, iris.target # 修正:变量名统一使用X和y
# 创建LDA模型,降维到2维
lda = LinearDiscriminantAnalysis(n_components=2)
# 拟合模型 # LDA需要同时传入特征X和标签y
X_lda = lda.fit_transform(X, y)
# 打印投影后的数据
print("LDA Projection:") # 修正:应该是LDA,不是DA
print(X_lda)
# 绘制投影后的数据
plt.scatter(X_lda[:, 0], X_lda[:, 1], c=y)
plt.xlabel('LDA Component 1')
plt.ylabel('LDA Component 2')
plt.title('LDA Projection of Iris Dataset')
plt.show()