NMFは画像を部分に分解して学習します
これまでに学んだNMFを使って、digitsデータセットを分解してみましょう。手書き数字の画像は、今回も2次元配列 samples として与えられています。さらに、任意の1次元配列が表す画像を表示する関数 show_as_image() も用意されています。
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をインポートします。7個のコンポーネントを持つNMFインスタンスmodelを作成します。(7 はLEDディスプレイのセル数です)。modelの.fit_transform()メソッドをsamplesに適用し、結果をfeaturesに代入します。- モデルの各コンポーネント(
model.components_でアクセス)に対して、ループ内でそのコンポーネントをshow_as_image()に渡して表示します。 featuresの行0をdigit_featuresに代入します。digit_featuresを出力(print)します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
# 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)