pseudo.py 9.7 KB
Newer Older
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
1
2
3
4
5
6
7
8
9
import numpy as np
from time import time
import _ucrdtw
import _lsh
import math
from libs.DBA_multivariate import performDBA
from tslearn.metrics import dtw
from collections import defaultdict

10
11
12
13
"""
data: 3d array [m][t][d]
query: 2d array [t][d]
"""
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
14
15
16
17
18
19
20
def lsh(data, query, parameters = None, weights = None):
    if parameters is None:
        parameters = preprocess(data)
    r = parameters[0]
    a = parameters[1]
    sd = parameters[2]

21
22
23
    data = np.array(data, dtype='float32')
    query = np.array(query, dtype='float32')

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
24
    if weights is None:
25
        candidates, distances, hf = _lsh.lsh(data, query, r, a, sd, 1)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
26
    else:
27
        candidates, distances, hf = _lsh.lsh(data, query, r, a, sd, 1, weights)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

    dict = defaultdict(int)
    for l in range(len(candidates)):
        for k in range(len(candidates[0])):
            for i in range(len(candidates[0][0])):
                dict[candidates[l][k][i]] += distances[l][k][i]
    sorted_dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
    average_candidates = np.array(list(sorted_dict.keys())).tolist()
    average_distances = np.array(list(sorted_dict.values())).tolist()

    tables = []
    samples_set = set()
    candidates = candidates.tolist()
    for l in range(len(candidates)):
        for k in range(len(candidates[0])):
            samples_set.update(candidates[l][k][0:5])
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
44
            samples_set.update(candidates[l][k][-100:-95])
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
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
            dict = defaultdict(list)
            length = len(distances[l][k])
            median = distances[l][k][math.ceil(length/2)]
            stepsize = median / 10
            indices = list(map(lambda x: 19 if x > median * 2 else math.floor(x / stepsize), distances[l][k]))
            for i in range(len(candidates[0][0])):
                dict[str(indices[i])].append(candidates[l][k][i])
            tables.append(dict)

    length = len(average_distances)
    median = average_distances[math.ceil(length/2)]
    stepsize = median / 10
    indices = list(map(lambda x: 19 if x > median * 2 else math.floor(x / stepsize), average_distances))
    average_table = defaultdict(list)
    for i in range(len(average_candidates)):
        average_table[str(indices[i])].append(average_candidates[i])

    samples = np.array(list(filter(lambda x: x in samples_set, average_candidates))).tolist()


    response = {
        "hash_functions": hf.reshape((len(candidates) * len(candidates[0]), len(query[0]))).tolist(),
        "candidates": candidates,
        "distances": distances.tolist(),
        "average_candidates": average_candidates,
        "average_distances": average_distances,
        "tables": tables,
        "average_table": average_table,
        "samples": list(samples),
        "parameters": [float(r), float(a), float(sd)]
    }
    return response

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
78
def preprocess(data, r=None):
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
79
80
    subset = []
    t0 = time()
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
81
    if r is None:
82
        r = 19.375 # r = data.shape[2]
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
83
84
85
    started = False
    first = 0
    last = r * 2
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
86
    i = 0
87
88
    print("r = " + str(r))
    while True:
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
89
90
91
92
93
94
95
96
97
        state = 1
        for s in subset:
            if np.linalg.norm(data[i] - data[s]) < r:
                state = 0
                break
        if state == 1:
            subset.append(i)

        i = i + 1
98
        if len(subset) > 400:
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
99
100
101
102
103
104
105
            print('bigger')
            if not started:
                first = r
                last = last * 2
            else:
                first = r
            r = (first + last) / 2
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
106
107
            subset = []
            i = 0
108
109
            print("r = " + str(r))
        elif (i == 10000 or i == len(data)) and len(subset) < 10:
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
110
111
112
113
            print('smaller')
            started = True
            last = r
            r = (first + last) / 2 # r / 2
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
114
115
            subset = []
            i = 0
116
117
118
119
            print("r = " + str(r))
        elif (i == len(data)):
            break

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
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

    # subset = sample(list(range(len(data))), 200)
    dtw_distances = []
    eq_distances = []
    for i, index_1 in enumerate(subset):
        for j, index_2 in enumerate(subset):
            if index_1 == index_2:
                continue
            e = np.linalg.norm(data[index_1] - data[index_2])
            if (math.isnan(e) or e == 0):
                eq_distances.append(0.0001)
                dtw_distances.append(0.0001)
                continue
            eq_distances.append(e)
            d = dtw(data[index_1], data[index_2], global_constraint='sakoe_chiba', sakoe_chiba_radius=int(0.05*120))
            dtw_distances.append(d)

    ratios = np.array(dtw_distances)/np.array(eq_distances)
    mean_dtw = np.mean(dtw_distances)
    sd_dtw = np.std(dtw_distances)
    mean_eq = np.mean(eq_distances)
    sd_eq = np.std(eq_distances)
    a = np.mean(ratios)
    sd = np.std(ratios)
    theta = mean_dtw + -2.58 * sd_dtw
    # theta = mean_eq + -2.58 * sd_eq
    r = theta / ((a-sd)*math.sqrt(120))
    if r < 0:
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
148
        print('Actual r ' + str(r))
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
149
150
151
152
153
154
155
156
157
158
159
160
161
        r = mean_dtw / 100
    # r = theta / (math.sqrt(120))
    print('Mean: ' + str(mean_dtw))
    print('Stdev: ' + str(sd_dtw))
    print('Ratio mean: ' + str(a))
    print('Ratio stdev: ' + str(sd))
    print('Theta: ' + str(theta))
    print('r: ' + str(r))
    print('Preprocessing time: ' + str(time() - t0))
    return r, a, sd

