scikit-learn/examples/manifold/plot_mds.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

102 lines
2.6 KiB
Python
Raw Normal View History

2012-04-26 04:31:04 +08:00
"""
=========================
Multi-dimensional scaling
=========================
2012-04-26 04:31:04 +08:00
An illustration of the metric and non-metric MDS on generated noisy data.
The reconstructed points using the metric MDS and non metric MDS are slightly
2012-06-01 16:19:52 +08:00
shifted to avoid overlapping.
2012-04-26 04:31:04 +08:00
"""
# Author: Nelle Varoquaux <nelle.varoquaux@gmail.com>
2016-04-01 08:25:31 +08:00
# License: BSD
2012-04-26 04:31:04 +08:00
import numpy as np
from matplotlib import pyplot as plt
from matplotlib.collections import LineCollection
from sklearn import manifold
from sklearn.metrics import euclidean_distances
from sklearn.decomposition import PCA
2012-04-26 04:31:04 +08:00
EPSILON = np.finfo(np.float32).eps
n_samples = 20
seed = np.random.RandomState(seed=3)
X_true = seed.randint(0, 20, 2 * n_samples).astype(float)
X_true = X_true.reshape((n_samples, 2))
# Center the data
X_true -= X_true.mean()
similarities = euclidean_distances(X_true)
# Add noise to the similarities
noise = np.random.rand(n_samples, n_samples)
2012-05-29 21:51:10 +08:00
noise = noise + noise.T
noise[np.arange(noise.shape[0]), np.arange(noise.shape[0])] = 0
similarities += noise
2013-01-17 05:54:13 +08:00
mds = manifold.MDS(
n_components=2,
max_iter=3000,
eps=1e-9,
random_state=seed,
2012-12-17 02:00:07 +08:00
dissimilarity="precomputed",
n_jobs=1,
)
2012-05-30 17:19:17 +08:00
pos = mds.fit(similarities).embedding_
2012-04-26 04:31:04 +08:00
2013-01-17 05:54:13 +08:00
nmds = manifold.MDS(
n_components=2,
metric=False,
max_iter=3000,
eps=1e-12,
dissimilarity="precomputed",
random_state=seed,
n_jobs=1,
n_init=1,
)
npos = nmds.fit_transform(similarities, init=pos)
# Rescale the data
pos *= np.sqrt((X_true**2).sum()) / np.sqrt((pos**2).sum())
npos *= np.sqrt((X_true**2).sum()) / np.sqrt((npos**2).sum())
2012-04-26 04:31:04 +08:00
# Rotate the data
2012-05-04 02:16:18 +08:00
clf = PCA(n_components=2)
X_true = clf.fit_transform(X_true)
pos = clf.fit_transform(pos)
npos = clf.fit_transform(npos)
fig = plt.figure(1)
2012-04-26 04:31:04 +08:00
ax = plt.axes([0.0, 0.0, 1.0, 1.0])
2015-10-24 01:06:53 +08:00
s = 100
plt.scatter(X_true[:, 0], X_true[:, 1], color="navy", s=s, lw=0, label="True Position")
plt.scatter(pos[:, 0], pos[:, 1], color="turquoise", s=s, lw=0, label="MDS")
plt.scatter(npos[:, 0], npos[:, 1], color="darkorange", s=s, lw=0, label="NMDS")
plt.legend(scatterpoints=1, loc="best", shadow=False)
similarities = similarities.max() / (similarities + EPSILON) * 100
np.fill_diagonal(similarities, 0)
2012-04-26 04:31:04 +08:00
# Plot the edges
start_idx, end_idx = np.where(pos)
2015-10-24 01:06:53 +08:00
# a sequence of (*line0*, *line1*, *line2*), where::
2012-04-26 04:31:04 +08:00
# linen = (x0, y0), (x1, y1), ... (xm, ym)
segments = [
2012-04-26 04:31:04 +08:00
[X_true[i, :], X_true[j, :]] for i in range(len(pos)) for j in range(len(pos))
]
2012-04-26 04:31:04 +08:00
values = np.abs(similarities)
lc = LineCollection(
segments, zorder=0, cmap=plt.cm.Blues, norm=plt.Normalize(0, values.max())
)
2012-04-26 04:31:04 +08:00
lc.set_array(similarities.flatten())
2018-07-23 15:49:01 +08:00
lc.set_linewidths(np.full(len(segments), 0.5))
2012-04-26 04:31:04 +08:00
ax.add_collection(lc)
plt.show()