-
Notifications
You must be signed in to change notification settings - Fork 0
/
LBG.py
352 lines (295 loc) · 12.5 KB
/
LBG.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
"""
LBG Clustering Algorithm
Partition n observations into K clusters
TODO: Need to train this on multiple speakers (consider cmd line loop)
Also need to be able to run this with test data
1. Initialization - K initial "means" centroids are generated at random
2. Assignment - K clusters are created by associating each observation w nearest centroid
3. Update - Centroid of clusters becomes new mean
4. Repeat until convergence
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import copy
import string
# Load the training data from the MFCC Matrices from ProcessSpeaker file
# TODO THis is a test to see if we can even get the codes
# Load the current MFCC Lifted numpy arrays from file
npy_dir = "./train/";
N = 6; # number of speakers (used for npy output)
MCOUNT = 1; # centroid tracking index (used for split)
K = 8; # number of codewords per codebook
delta = 0.01; # delta for splitting the centroids
eps = 0.001; # epsilon distortion limit for centroids
# Color map for centroids and data partition clusters
colormap = {1: 'blueviolet', 2: 'forestgreen', 3: 'deeppink', 4: 'dodgerblue', 5: 'indigo', 6: 'gold', 7: 'darkgray', 8: 'red', 9: 'lawngreen', 10: 'sienna', 11: 'olive', 12: 'salmon', 13: 'steelblue', 14: 'mediumblue', 15: 'purple', 16: 'peru'}
MFCC = {}
# From the MFCC we will use LBG algorithm to find distances (clustering)
# NOTE We will have N Columns of M dimensional vectors (i.e. 19-D vectors)
for i in np.arange(1, N):
filename = npy_dir + "s" + str(i) + "_mfcc_lift.npy"
mfcc = np.load(filename)
MFCC[i] = mfcc
# TODO Will use a loop over all speakers and pull MFCC for each
# Will test on one speaker MFCC matrix
mfcc = MFCC[1]
[M, N] = mfcc.shape
# Create the DataFrame with all of the MFCC data vectors
data = {}
axes = {}
print("Data:")
for i in range(M):
axis = string.ascii_lowercase[i]
axes[i] = axis
row = mfcc[i,:]
data[axis] = row
data_frame = pd.DataFrame(data)
print("Axes:")
print(len(axes))
print(axes)
print("\n")
print("Data Frame:")
print(data_frame.shape)
print(data_frame)
print("\n")
# --------------------------------------------------------------------------------
# Calculate average distortion betwen centroids and data points
# --------------------------------------------------------------------------------
def average_distortion(df, centroid_distance_cols):
total_dists = {}
total_sum = 0
for x in centroid_distance_cols:
key = int(x.lstrip('distance_from_'))
idx = df.index[df.loc[:, 'closest'] == key].tolist()
dists = df[x][idx]
total_dists[x] = np.sum(dists)
total_sum = total_sum + total_dists[x]
aver_dist = total_sum/M
return [total_sum, aver_dist]
# --------------------------------------------------------------------------------
# Centroid split when the distortion drops below threshold (epsilon)
# --------------------------------------------------------------------------------
def centroid_split(M, centroids):
cc = copy.deepcopy(centroids)
centroid_keys = cc.keys()
print("Centroid Split:")
print("Len centroids = " + str(len(centroids)))
print("M = " + str(M))
print("delta = " + str(delta))
print("centroids keys:");
print(centroid_keys)
print("\n")
# Loop through centroids and split each into two
for i in centroid_keys:
# update centroids with close centroids
centroids[2*i - 1] = centroids[i] * (1+delta)
centroids[2*i] = centroids[i] * (1-delta)
M = len(centroids)
return [M, centroids]
# --------------------------------------------------------------------------------
# Nearest-Neighbor Assignment (i.e. assign 19-d vectors to nearest centroids)
# --------------------------------------------------------------------------------
def nearest_neighbor(MCOUNT, count, df, centroids):
if (count == 10):
if (MCOUNT >= 8):
print("Nearest Neighbor:")
print("------------------------------------------------------------------")
print("Centroids (len = " + str(len(centroids)) + "):")
print(centroids)
print("\n")
# loop through the centroids to calculate distances
for i in centroids.keys():
diff_sum = 0
# loop through axes for coordinates of each dimension
for j in range(len(axes)):
axis = axes[j]
ci = centroids[i][j]
# Sum of all the dimensional vectors
diff_sq = (df[axis] - ci) ** 2
diff_sum = diff_sum + diff_sq
if (count == 10):
if (MCOUNT >= 8):
if (j <= 2):
print("------------------------------------------------------------")
print("axis = " + str(axis))
print("df[" + str(axis) + "]:")
print(df[axis])
print("\n")
print("centroid[" + str(i) + ", " + str(j) + "]:")
print(ci);
print("Diff squared = " + str(diff_sq))
print("Diff sum = " + str(diff_sum))
print("------------------------------------------------------------")
print("\n")
# Assign the final distance calculations to the distance from column
distance_from = np.sqrt(diff_sum)
if (count == 10):
if (MCOUNT >= 8):
print("COUNT = " + str(count));
print("Distance from [" + str(i) + "]:")
print(distance_from)
print("------------------------------------------------------------------")
print("\n")
df['distance_from_{}'.format(i)] = distance_from
# Set the distance from centroid column in the data frame
centroid_distance_cols = ['distance_from_{}'.format(i) for i in centroids.keys()]
# Set the minimum distances for each data point to nearest centroid
df['closest'] = df.loc[:,centroid_distance_cols].idxmin(axis=1) # find the minimum of all cols
df['closest'] = df['closest'].map(lambda x: int(x.lstrip('distance_from_')))
df['color'] = df['closest'].map(lambda x: colormap[x])
return [centroid_distance_cols, df]
# --------------------------------------------------------------------------------
# Update the centroids according to the new averages of partitions
# --------------------------------------------------------------------------------
def update_centroids(MCOUNT, count, df, centroids):
# loop through the centroids and calculate the means of the closest vectors
for i in centroids.keys():
# loop through the axes in order to calculate averages
for j in range(len(axes)):
axis = axes[j]
if (count >= 9):
if (MCOUNT >= 8):
print("Centroid Key:")
print(str(i))
print("[j, Axis] = [" + str(j) + ", " + str(axis) + "]");
print("\n")
print("DF Closest:")
print(df['closest'])
print(centroids)
print("\n")
# average all dimension coordinates for a given centroid (i.e. [a, b, c, ...]
centroids[i][j] = np.mean(df[df['closest'] == i][axis])
return centroids
# Create the initial centroid
centroids = {}
centroids[1] = np.mean(mfcc, axis=1)
print("Initial Centroid:")
print(len(centroids))
print(centroids)
print("\n");
# Create the split using the delta given perturbation factor
[MCOUNT, centroids] = centroid_split(MCOUNT, centroids)
print("Split Centroids:")
print("MCOUNT = " + str(MCOUNT))
print(len(centroids))
print(centroids)
print("\n");
# Print the initial data along with the first centroid
# We will plot the first two columns
fig = plt.figure(figsize=(5,5))
plt.scatter(data_frame['g'], data_frame['h'], color='lightgray')
for i in centroids.keys():
plt.scatter(*centroids[i][6:8], color=colormap[i])
plt.show()
# Calculate the initial neighbor partitions
[centroid_distance_cols, data_frame] = nearest_neighbor(0, 0, data_frame, centroids)
# Compute initial average distortion
[total_dist, mean_dist] = average_distortion(data_frame, centroid_distance_cols)
# Update the centroids for the new distances
centroids = update_centroids(0, 0, data_frame, centroids)
print("Update Centroids Out:")
print(len(centroids))
print(centroids)
print("\n")
#print("Final Data Frame:")
#print(data_frame.shape)
#print(data_frame);
#print("\n")
#print("Total Distortion = " + str(total_dist))
#print("Average Distortion = " + str(mean_dist))
#print("\n")
# Plot the updated centroids prior to the loop of fitting
fig = plt.figure(figsize=(5,5))
plt.scatter(data_frame['g'], data_frame['h'], color=data_frame['color'], alpha=0.2, edgecolor='k')
for i in centroids.keys():
plt.scatter(*centroids[i][6:8], color=colormap[i])
plt.show()
"""
Framework for Centroid Searching:
1. Centroid Split (Step 2)
-> Divide current centroids into two (2*MCOUNT)
-> Set the difference as delta separation
2. Distortion check (Step 6)
if (D[n-1] - D[n])/D[n] > epsilon:
-> Step 3 (Nearest-neighbor search)
else:
-> Step 7 (Codebook check)
3 . Codebook check
if (MCOUNT == K):
-> MCOUNT = K, number of codewords for codebook is reached (BREAK)
else:
-> Step 2 (split the centroids)
"""
count = 0;
while True:
if count == 11:
break;
# Old centroid closest vector (used for final checks)
old_centroids = data_frame['closest'].copy(deep=True)
# Old mean distortion (i.e. D[n-1])
old_mean_dist = mean_dist
# Update centroids and calculate nearest neighbors
[centroid_distance_cols, data_frame] = nearest_neighbor(MCOUNT, count, data_frame, centroids)
[M, N] = data_frame.shape
# Check the Data Frames for distances
# dist_from = data_frame.filter(regex="distance_from")
# for k in dist_from.keys():
# print("Distance From [" + str(k) + "]:")
# print(dist_from[k])
# print("\n")
# Compute average distortion and threshold distorition
[total_dist, mean_dist] = average_distortion(data_frame, centroid_distance_cols)
thresh_dist = (old_mean_dist - mean_dist)/mean_dist
thresh_dist = abs(thresh_dist)
# print(" => Total Distortion = " + str(total_dist))
# print(" => Old Aver Distortion = " + str(old_mean_dist))
# print(" => Aver. Distortion = " + str(mean_dist))
# print(" => Thresh. Distortion = " + str(thresh_dist))
# print(" => Epsilon (thresh) = " + str(eps))
# print("\n")
# Update the centroids
centroids = update_centroids(MCOUNT, count, data_frame, centroids)
if (count >= 9):
if (MCOUNT >= 8):
print("Updated Centroids:")
print(len(centroids))
print(centroids)
print("\n")
# Plot the updated centroids prior to the loop of fitting
# TODO Will plot the final clusters from the LBG output
# fig = plt.figure(figsize=(5,5))
# plt.scatter(data_frame['j'], data_frame['k'], color=data_frame['color'], alpha=0.2, edgecolor='k')
# for i in centroids.keys():
# plt.scatter(*centroids[i][12:14], color=colormap[i], edgecolor='k')
# plt.show()
# TODO This isn't being hit for the threshold epsilon check
# First check if new centroids equal previous centroids (i.e. convergence)
if (old_centroids.equals(data_frame['closest'])) or (thresh_dist < eps):
# Split the centroids
if (MCOUNT != K):
# print("Split Centroids:")
# print("MCOUNT = " + str(MCOUNT))
# print("Centroids in:")
# print(len(centroids))
# print("\n")
[MCOUNT, centroids] = centroid_split(MCOUNT, centroids)
print("---------- Centroid Split K = "
+ str(MCOUNT) + " ----------")
print("Count = " + str(count))
print("MCOUNT = " + str(MCOUNT))
print("Centroids out:")
print(len(centroids))
print(centroids)
print("\n")
continue
else:
print("BREAK!!!!");
print("Count = " + str(count))
print("MCOUNT == K == " + str(MCOUNT));
print("Final Centroids:")
print(len(centroids))
print(centroids)
print("\n")
break;
count = count + 1