WOLFRAM NOTEBOOK

3.4 Spectral Clustering

3.4.1 Nonlinear Data Set Moons

In[]:=
session=StartExternalSession["Python"]
Out[]=
ExternalSessionObject
System: Python
EvaluationCount:
None
UUID: ff3a2578-1c61-48e1-ba9a-d1cee126afb1
Test
In[]:=
5+6
Out[]=
11
In[]:=

from numpy import array, matrix
from scipy.io import mmread, mmwrite
import numpy as np
In[]:=
from sklearn.datasets import make_moons
X, y = make_moons(n_samples=1500,noise=0.05,random_state=0)
In[]:=
mmwrite('pubi.mtx',X)
In[]:=
mmwrite('puba.mtx',[y])
In[]:=
trainX=Import["pubi.mtx"];
In[]:=
clusters=Import["puba.mtx"];
In[]:=
total=MapThread[{#1,#2}&,{trainX,First[clusters]}];
In[]:=
clust1=Select[total,#[[2]]0&];
In[]:=
clust2=Select[total,#[[2]]1&];
In[]:=
pclust1=Map[#[[1]]&,clust1];
In[]:=
pclust2=Map[#[[1]]&,clust2];
In[]:=
p0=ListPlot[{pclust1,pclust2},PlotStyle{Pink,Green}]
Out[]=
-1.0
-0.5
0.5
1.0
1.5
2.0
-0.5
0.5
1.0
In[]:=
c=FindClusters[trainX,Method{"Spectral","NeighborhoodRadius"0.047}];
In[]:=
n=Length[c]
Out[]=
3
In[]:=
ListPlot[Table[c[[i]],{i,1,n}]]
Out[]=
-1.0
-0.5
0.5
1.0
1.5
2.0
-0.5
0.5
1.0
In[]:=
c=FindClusters[trainX,2,Method"Spectral"];
In[]:=
n=Length[c]
Out[]=
2
In[]:=
ListPlot[Table[c[[i]],{i,1,n}]]
Out[]=
-1.0
-0.5
0.5
1.0
1.5
2.0
-0.5
0.5
1.0
In[]:=
index=Table[0,{i,1,1500}];
In[]:=
Do[If[MemberQ[c[[2]],trainX[[i]]],index[[i]]=1],{i,1,1500}];
In[]:=
cuki=MapThread[Flatten[{#1,#2}]&,{trainX,index}];
In[]:=
Show[{p0,ListDensityPlot[cuki,MeshNone,InterpolationOrder0,ColorFunction"SouthwestColors"],p0}]
Out[]=
In[]:=
from sklearn import cluster
spectral = cluster.SpectralClustering(n_clusters=2, eigen_solver='arpack',affinity="nearest_neighbors")
In[]:=
from sklearn.preprocessing import StandardScaler
X = StandardScaler().fit_transform(X)
spectral.fit(X)
y_pred = spectral.labels_.astype(np.int)
In[]:=
import numpy
In[]:=
from numpy import linalg as LA
In[]:=
LA.norm(y_pred-y)
Out[]=
0.

3.4.2 Image Coloring

In[]:=
img=
;
In[]:=
imgC=Colorize[img]
Out[]=
In[]:=
imgData=ImageData[img];
In[]:=
imgData[[1,2]]
Out[]=
0.619608
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.