Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download

📚 The CoCalc Library - books, templates and other resources

132923 views
License: OTHER
1
from sklearn.decomposition import NMF
2
import matplotlib.pyplot as plt
3
import numpy as np
4
5
from joblib import Memory
6
7
memory = Memory(cachedir="cache")
8
9
10
def plot_nmf_illustration():
11
rnd = np.random.RandomState(5)
12
X_ = rnd.normal(size=(300, 2))
13
# Add 8 to make sure every point lies in the positive part of the space
14
X_blob = np.dot(X_, rnd.normal(size=(2, 2))) + rnd.normal(size=2) + 8
15
16
nmf = NMF(random_state=0)
17
nmf.fit(X_blob)
18
X_nmf = nmf.transform(X_blob)
19
20
fig, axes = plt.subplots(1, 2, figsize=(15, 5))
21
22
axes[0].scatter(X_blob[:, 0], X_blob[:, 1], c=X_nmf[:, 0], linewidths=0,
23
s=60, cmap='viridis')
24
axes[0].set_xlabel("feature 1")
25
axes[0].set_ylabel("feature 2")
26
axes[0].set_xlim(0, 12)
27
axes[0].set_ylim(0, 12)
28
axes[0].arrow(0, 0, nmf.components_[0, 0], nmf.components_[0, 1], width=.1,
29
head_width=.3, color='k')
30
axes[0].arrow(0, 0, nmf.components_[1, 0], nmf.components_[1, 1], width=.1,
31
head_width=.3, color='k')
32
axes[0].set_aspect('equal')
33
axes[0].set_title("NMF with two components")
34
35
# second plot
36
nmf = NMF(random_state=0, n_components=1)
37
nmf.fit(X_blob)
38
39
axes[1].scatter(X_blob[:, 0], X_blob[:, 1], c=X_nmf[:, 0], linewidths=0,
40
s=60, cmap='viridis')
41
axes[1].set_xlabel("feature 1")
42
axes[1].set_ylabel("feature 2")
43
axes[1].set_xlim(0, 12)
44
axes[1].set_ylim(0, 12)
45
axes[1].arrow(0, 0, nmf.components_[0, 0], nmf.components_[0, 1], width=.1,
46
head_width=.3, color='k')
47
48
axes[1].set_aspect('equal')
49
axes[1].set_title("NMF with one component")
50
51
52
@memory.cache
53
def nmf_faces(X_train, X_test):
54
# Build NMF models with 10, 50, 100 and 500 components
55
# this list will hold the back-transformd test-data
56
reduced_images = []
57
for n_components in [10, 50, 100, 500]:
58
# build the NMF model
59
nmf = NMF(n_components=n_components, random_state=0)
60
nmf.fit(X_train)
61
# transform the test data (afterwards has n_components many dimensions)
62
X_test_nmf = nmf.transform(X_test)
63
# back-transform the transformed test-data
64
# (afterwards it's in the original space again)
65
X_test_back = np.dot(X_test_nmf, nmf.components_)
66
reduced_images.append(X_test_back)
67
return reduced_images
68
69
70
def plot_nmf_faces(X_train, X_test, image_shape):
71
reduced_images = nmf_faces(X_train, X_test)
72
73
# plot the first three images in the test set:
74
fix, axes = plt.subplots(3, 5, figsize=(15, 12),
75
subplot_kw={'xticks': (), 'yticks': ()})
76
for i, ax in enumerate(axes):
77
# plot original image
78
ax[0].imshow(X_test[i].reshape(image_shape),
79
vmin=0, vmax=1)
80
# plot the four back-transformed images
81
for a, X_test_back in zip(ax[1:], reduced_images):
82
a.imshow(X_test_back[i].reshape(image_shape), vmin=0, vmax=1)
83
84
# label the top row
85
axes[0, 0].set_title("original image")
86
for ax, n_components in zip(axes[0, 1:], [10, 50, 100, 500]):
87
ax.set_title("%d components" % n_components)
88
89