NMF learns the parts of images
Now use what you've learned about NMF to decompose the digits dataset. You are again given the digit images as a 2D array samples
. This time, you are also provided with a function show_as_image()
that displays the image encoded by any 1D array:
def show_as_image(sample):
bitmap = sample.reshape((13, 8))
plt.figure()
plt.imshow(bitmap, cmap='gray', interpolation='nearest')
plt.colorbar()
plt.show()
After you are done, take a moment to look through the plots and notice how NMF has expressed the digit as a sum of the components!
This exercise is part of the course
Unsupervised Learning in Python
Exercise instructions
- Import
NMF
fromsklearn.decomposition
. - Create an
NMF
instance calledmodel
with7
components. (7 is the number of cells in an LED display). - Apply the
.fit_transform()
method ofmodel
tosamples
. Assign the result tofeatures
. - To each component of the model (accessed via
model.components_
), apply theshow_as_image()
function to that component inside the loop. - Assign the row
0
offeatures
todigit_features
. - Print
digit_features
.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# 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)