-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdbscan.py
138 lines (110 loc) · 4.11 KB
/
dbscan.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import os
import warnings
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from numpy import arange
from scipy.io import arff
from sklearn import cluster, metrics
from time import time
from sklearn.neighbors import NearestNeighbors
from sklearn.cluster import DBSCAN
print()
warnings.filterwarnings("ignore")
path = './clustering-benchmark/src/main/resources/datasets/artificial/'
path2 = './dataset-rapport/'
import scipy.cluster.hierarchy as shc
def load_data(dataset: str) -> np.ndarray:
databrut = arff.loadarff(open(path + dataset + ".arff", 'r'))
return np.array([[x[0], x[1]] for x in databrut[0]])
def load_data2(dataset : str) -> np.ndarray:
databrut = np.loadtxt(path2 + dataset + ".txt")
data = [[x[0],x[1]] for x in databrut]
return np.array([[f[0], f[1]] for f in data])
def compute(dataset, datanp, eps, min_samples, trace_time=False):
begin_fit_time = time()
model = DBSCAN(eps=eps, min_samples=min_samples)
model.fit(datanp)
labels = model.labels_
end_fit_time = time()
if trace_time:
print(f"Fit time for {dataset}: {end_fit_time - begin_fit_time:.2}s")
#
begin_score_davies_bouldin = time()
try:
davies_bouldin_score = metrics.davies_bouldin_score(datanp, labels)
except ValueError:
davies_bouldin_score = 0
end_score_davies_bouldin = time()
if trace_time:
print(f"Davies-Bouldin time for {dataset}: {end_score_davies_bouldin - begin_score_davies_bouldin:.2}s")
begin_score_calinski_harabasz = time()
try:
calinski_harabasz_score = metrics.calinski_harabasz_score(datanp, labels)
except ValueError:
calinski_harabasz_score = 0
end_score_calinski_harabasz = time()
if trace_time:
print(
f"Calinski-Harabasz time for {dataset}): {end_score_calinski_harabasz - begin_score_calinski_harabasz:.2}s")
begin_score_silhouette_score = time()
try:
silhouette_score = metrics.silhouette_score(datanp, labels)
except ValueError:
silhouette_score = 0
end_score_silhouette_score = time()
if trace_time:
print(
f"Silhouette time for {dataset}): {end_score_silhouette_score - begin_score_silhouette_score:.2}s")
# print(f"Davies-Bouldin score for {dataset}: {davies_bouldin_score}")
# print(f"Calinski-Harabasz score for {dataset}: {calinski_harabasz_score}")
# print(f"Silhouette score for {dataset}: {calinski_harabasz_score}")
f0 = datanp[:, 0]
f1 = datanp[:, 1]
plt.scatter(f0, f1, c=labels, s=8)
plt.title(f"{dataset}: dbscan")
os.makedirs(f"db_scan/{dataset}/", exist_ok=True)
plt.savefig(f"db_scan/{dataset}/{eps}-{min_samples}.png")
plt.clf()
return davies_bouldin_score, calinski_harabasz_score, silhouette_score,
def generate_plot(dataset, trace_time=False, max_clusters=20):
begin_load_time = time()
datanp = load_data2(dataset)
end_load_time = time()
if trace_time:
print(f"Load time for {dataset}: {end_load_time - begin_load_time:.2}s")
cluster_count = list(range(2, max_clusters))
db_all = []
ch_all = []
s_all = []
y = [1,10,20,30,80,100,200,250,300,350]
x = [50000,65000]
for eps in x:
db = []
ch = []
s = []
print(eps)
for min_samples in y:
db_s, ch_s, s_s = compute(dataset, datanp, eps, min_samples, trace_time=trace_time)
db.append(db_s)
ch.append(ch_s)
s.append(s_s)
db_all.append(db)
ch_all.append(ch)
s_all.append(s)
# Distances k plus proches voisins
# Donnees dans X
k = 5
neigh = NearestNeighbors(n_neighbors=k)
neigh.fit(datanp)
distances, indices = neigh.kneighbors(datanp)
# retirer le point " origine "
newDistances = np.asarray([np.average(distances[i][1:]) for i in range(0, distances.shape[0])])
trie = np.sort(newDistances)
plt.title(dataset + ": Moyenne de la distance aux 5 plus proches voisins")
plt.plot(trie);
plt.savefig(f"db_scan/{dataset}-db-nearest.png")
plt.show()
models = ["zz1","zz2"]
for dataset in models:
generate_plot(dataset)