def weights(data, query, old_weights, labels, hash_functions):
    alpha = 0.2
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
162
163
164
    d = len(query)
    print(d)

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
165
166
    all_good_windows = data[[[int(index) for index, value in labels.items() if value is True]]]

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
167
168
169
170
171
    def normalize(array):
        array /= np.sum(array)
        array *= d
        return np.sqrt(array)

Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
172
173
174
175
176
177
178
179
180
    good_distances = np.zeros(len(query))
    for window in all_good_windows:
        for i in range(len(all_good_windows[0])):
            good_distances[i] += _ucrdtw.ucrdtw(query[i], window[i], 0.05, False)[1]
    if len(all_good_windows) != 0:
        good_distances = np.square(good_distances)
        if np.sum(good_distances) != 0:
            good_distances /= np.sum(good_distances)
        good_distances = np.ones(len(query)) - good_distances
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
181
        good_distances = normalize(good_distances)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
182
183
184
185

    if len(hash_functions) != 0:
        summed_hash_functions = np.sum(hash_functions, axis=0)
        summed_hash_functions = np.square(summed_hash_functions)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
186
        normalized_hash_functions = normalize(summed_hash_functions)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
187
188
189
190
191
192
193

    if len(hash_functions) + len(all_good_windows) == 0:
        print("no update")
        new_weights = old_weights
    elif len(hash_functions) == 0:
        print("only windows")
        new_weights = alpha * np.array(old_weights) + (1 - alpha) * good_distances
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
194
        new_weights = normalize(np.square(new_weights))
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
195
196
197
    elif len(all_good_windows) == 0:
        print("only tables")
        new_weights = alpha * np.array(old_weights) + (1 - alpha) * normalized_hash_functions
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
198
        new_weights = normalize(np.square(new_weights))
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
199
200
201
    else:
        print("tables & windows")
        new_weights = alpha * np.array(old_weights) + 0.5 * (1-alpha) * good_distances + 0.5 * (1-alpha) * normalized_hash_functions
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
202
        new_weights = normalize(np.square(new_weights))
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
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

    print(new_weights)
    return new_weights.tolist()

def table_info(data, table):
    prototypes = []
    for cluster in table:
        windows = data[cluster]
        average_values = np.average(windows, 0)
        std_values = np.std(windows, 0)
        max_values = average_values + std_values
        min_values = average_values - std_values
        prototypes.append({
            'average': average_values.tolist(),
            'max': max_values.tolist(),
            'min': min_values.tolist()
        })
    # distances = [[dtw(np.array(v["average"]), np.array(w["average"]), global_constraint='sakoe_chiba', sakoe_chiba_radius=int(0.05 * 120)) for j, w in enumerate(prototypes)] for i, v in enumerate(prototypes)]
    return {'prototypes': prototypes, 'distances': []}

def query(data, window_indices):
    if isinstance(window_indices, int):
        output = data[window_indices]
    else:
        indices = [int(index) for index, value in window_indices.items() if value is True]
        indices_windows = data[indices]
        output = performDBA(indices_windows)
    return output.tolist()

def debug_test_lsh():
233
    data = np.load('data/processed-data.npy')
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
234
235
236
    # data = np.repeat(data, repeats=7, axis=1)
    print(data.shape)
    data = np.reshape(data, (len(data), len(data[0][0]), len(data[0])))
237
238
    data = np.array(data, dtype='float32')
    print(data.shape)
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
239
240
241
242
243
244
245
246
247
248
249
250
251
252

    r, a, sd = preprocess(data, 11.25)
    query_n = 1234
    t0 = time()
    query = data[query_n]
    dict = defaultdict(int)
    candidates, distances, hf = _lsh.lsh(data, query, r, a, sd)
    print("Calculated approximate in: " + str(time()-t0))
    for l in range(len(candidates)):
        for k in range(len(candidates[0])):
            for i in range(len(candidates[0][0])):
                dict[candidates[l][k][i]] += distances[l][k][i]
    sorted_dict = {k: v for k, v in sorted(dict.items(), key=lambda item: item[1])}
    candidates = list(sorted_dict.keys())
253
    print("Calculated ranked in: " + str(time()-t0))
Kruyff,D.L.W. (Dylan)'s avatar
Kruyff,D.L.W. (Dylan) committed
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275

    print(candidates[0:20])

    t0 = time()
    # distances = [dtw_ndim.distance_fast(window, query) for window in data]
    distances = [dtw(window, query, global_constraint='sakoe_chiba', sakoe_chiba_radius=int(0.05*120)) for window in data]
    topk_dtw = sorted(range(len(distances)), key=lambda k: distances[k])
    print("Calculated exact dtw in: " + str(time()-t0))
    print(topk_dtw[0:20])

    t0 = time()
    l2distances = [np.linalg.norm(window - query) for window in data]
    print("Calculated exact l2 in: " + str(time()-t0))

    # # distances_ed = [distance.euclidean(query, window) for window in data]
    # # topk_ed = sorted(range(len(distances_ed)), key=lambda k: distances_ed[k])
    #
    accuracy = 0
    for index in topk_dtw[0:20]:
        if index in candidates:
            accuracy += 1
    print(accuracy)