开始使用免费开始使用

第一个主成分

数据的第一个主成分是数据方差最大的一条方向。在本练习中,您的任务是使用 PCA 找到谷物样本长度和宽度测量的第一个主成分,并把它作为箭头显示在散点图上。

数组 grains 给出了谷物样本的长度和宽度。PyPlot(plt)和 PCA 已为您导入。

本练习是课程的一部分

Python 中的无监督学习

查看课程

练习说明

  • 绘制谷物测量值的散点图。此步骤已为您完成。
  • 创建名为 modelPCA 实例。
  • 将模型拟合到 grains 数据。
  • 使用 model.mean_ 属性提取数据的均值坐标。
  • 使用 .components_[0,:] 获取 model 的第一个主成分。
  • 使用 plt.arrow() 函数在散点图上绘制第一个主成分为箭头。您需要指定前两个参数 mean[0]mean[1]

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Make a scatter plot of the untransformed points
plt.scatter(grains[:,0], grains[:,1])

# Create a PCA instance: model
model = ____

# Fit model to points
____

# Get the mean of the grain samples: mean
mean = ____

# Get the first principal component: first_pc
first_pc = ____

# Plot first_pc as an arrow, starting at mean
plt.arrow(____, ____, first_pc[0], first_pc[1], color='red', width=0.01)

# Keep axes on same scale
plt.axis('equal')
plt.show()
编辑并运行代码