Now we compute pairwise distances between all points and add
a small amount of noise to the distance matrix. We make sure
to keep the noisy distance matrix symmetric.
# Compute pairwise Euclidean distancesdistances=euclidean_distances(X_true)# Add noise to the distancesnoise=rng.rand(n_samples,n_samples)noise=noise+noise.Tnp.fill_diagonal(noise,0)distances+=noise
Here we compute metric, non-metric, and classical MDS of the noisy distance matrix.
To make the visual comparisons easier, we rotate the original data and all MDS
solutions to their PCA axes. And flip horizontal and vertical MDS axes, if needed,
to match the original data orientation.
# Rotate the data (CMDS does not need to be rotated, it is inherently PCA-aligned)pca=PCA(n_components=2)X_true=pca.fit_transform(X_true)X_mds=pca.fit_transform(X_mds)X_nmds=pca.fit_transform(X_nmds)# Align the sign of PCsforiin[0,1]:ifnp.corrcoef(X_mds[:,i],X_true[:,i])[0,1]<0:X_mds[:,i]*=-1ifnp.corrcoef(X_nmds[:,i],X_true[:,i])[0,1]<0:X_nmds[:,i]*=-1ifnp.corrcoef(X_cmds[:,i],X_true[:,i])[0,1]<0:X_cmds[:,i]*=-1
Finally, we plot the original data and all MDS reconstructions.
fig=plt.figure(1)ax=plt.axes([0.0,0.0,1.0,1.0])s=100plt.scatter(X_true[:,0],X_true[:,1],color="navy",s=s,lw=0,label="True Position")plt.scatter(X_mds[:,0],X_mds[:,1],color="turquoise",s=s,lw=0,label="MDS")plt.scatter(X_nmds[:,0],X_nmds[:,1],color="darkorange",s=s,lw=0,label="Non-metric MDS")plt.scatter(X_cmds[:,0],X_cmds[:,1],color="lightcoral",s=s,lw=0,label="Classical MDS")plt.legend(scatterpoints=1,loc="best",shadow=False)# Plot the edgesstart_idx,end_idx=X_mds.nonzero()# a sequence of (*line0*, *line1*, *line2*), where::# linen = (x0, y0), (x1, y1), ... (xm, ym)segments=[[X_true[i,:],X_true[j,:]]foriinrange(len(X_true))forjinrange(len(X_true))]edges=distances.max()/(distances+EPSILON)*100np.fill_diagonal(edges,0)edges=np.abs(edges)lc=LineCollection(segments,zorder=0,cmap=plt.cm.Blues,norm=plt.Normalize(0,edges.max()))lc.set_array(edges.flatten())lc.set_linewidths(np.full(len(segments),0.5))ax.add_collection(lc)plt.show()
Total running time of the script: (0 minutes 0.170 seconds)