开始使用免费开始使用

NMF 学习图像的"部分"

现在,请运用您对 NMF 的所学来分解手写数字数据集。您再次得到了作为 2D 数组的数字图像 samples。这一次,还提供了一个函数 show_as_image(),它可以显示任何 1D 数组所编码的图像:

def show_as_image(sample):
    bitmap = sample.reshape((13, 8))
    plt.figure()
    plt.imshow(bitmap, cmap='gray', interpolation='nearest')
    plt.colorbar()
    plt.show()

完成后,请花点时间查看这些图,并留意 NMF 如何将一个数字表示为各个组件之和!

本练习是课程的一部分

Python 中的无监督学习

查看课程

练习说明

  • sklearn.decomposition 导入 NMF
  • 创建名为 model、包含 7 个组件的 NMF 实例。(7 是 LED 显示屏的单元个数。)
  • model 调用 .fit_transform() 方法,传入 samples。将结果赋值给 features
  • 对模型的每个组件(通过 model.components_ 访问),在循环内对该组件调用 show_as_image() 函数。
  • features 的第 0 行赋值给 digit_features
  • 打印 digit_features

交互式实操练习

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

# Import NMF
____

# Create an NMF model: model
model = ____

# Apply fit_transform to samples: features
features = ____

# Call show_as_image on each component
for component in model.components_:
    ____

# Select the 0th row of features: digit_features
digit_features = ____

# Print digit_features
print(digit_features)
编辑并运行代码