📚 The CoCalc Library - books, templates and other resources
License: OTHER
from sklearn.decomposition import NMF1import matplotlib.pyplot as plt2import numpy as np34from joblib import Memory56memory = Memory(cachedir="cache")789def plot_nmf_illustration():10rnd = np.random.RandomState(5)11X_ = rnd.normal(size=(300, 2))12# Add 8 to make sure every point lies in the positive part of the space13X_blob = np.dot(X_, rnd.normal(size=(2, 2))) + rnd.normal(size=2) + 81415nmf = NMF(random_state=0)16nmf.fit(X_blob)17X_nmf = nmf.transform(X_blob)1819fig, axes = plt.subplots(1, 2, figsize=(15, 5))2021axes[0].scatter(X_blob[:, 0], X_blob[:, 1], c=X_nmf[:, 0], linewidths=0,22s=60, cmap='viridis')23axes[0].set_xlabel("feature 1")24axes[0].set_ylabel("feature 2")25axes[0].set_xlim(0, 12)26axes[0].set_ylim(0, 12)27axes[0].arrow(0, 0, nmf.components_[0, 0], nmf.components_[0, 1], width=.1,28head_width=.3, color='k')29axes[0].arrow(0, 0, nmf.components_[1, 0], nmf.components_[1, 1], width=.1,30head_width=.3, color='k')31axes[0].set_aspect('equal')32axes[0].set_title("NMF with two components")3334# second plot35nmf = NMF(random_state=0, n_components=1)36nmf.fit(X_blob)3738axes[1].scatter(X_blob[:, 0], X_blob[:, 1], c=X_nmf[:, 0], linewidths=0,39s=60, cmap='viridis')40axes[1].set_xlabel("feature 1")41axes[1].set_ylabel("feature 2")42axes[1].set_xlim(0, 12)43axes[1].set_ylim(0, 12)44axes[1].arrow(0, 0, nmf.components_[0, 0], nmf.components_[0, 1], width=.1,45head_width=.3, color='k')4647axes[1].set_aspect('equal')48axes[1].set_title("NMF with one component")495051@memory.cache52def nmf_faces(X_train, X_test):53# Build NMF models with 10, 50, 100 and 500 components54# this list will hold the back-transformd test-data55reduced_images = []56for n_components in [10, 50, 100, 500]:57# build the NMF model58nmf = NMF(n_components=n_components, random_state=0)59nmf.fit(X_train)60# transform the test data (afterwards has n_components many dimensions)61X_test_nmf = nmf.transform(X_test)62# back-transform the transformed test-data63# (afterwards it's in the original space again)64X_test_back = np.dot(X_test_nmf, nmf.components_)65reduced_images.append(X_test_back)66return reduced_images676869def plot_nmf_faces(X_train, X_test, image_shape):70reduced_images = nmf_faces(X_train, X_test)7172# plot the first three images in the test set:73fix, axes = plt.subplots(3, 5, figsize=(15, 12),74subplot_kw={'xticks': (), 'yticks': ()})75for i, ax in enumerate(axes):76# plot original image77ax[0].imshow(X_test[i].reshape(image_shape),78vmin=0, vmax=1)79# plot the four back-transformed images80for a, X_test_back in zip(ax[1:], reduced_images):81a.imshow(X_test_back[i].reshape(image_shape), vmin=0, vmax=1)8283# label the top row84axes[0, 0].set_title("original image")85for ax, n_components in zip(axes[0, 1:], [10, 50, 100, 500]):86ax.set_title("%d components" % n_components)878889