This repository has been archived by the owner on May 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathunsup_utils.py
237 lines (208 loc) · 8.68 KB
/
unsup_utils.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
import scipy
import numpy as np
from sklearn import mixture
from vis import plot_analysis
def select_mean_id(vals):
mn = vals[0][0]
_id = 0
for idx, val in enumerate(vals):
if val[0] < mn:
mn = val[0]
_id = idx
return _id
def unsupervised_sample_selection(
losses,
n_mixture_component,
n_mixture_select,
threshold,
covariance_type,
noise_model=None
):
losses = np.array(losses)
losses = losses.reshape(-1,1) if len(losses.shape) == 1 else losses
if noise_model is None:
noise_model = mixture.GaussianMixture(
n_components = n_mixture_component,
covariance_type = covariance_type,
tol = 1e-5,
reg_covar = 1e-5,
random_state = 1234
)
noise_model.fit(losses)
prob = noise_model.predict_proba(losses)
ret_index_list = None
for i in range(n_mixture_select):
min_class_index = noise_model.means_.argmin()
prob1 = prob[:,min_class_index]
pred = prob1 > threshold[i]
index_list = list(range(len(losses)))
np_index_list = np.array(index_list)
np_index_list = np_index_list[pred]
ret_index_list = np_index_list if ret_index_list is None else np.append(ret_index_list, np_index_list, axis=0)
noise_model.means_[min_class_index, 0] = 1000000000
ret_index_list = np.array(list(set(list(ret_index_list))))
assert len(set(list(ret_index_list))) == len(list(ret_index_list))
return ret_index_list, noise_model
def select_samples_with_GMM(
args,
dict_key,
loss_dict,
path,
bin_increment,
noise_threshold=0,
min_length_restriction=10,
max_length_restriction=150,
mode="train",
logger=None,
debug=0
):
logger.info("Sample selection from :: {}".format(dict_key))
values = loss_dict[dict_key]
all_lengths = []
loss_list = []
for val in values:
loss_list.append((val[0]))
all_lengths.append(val[1])
tota_number_of_samples = len(loss_list)
logger.info("Total number of sample : {}".format(tota_number_of_samples))
indexes, noise_model = unsupervised_sample_selection(
loss_list,
args.n_mixture_component,
args.n_mixture_select,
args.posterior_threshold,
args.covariance_type
)
tota_number_of_selected_samples = len(indexes)
logger.info("Total number of sample selected : {}".format(tota_number_of_selected_samples))
if debug:
correct_sample_cnt = 0
noisy_sample_cnt = 0
good_samples_cnt = 0
cnt = 0
selected_sentence_lengths = []
for i in indexes:
val = values[i]
if val[2] > noise_threshold:
noisy_sample_cnt += 1
else:
correct_sample_cnt += 1
cnt += 1
selected_sentence_lengths.append(val[1])
if val[1] >= min_length_restriction and val[1] <= max_length_restriction:
good_samples_cnt += 1
if tota_number_of_selected_samples != 0:
logger.info("Total Number of Noisy Samples : {} ({}%)".format(noisy_sample_cnt, round(noisy_sample_cnt/tota_number_of_selected_samples*100,2)))
logger.info("Total Number of Correct Samples : {} ({}%)".format(correct_sample_cnt, round(correct_sample_cnt/tota_number_of_selected_samples*100,2)))
logger.info("Total Number of Correct Sample in dataset : {} ({}%)".format(correct_sample_cnt, round(correct_sample_cnt/len(loss_list)*100,2)))
logger.info("Good Samples Coverage : {} ({}%)".format(good_samples_cnt, round(good_samples_cnt/len(loss_list)*100,2)))
sample_selection_acc = round(correct_sample_cnt/tota_number_of_selected_samples*100, 2)
plot_analysis(
dict_key = dict_key,
loss_dict = loss_dict,
all_lengths = all_lengths,
selected_sentence_lengths = selected_sentence_lengths,
path = path,
bin_increment = bin_increment,
noise_threshold = noise_threshold,
mode = mode,
min_length_restriction = min_length_restriction,
max_length_restriction = max_length_restriction,
sample_selection_acc = sample_selection_acc
)
return indexes, noise_model
def select_data_from_logit(
args,
dict_key,
logit_dict,
loss_dict,
path,
bin_increment,
top_k,
noise_threshold=0,
min_length_restriction=10,
max_length_restriction=150,
mode="train",
logger=None,
debug=0,
isGMM=0
):
logger.info("Sample selection from :: {}".format(dict_key))
sentence_logits = logit_dict[dict_key]
values = loss_dict[dict_key]
all_lengths = []
loss_list = []
for val in values:
# if val[1] > max_length_restriction:
# continue
loss_list.append((val[0]))
all_lengths.append(val[1])
logit_avg_idx_list = []
for idx, logits in enumerate(sentence_logits):
__sum = 0
for logit in logits:
logit_softmax = scipy.special.softmax(logit, axis=-1)
__sum += logit_softmax.max()
__avg = __sum / len(logits)
logit_avg_idx_list.append((__avg, idx))
logit_avg_idx_list = sorted(logit_avg_idx_list, key=lambda logit_sum_idx_list: logit_sum_idx_list[0], reverse=True)
total_selected_sample = (len(logit_avg_idx_list)*top_k)//100
logger.info("Total number of sample selected (by max sorting) : {}".format(total_selected_sample))
if isGMM == 1:
indexes = []
confidence = []
for i in range(total_selected_sample):
# indexes.append(logit_avg_idx_list[i][1])
confidence.append([ -logit_avg_idx_list[i][0] ])
confidence = np.array(confidence)
I, noise_model = unsupervised_sample_selection(
confidence,
args.n_mixture_component,
args.n_mixture_select,
args.posterior_threshold,
args.covariance_type
)
indexes = []
for idx in I:
indexes.append(logit_avg_idx_list[idx][1])
else:
indexes = []
for i in range(total_selected_sample):
indexes.append(logit_avg_idx_list[i][1])
######################################
if debug:
tota_number_of_selected_samples = len(indexes)
logger.info("Total number of sample selected (if GMM applied) : {}".format(tota_number_of_selected_samples))
correct_sample_cnt = 0
noisy_sample_cnt = 0
good_samples_cnt = 0
cnt = 0
selected_sentence_lengths = []
for i in indexes:
val = values[i]
if val[2] > noise_threshold:
noisy_sample_cnt += 1
else:
correct_sample_cnt += 1
cnt += 1
selected_sentence_lengths.append(val[1])
if val[1] >= min_length_restriction and val[1] <= max_length_restriction:
good_samples_cnt += 1
if tota_number_of_selected_samples != 0:
logger.info("Total Number of Noisy Samples : {} ({}%)".format(noisy_sample_cnt, round(noisy_sample_cnt/tota_number_of_selected_samples*100,2)))
logger.info("Total Number of Correct Samples : {} ({}%)".format(correct_sample_cnt, round(correct_sample_cnt/tota_number_of_selected_samples*100,2)))
logger.info("Total Number of Correct Sample in dataset : {} ({}%)".format(correct_sample_cnt, round(correct_sample_cnt/len(loss_dict)*100,2)))
sample_selection_acc = round(correct_sample_cnt/tota_number_of_selected_samples*100, 2)
plot_analysis(
dict_key = dict_key,
loss_dict = loss_dict,
all_lengths = all_lengths,
selected_sentence_lengths = selected_sentence_lengths,
path = path,
bin_increment = bin_increment,
noise_threshold = noise_threshold,
mode = mode,
min_length_restriction = min_length_restriction,
max_length_restriction = max_length_restriction,
sample_selection_acc = sample_selection_acc
)
return indexes