-
Notifications
You must be signed in to change notification settings - Fork 1
/
HC-DBSCAN_toy_benchmarks.py
197 lines (172 loc) · 6.94 KB
/
HC-DBSCAN_toy_benchmarks.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
#
# author: Jongwon Kim (pioneer0517@postech.ac.kr)
# last updated: June 02, 2022
#
#%%
from HCDBSCAN import core
from HCDBSCAN import preprocessing
from HCDBSCAN import benchmarks
from HCDBSCAN.clustering import DBSCAN
from HCDBSCAN.clustering import evaluation_metric
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import time
import argparse
hyp_dict = {
"eps" : 0.5,
"min_samples" : 5
}
def main(data_name = 'mnist',n_iter=10):
# Load and preprocess the MNIST dataset
train_data0, train_labels = preprocessing.import_data(data=data_name,size=3000)
show_data = train_data0
if data_name != "reuters":
if train_data0.shape[1]>10 :
train_data = preprocessing.embedding_data(train_data = train_data0,n_components = round(np.sqrt(train_data0.shape[1]+1)) )
else :
train_data = preprocessing.embedding_data(train_data = train_data0,n_components = round(np.sqrt(train_data0.shape[1]+1)) )
else :
train_data = train_data0
scaler = MinMaxScaler()
scaler.fit(train_data)
train_data = scaler.transform(train_data)
scaler2 = MinMaxScaler()
scaler2.fit(show_data)
show_data = scaler2.transform(show_data)
# Define constraint functions
def constraint_CL(idx1,idx2):
def constraint_function_CL(cluster_data):
labels = cluster_data.labels_
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
# Feasible solution = negative value
C_score = - np.double(labels[idx1]==labels[idx2])+1
return C_score
return constraint_function_CL
#n_labels = len(np.unique(train_labels))
n_labels = 6
def constraint_function1(cluster_data):
labels = cluster_data.labels_
n_clusters = len(set(labels)) - (1 if -1 in labels else 0)
# Feasible solution = negative value
C_score = - min(int(n_labels *1.0) - n_clusters , n_clusters - int(n_labels*1.0))
return C_score
constraint_function_list = [constraint_function1]
# Define HC-DBSCAN function's input parameters
label_max = max(np.unique(train_labels,return_counts=True)[1])
bounds = np.array( [[0.0001,1],[2,train_data.shape[1]*np.round(np.log10(train_data.shape[0])) ]])
ADMMBO_dict = {
"data_name" : data_name,
"train_data" : train_data,
"show_data" : show_data,
"train_labels" : train_labels,
"rho" : 10,
"M" : 100,
"n_max" : 0,
"n_min" : 0,
"ele_max" : label_max,
"n_init" : 20,
"n_iter" : n_iter,
"n_test" : 500,
"str_cov" : 'se',
"str_initial_method_bo" : 'uniform',
"seed" : 0,
"clustering_method" : 'dbscan',
"metric_method" : 'davies_bouldin_score',
"hyp_dict" : hyp_dict,
"bounds" : bounds,
"integer_var" : [1],
"hyperparamter_optimization" : "ADMMBO",
"constraint":'Soft',
"acquisition_function":"EI",
"alpha" : 2,
"beta" : 2,
"constraint_function_list" :constraint_function_list,
'initial_index':0
}
HPO_list = [core.HC_DBSCAN, benchmarks.RS_, benchmarks.Grid_, benchmarks.BO_ ]
HPO_list_name = ['HC-DBSCAN','RS','Grid','BO']
Best_X_list = []
Best_label_list = []
NMI_val_list=[]
for idx, HPO in enumerate(HPO_list):
if idx==1:
ADMMBO_dict['n_iter'] = ADMMBO_dict['n_iter'] *( ADMMBO_dict['alpha']+ len(constraint_function_list)*ADMMBO_dict['beta']) + ADMMBO_dict['n_init']
if idx==3:
ADMMBO_dict['n_iter'] = ADMMBO_dict['n_iter'] - ADMMBO_dict['n_init']
X_train, F_train, C_train, real_C_train,NMI_tain,Y_train = HPO(**ADMMBO_dict)
C_train = (np.array(C_train)>0)*10
#print(F_train.shape)
#print(C_train.shape)
#print(np.sum(C_train,axis=0).shape)
F_train = F_train + np.sum(C_train,axis=0)
#print("num : "+ str(len(X_train)))
#print("min : "+str(np.min(F_train)) )
best_hyperparameter = X_train[np.argmin(F_train)]
hyp_key = hyp_dict.keys()
for idx_, key in enumerate(hyp_key):
hyp_dict[key] = best_hyperparameter[idx_]
cluster = DBSCAN.clustering(clustering_method = ADMMBO_dict['clustering_method'], hyp_dict= hyp_dict)
cluster_data = cluster.fit(train_data)
labels = cluster_data.labels_
NMI_value = evaluation_metric.metric(train_data,labels,train_labels,metric_method='normalized_mutual_info_score')
Best_X_list.append(best_hyperparameter)
NMI_val_list.append(NMI_value)
Best_label_list.append(labels)
n_labels = len(labels)
# Plot the image
color_list = ['lightcoral','pink','r','y','g','c','b','m','green','navy']
fig = plt.figure()
for i in range(10):
idx = (train_labels==i)
plt.scatter(show_data[idx,0],show_data[idx,1],alpha=0.3,color=color_list[i])
plt.title(data_name +" dataset")
plt.show()
plt.close(fig)
fig = plt.figure(figsize=(10,8))
for idx, labels in enumerate(Best_label_list):
plt.subplot(2,2,idx+1)
plt.legend()
# plt.xlim(-2,16)
# plt.ylim(-2,12)
labels = Best_label_list[idx]
n_clusters_res = len(set(labels)) - (1 if -1 in labels else 0)
n_labels = len(np.unique(labels))
for i in range(-1,n_labels):
idx_list = (labels==i)
if n_labels == n_clusters_res:
plt.scatter(show_data[idx_list,0],show_data[idx_list,1],alpha=0.05)
else:
plt.scatter(show_data[idx_list,0],show_data[idx_list,1],alpha=0.05,color='gray')
plt.title(HPO_list_name[idx] +" for "+ data_name + " with # of cluster:" +str(len(set(labels)) - (1 if -1 in labels else 0)))
plt.show()
plt.close(fig)
for idx, labels in enumerate(Best_label_list):
plt.figure(figsize=(8,5))
#plt.legend()
# plt.xlim(-2,16)
# plt.ylim(-2,12)
labels = Best_label_list[idx]
n_clusters_res = len(set(labels)) - (1 if -1 in labels else 0)
n_labels = len(np.unique(labels))
for i in range(-1,n_labels):
idx_list = (labels==i)
if 6 == n_clusters_res:
plt.scatter(show_data[idx_list,0],show_data[idx_list,1])
else:
plt.scatter(show_data[idx_list,0],show_data[idx_list,1],color='gray')
#plt.title(HPO_list_name[idx] +" for "+ data_name + " with # of cluster:" +str(len(set(labels)) - (1 if -1 in labels else 0)))
plt.show()
plt.close(fig)
#%%
main("toy8", 30)
#%%
plt.figure(figsize=(8,5))
plt.scatter([1,2,3],[4,5,6],color='gray')
#%%
parser = argparse.ArgumentParser()
parser.add_argument('--data_name', type=str, default='mnist')
parser.add_argument('--n_iter', type=int, default=10)
args = parser.parse_args()
if __name__ == "__main__":
main(args.data_name, args.n_iter)