-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutils.py
111 lines (85 loc) · 2.82 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
import numpy as np
import pandas as pd
import os
def from_unit_cube(point, lb, ub):
assert np.all(lb < ub)
assert lb.ndim == 1
assert ub.ndim == 1
assert point.ndim == 2
new_point = point * (ub - lb) + lb
return new_point
def latin_hypercube(n, dims):
points = np.zeros((n, dims))
centers = (1.0 + 2.0 * np.arange(0.0, n))
centers = centers / float(2 * n)
for i in range(0, dims):
points[:, i] = centers[np.random.permutation(n)]
perturbation = np.random.uniform(-1.0, 1.0, (n, dims))
perturbation = perturbation / float(2 * n)
points += perturbation
return points
def bernoulli(n, dims, p=0.5):
assert n <= 2**dims, 'the number of init samples is larger than the whole space'
if n > 2**(dims-1):
print('too many init samples')
points = []
i = 0
while i < n:
point = np.zeros(dims)
prob = np.random.uniform(0.0, 1.0, dims)
point[prob < p] = 1
point = list(point)
if point not in points:
points.append(point)
i += 1
points = [np.array(point) for point in points]
# points = np.zeros((n, dims))
# prob = np.random.uniform(0.0, 1.0, (n, dims))
# points[prob < p] = 1
return points
def feature_complementary(feature):
comp = []
for i in feature:
i_comp = 0 if i else 1
comp.append(i_comp)
return np.array(comp)
def ndarray2str(arr):
s = ''
for i in arr:
s += str(int(i))
return s
def pad_str_to_8chars(ins, total):
if len(ins) <= total:
ins += ' '*(total - len(ins) )
return ins
else:
return ins[0:total]
def feature_dedup(features):
feature_set = set()
dedup = []
for f in features:
feature_set.add(tuple(f))
for f in feature_set:
dedup.append(np.array(f))
return dedup
def save_results(root_dir, algo, func, seed, df_data):
os.makedirs(root_dir, exist_ok=True)
save_dir = os.path.join(root_dir, func)
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, '%s-%d.csv' % (algo, seed))
df_data.to_csv(save_path)
print('save %s result into: %s' % (algo, save_path))
def save_args(root_dir, algo, func, seed, args):
os.makedirs(root_dir, exist_ok=True)
save_dir = os.path.join(root_dir, func)
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, '%s-%d.txt' % (algo, seed))
with open(save_path, 'w') as f:
for k, v in args.__dict__.items():
f.write('{}: {}\n'.format(k, v))
print('save {} config into: {}'.format(algo, save_path))
if __name__ == '__main__':
# print(latin_hypercube(3, 6))
# print(bernoulli(3, 3))
features = [np.array([1, 0]), np.array([1, 0]), np.array([1, 1])]
print(feature_dedup(features))