Demo of OPTICS clustering algorithm
import
matplotlib.gridspec
as
gridspec
import
matplotlib.pyplot
as
plt
import
numpy
as
np
from
sklearn.cluster
import
,
(
0
)
n_points_per_cluster
=
250
C1
=
[
-
5
,
-
2
]
+
0.8
*
(
n_points_per_cluster
,
2
)
C2
=
[
4
,
-
1
]
+
0.1
*
(
n_points_per_cluster
,
2
)
C3
=
[
1
,
-
2
]
+
0.2
*
(
n_points_per_cluster
,
2
)
C4
=
[
-
2
,
3
]
+
0.3
*
(
n_points_per_cluster
,
2
)
C5
=
[
3
,
-
2
]
+
1.6
*
(
n_points_per_cluster
,
2
)
C6
=
[
5
,
6
]
+
2
*
(
n_points_per_cluster
,
2
)
X
=
((
C1
,
C2
,
C3
,
C4
,
C5
,
C6
))
clust
=
(
min_samples
=
50
,
xi
=
0.05
,
min_cluster_size
=
0.05
)
clust
.
fit
(
X
)
labels_050
=
(
reachability
=
clust
.
reachability_
,
core_distances
=
clust
.
core_distances_
,
ordering
=
clust
.
ordering_
,
eps
=
0.5
,
)
labels_200
=
(
reachability
=
clust
.
reachability_
,
core_distances
=
clust
.
core_distances_
,
ordering
=
clust
.
ordering_
,
eps
=
2
,
)
space
=
(
len
(
X
))
reachability
=
clust
.
reachability_
[
clust
.
ordering_
]
labels
=
clust
.
labels_
[
clust
.
ordering_
]
(
figsize
=
(
10
,
7
))
G
=
(
2
,
3
)
ax1
=
(
G
[
0
,
:])
ax2
=
(
G
[
1
,
0
])
ax3
=
(
G
[
1
,
1
])
ax4
=
(
G
[
1
,
2
])
colors
=
[
"g."
,
"r."
,
"b."
,
"y."
,
"c."
]
for
klass
,
color
in
enumerate
(
colors
):
Xk
=
space
[
labels
==
klass
]
Rk
=
reachability
[
labels
==
klass
]
ax1
.
plot
(
Xk
,
Rk
,
color
,
alpha
=
0.3
)
ax1
.
plot
(
space
[
labels
==
-
1
],
reachability
[
labels
==
-
1
],
"k."
,
alpha
=
0.3
)
ax1
.
plot
(
space
,
(
space
,
2.0
,
dtype
=
float
),
"k-"
,
alpha
=
0.5
)
ax1
.
plot
(
space
,
(
space
,
0.5
,
dtype
=
float
),
"k-."
,
alpha
=
0.5
)
ax1
.
set_ylabel
(
"Reachability (epsilon distance)"
)
ax1
.
set_title
(
"Reachability Plot"
)
colors
=
[
"g."
,
"r."
,
"b."
,
"y."
,
"c."
]
for
klass
,
color
in
enumerate
(
colors
):
Xk
=
X
[
clust
.
labels_
==
klass
]
ax2
.
plot
(
Xk
[:,
0
],
Xk
[:,
1
],
color
,
alpha
=
0.3
)
ax2
.
plot
(
X
[
clust
.
labels_
==
-
1
,
0
],
X
[
clust
.
labels_
==
-
1
,
1
],
"k+"
,
alpha
=
0.1
)
ax2
.
set_title
(
"Automatic Clustering
\n
OPTICS"
)
colors
=
[
"g."
,
"r."
,
"b."
,
"c."
]
for
klass
,
color
in
enumerate
(
colors
):
Xk
=
X
[
labels_050
==
klass
]
ax3
.
plot
(
Xk
[:,
0
],
Xk
[:,
1
],
color
,
alpha
=
0.3
)
ax3
.
plot
(
X
[
labels_050
==
-
1
,
0
],
X
[
labels_050
==
-
1
,
1
],
"k+"
,
alpha
=
0.1
)
ax3
.
set_title
(
"Clustering at 0.5 epsilon cut
\n
DBSCAN"
)
colors
=
[
"g."
,
"m."
,
"y."
,
"c."
]
for
klass
,
color
in
enumerate
(
colors
):
Xk
=
X
[
labels_200
==
klass
]
ax4
.
plot
(
Xk
[:,
0
],
Xk
[:,
1
],
color
,
alpha
=
0.3
)
ax4
.
plot
(
X
[
labels_200
==
-
1
,
0
],
X
[
labels_200
==
-
1
,
1
],
"k+"
,
alpha
=
0.1
)
ax4
.
set_title
(
"Clustering at 2.0 epsilon cut
\n
DBSCAN"
)
()
()
Total running time of the script: (0 minutes 1.779 seconds)
Related examples