-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.py
362 lines (267 loc) · 10.3 KB
/
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
import torch
import wandb
from settings import d_params, n_params
def get_unif_Vmax(mu, scale_value=1):
"""
Description:
Estimates the maximum variance needed for the uniform distribution to produce maximum heteroscedasticity.
Return:
:vmax: the maximum uniform variance.
Return type:
float
Args:
:mu: mean of the the uniform.
:scale_value [optional]: controls scaling the Vmax to different values.
Here is the formula for estimating :math:`V_{max}`
.. math::
V_{max} = \\frac{4 \mu^2}{12}
"""
vmax = (4*mu**2)/12
vmax = vmax*scale_value
return vmax
def get_dataset_stats(dataset='UTKFace'):
"""
Description:
Gets dataset statistics. The statistics include:
1) Features mean.
2) Features std.
3) Labels mean.
4) Labels std.
Return:
:features_mean: mean of the input features.
:features_std: standard deviation of the input features.
:labels_mean: mean of the labels.
:labels_std: standard deviation of the labels.
Return type:
Tuple.
Args:
:dataset: Dataset name.
"""
if dataset == 'UTKFace' or dataset == 'utkf':
images_mean = torch.Tensor(pd.read_csv(d_params['d_img_mean_path']).values)[0][1]
images_std = torch.Tensor(pd.read_csv(d_params['d_img_std_path']).values)[0][1]
labels_mean = torch.Tensor(pd.read_csv(d_params['d_lbl_mean_path']).values)[0][1]
labels_std = torch.Tensor(pd.read_csv(d_params['d_lbl_std_path']).values)[0][1]
return ( images_mean, images_std, labels_mean, labels_std )
elif dataset=='WineQuality' or dataset == 'wine':
features_mean = np.genfromtxt(d_params['wine_features_mean_path'], delimiter=',')
features_std = np.genfromtxt(d_params['wine_features_std_path'], delimiter=',')
labels_mean = np.genfromtxt(d_params['wine_lbl_mean_path'],delimiter=',')
labels_std = np.genfromtxt(d_params['wine_lbl_std_path'], delimiter=',')
features_mean = torch.tensor(features_mean,dtype=torch.float32)
features_std = torch.tensor(features_std,dtype=torch.float32)
labels_mean = torch.tensor(labels_mean,dtype=torch.float32)
labels_std = torch.tensor(labels_std,dtype=torch.float32)
return ( features_mean, features_std, labels_mean, labels_std )
elif dataset=='BikeSharing' or dataset == 'bike':
features_mean = np.genfromtxt(d_params['bike_features_mean_path'], delimiter=',')
features_std = np.genfromtxt(d_params['bike_features_std_path'], delimiter=',')
labels_mean = np.genfromtxt(d_params['bike_lbl_mean_path'],delimiter=',')
labels_std = np.genfromtxt(d_params['bike_lbl_std_path'], delimiter=',')
features_mean = torch.tensor(features_mean,dtype=torch.float32)
features_std = torch.tensor(features_std,dtype=torch.float32)
labels_mean = torch.tensor(labels_mean,dtype=torch.float32)
labels_std = torch.tensor(labels_std,dtype=torch.float32)
return ( features_mean, features_std, labels_mean, labels_std )
else:
raise ValueError('Dataset is not recognized.')
def normalize_labels(labels, labels_mean, labels_std):
"""
Description:
Normalize the training labels as follow:
.. math::
\widetilde{y} = \\frac{(y - \overline{y})} {\sigma_y}.
where
.. math::
\widetilde{y} = \\text{Normalized labels, }
y = \\text{labels, }
\overline{y} = \\text{Mean of the labels, }.
\sigma = \\text{Standard deviation of the labels}
Return:
:labels_norm: Normalized labels.
Return type:
1D Tensor.
Args:
:labels: Training labels.
:labels_mean: Emprical mean of the training labels .
:labels_std: Emprical standard deviation of the training labels.
"""
labels_norm = (labels - labels_mean)/labels_std
return labels_norm
def normalize_features(features, features_mean, features_std, dataset='UTKFace'):
"""
Description:
Normalize the training input features as follows:
.. math::
\widetilde{X} = \\frac{(X - \overline{X})} {\sigma_x}.
where
.. math::
\widetilde{X} = \\text{Normalized features, }
X = \\text{Input features, }
\overline{X} = \\text{Features mean, }.
\sigma = \\text{Features standard deviation}
Return:
:images_norm: Normalized Features.
Return type:
NxD Tensor
Args:
:features: train data. (images)
:features_mean: Mean of the features.
:features_std: Standard deviation of the features.
:dataset: Name of the dataset that needs to be normalized.
"""
if dataset == 'UTKFace':
channels = features.shape[0]
width = features.shape[1]
length = features.shape[2]
features = features.squeeze().view(1,-1) # rolling out the whole training dataset to be a one vector.
features_norm = (features - features_mean) / features_std
# reshape the image
features_norm = features_norm.view(channels,length,width)
return features_norm
elif dataset=="WineQuality" or dataset=="BikeSharing":
features_norm = (features - features_mean) / features_std
return features_norm
else:
raise ValueError("Dataset is not recognized.")
def str_to_bool(string):
"""
Description:
Convert a string to a boolean.
Return:
True or False.
Return type:
boolean
Args:
:string: A string to be converted.
"""
if string =='True':
return True
elif string == 'False':
return False
else:
if isinstance(string, str) :
raise ValueError("Received {} as an argument. Only 'True' or 'False' are accepted.".format(string))
else:
raise TypeError("The argument is not a string but a {}.".format(type(string)))
def generate_intervals(num_dists, p=0.5):
"""
Description:
Generates intervals for sampling noise variance distributions. The intervals are low, which assigns low sampling probablity values, and high, that assigns high values.
Return:
intervals
Return type:
Dictionary
Args:
:num_dists: Number of distributions that need to have sampling intervals.
:p: Interval balance factor.It controls the balance between low and high intervals.
"""
if num_dists ==0:
raise ValueError(" number of distributions are zero: {}".format(num_dists))
elif num_dists ==1:
p =1
l = np.linspace(0,p,num_dists+1, endpoint=True)
else:
l1 = np.linspace(0,p,(num_dists//2)+num_dists%2, endpoint=False)
l2 = np.linspace(p,1,(num_dists//2)+1, endpoint=True,)
l = np.concatenate((l1,l2))
intervals = {}
for i in range(len(l)-1):
intervals[str(i+1)] = (l[i], l[i+1])
return intervals
def choose_distribution(intervals):
"""
Description:
Chooses a distribution based on sampling from the intervals.
Return:
key, (an id for the sampled distribution)
Return type:
int
Args:
:intervals: A dictionary of tuple values, each tuple represents an interval that is compared against when the sampling happens.
:p: Interval balance factor.It controls the balance between low and high intervals.
"""
random_number = torch.rand((1,1)).item()
for key in intervals.keys():
if random_number> intervals.get(key)[0] and random_number< intervals.get(key)[1]:
return key
raise RuntimeError("generated random number does not fall into any category: {}".format(random_number))
def get_mean_avg_variance(noise_type,avg_variance_m,mu1,p):
"""
Description:
Estimates the value of the mean of the second distribution, in a bi-model distribution, based on the average noise varaince mean.
Return:
mu2
Return type:
float
Args:
:noise_type: Noise type.
:avg_variance_m: The average of means of the noise variance distributions.
:mu1: First distribution's mean.
:p: Distributions ratio.
"""
mu2 = (avg_variance_m-p*mu1)/(1-p)
return mu2
def print_experiment_information(args):
"""
Description:
Print experiment information, which consists of :
1) Dataset information.
2) Models informations.
3) Commandline options information.
Return:
None
Return type:
None
Args:
:args: Commandline options.
"""
print("#"*80,"Dataset Settings:","#"*80)
print(d_params)
print("#"*80,"Network Settings:","#"*80)
print(n_params)
print("#"*80,"CommandLine Arguments:","#"*80)
print(args)
print("*"*180)
def filter_batch(predictions, labels, noise_var, threshold = 0.4):
"""
Description:
Filters a batch of labels based on a noise varaince threshold.
Return:
filtered predictions, filtered labels , filtered noise_variance
Return type:
Tuple
Args:
:predictions: model's predictions.
:labels: Noisy labels.
:noise_var: noises variances
:threshold: noise variance threshold.
"""
noise_var_mask = noise_var < threshold
noise_var = noise_var[noise_var_mask]
labels_n = labels[noise_var_mask]
predictions_n = predictions[noise_var_mask]
num_filtered_samples = len(labels_n)
num_total_samples = len(labels)
print("Number of filtered samples per batch: {}".format(num_filtered_samples))
print("Ratio of filtered samples per batch: {}".format((num_filtered_samples/num_total_samples)*100))
return predictions_n, labels_n , noise_var
def assert_args_mixture(args):
"""
Description:
Check the validaty of the combination of two or more arguments.
Return:
None
Return type:
None
Args:
:args: Arguments that need to be checked.
"""
if args.get('loss_type') == "biv" and args.get('noise') ==False:
raise RuntimeError("BIV needs noise variance to work properly. Please enable 'noise'= True and specifiy the noise.")
return None