WOLFRAM NOTEBOOK

Manifold Learning

Example dataset

In[]:=
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
In[]:=
def make_hello(N=1000, rseed=42):
# Make a plot with "HELLO" text; save as PNG
fig, ax = plt.subplots(figsize=(4, 1))
fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
ax.axis('off')
ax.text(0.5, 0.4, 'HELLO', va='center', ha='center', weight='bold', size=85)
fig.savefig('hello.png')
plt.close(fig)

# Open this PNG and draw random points from it
from matplotlib.image import imread
data = imread('hello.png')[::-1, :, 0].T
rng = np.random.RandomState(rseed)
X = rng.rand(4 * N, 2)
i, j = (X * data.shape).astype(int).T
mask = (data[i, j] < 1)
X = X[mask]
X[:, 0] *= (data.shape[0] / data.shape[1])
X = X[:N]
return X[np.argsort(X[:, 0])]
In[]:=
X = make_hello(1000)
In[]:=
from sklearn.metrics import pairwise_distances
D = pairwise_distances(X)
In[]:=
exampleDistanceMatrix=Normal[ExternalValue["Python","D"]];

Code

In[]:=
getCoordinates[distanceMatrix : {___ : {___Real}}, dimensions_Integer] := Normal @ ExternalEvaluate["Python", "Prolog" "from sklearn.manifold import MDSdef manifoldPoints(dim, D): model = MDS(n_components=dim, dissimilarity='precomputed', random_state=1) return model.fit_transform(D)", <| "Command" "manifoldPoints", "Arguments" {dimensions, NumericArray[distanceMatrix, "Real64"]}|>]
In[]:=
result=getCoordinates[exampleDistanceMatrix,2];
In[]:=
ListPlot[result,AspectRatioAutomatic]
Out[]=

With SetReplace

In[]:=
<<SetReplace`
In[]:=
system=SetSubstitutionSystem[FromAnonymousRules[{{0,1},{0,2},{0,3}}{{4,5},{5,4},{4,6},{6,4},{5,6},{6,5},{4,1},{5,2},{6,3},{1,6},{3,4}}],{{0,0},{0,0},{0,0}},6]
Out[]=
In[]:=
graph=CanonicalGraph@SimpleGraph@Graph[UndirectedEdge@@@system[-1]]
Out[]=
In[]:=
graphDistanceMatrix=GraphDistanceMatrix[graph];
In[]:=
graphCoordinates2=getCoordinates[graphDistanceMatrix,2];
In[]:=
Graphics[(Line@*List)@@@(graphCoordinates2#&/@List@@@EdgeList[graph])]
Out[]=
In[]:=
graphCoordinates3=getCoordinates[graphDistanceMatrix,3];
In[]:=
Graphics3D[(Line@*List)@@@(graphCoordinates3#&/@List@@@EdgeList[graph])]
Out[]=
In[]:=
system=SetSubstitutionSystem[FromAnonymousRules[{{0,1},{0,2},{0,3}}{{4,5},{5,4},{4,6},{6,4},{5,6},{6,5},{4,1},{5,2},{6,3},{1,6},{3,4}}],{{0,0},{0,0},{0,0}},7]
Out[]=
In[]:=
graph=CanonicalGraph@SimpleGraph@Graph[UndirectedEdge@@@system[-1]]
Out[]=
In[]:=
graphDistanceMatrix=GraphDistanceMatrix[graph];
In[]:=
graphCoordinates2=getCoordinates[graphDistanceMatrix,2];
Wolfram Cloud

You are using a browser not supported by the Wolfram Cloud

Supported browsers include recent versions of Chrome, Edge, Firefox and Safari.


I understand and wish to continue anyway »

You are using a browser not supported by the Wolfram Cloud. Supported browsers include recent versions of Chrome, Edge, Firefox and Safari.