開始使用免費開始

NMF 學出影像的組成部分

現在運用你對 NMF 的所學,來分解 digits 資料集。你一樣會拿到以 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 是如何把每個數字表示成多個元件的加總!

本練習屬於課程

Unsupervised Learning in 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)
編輯並執行程式碼