NMF เรียนรู้ส่วนประกอบของภาพ
ลองนำความรู้เรื่อง NMF มาใช้ถอดรหัสชุดข้อมูลตัวเลข โดยจะได้รับภาพตัวเลขในรูปแบบอาร์เรย์ 2 มิติชื่อ samples และมีฟังก์ชัน show_as_image() ให้พร้อม ฟังก์ชันนี้แสดงภาพที่เข้ารหัสอยู่ในอาร์เรย์ 1 มิติใดก็ได้:
def show_as_image(sample):
bitmap = sample.reshape((13, 8))
plt.figure()
plt.imshow(bitmap, cmap='gray', interpolation='nearest')
plt.colorbar()
plt.show()
เมื่อทำเสร็จแล้ว ลองดูกราฟที่แสดงออกมาสักครู่ สังเกตว่า NMF แยกแต่ละตัวเลขออกเป็นผลรวมของ component ต่าง ๆ ได้อย่างไร!
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Unsupervised Learning ใน Python
คำแนะนำการฝึกหัด
- Import
NMFจากsklearn.decomposition - สร้าง instance ของ
NMFชื่อmodelโดยกำหนดให้มี7components (7 คือจำนวนเซกเมนต์ในจอแสดงผลแบบ LED) - เรียกใช้เมธอด
.fit_transform()ของmodelกับsamplesแล้วเก็บผลลัพธ์ไว้ในตัวแปรfeatures - ใช้ฟังก์ชัน
show_as_image()กับแต่ละ component ของโมเดล (เข้าถึงได้ผ่านmodel.components_) ภายใน loop - กำหนดให้
digit_featuresเท่ากับแถวที่0ของ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)