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)