CodeLibrary/03_pycharm_python_coursework_20240427/pca.py

20 lines
480 B
Python
Raw Normal View History

import numpy as np
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
from sklearn.datasets import load_iris
# 加载数据
iris = load_iris()
x = iris.data
# 执行 PCA
pca = PCA(n_components=2)
x_reduced = pca.fit_transform(x)
# 绘制结果
plt.figure(figsize=(10, 5))
plt.scatter(x_reduced[:, 0], x_reduced[:, 1], c=iris.target)
plt.xlabel('First Principal Component')
plt.ylabel('Second Principal Component')
plt.title('PCA of Iris Dataset')
plt.show()