-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathclusterer.py
407 lines (284 loc) · 11.9 KB
/
clusterer.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import random
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
# Define the dimensions of the plot and the box
width = 150
height = 25
padding = 10
# target types
targets = {
0: ('person', 'red', 'o'),
1: ('car', 'green', 'o'),
2: ('motorcycle', 'blue', 'o'),
3: ('airplane', 'orange', 'o'),
4: ('bus', 'purple', 'o'),
5: ('boat', 'brown', 'o'),
6: ('stop sign', 'pink', 'o'),
7: ('snowboard', 'gray', 'o'),
8: ('umbrella', 'cyan', 'o'),
9: ('sports ball', 'magenta', 'o'),
10: ('baseball bat', 'yellow', 'o'),
11: ('bed/mattress', 'red', 'x'),
12: ('tennis racket', 'green', 'x'),
13: ('suitcase', 'blue', 'x'),
14: ('skis', 'orange', 'x')
}
def generateTargets():
# Randomly select 4 numbers from 0-14
random_numbers = random.sample(range(15), 4)
# Generate 4 random points within the box dimensions
points = []
for _ in range(4):
# generate coordinates
x = random.uniform(0, width)
y = random.uniform(0, height)
# generate label
index = random.randint(0, len(random_numbers) - 1)
class_vector = generateClassVector(random_numbers[index])
del random_numbers[index] # remove the label from the list
object_vector = [x, y] + class_vector
points.append(object_vector)
return points
def generateClassVector(true_label, error=False, error_size=0.1):
# Initialize the class vector with small random scores
class_vector = [random.uniform(0, 0.8) for _ in range(15)]
if error:
# Randomly select a label that is not the true label
false_label = random.choice([label for label in range(15) if label != true_label])
class_vector[false_label] = random.uniform(0.81, 0.999)
class_vector[true_label] = random.uniform(0.8 - error_size, 0.8)
else:
# Set the score for the true label to a high value
class_vector[true_label] = random.uniform(0.81, 0.999) # High value for the true label
return class_vector
def scramblePoint(point, scramble_range, correctness):
x, y = point[:2]
class_vector = point[2:]
# Randomly select a new point within the range
new_x = x + random.uniform(-scramble_range, scramble_range)
new_y = y + random.uniform(-scramble_range, scramble_range)
# Randomly change the label with a certain probability
if random.random() > correctness:
new_vector = generateClassVector(np.argmax(class_vector), error=True, error_size = 1 - correctness)
else:
new_vector = generateClassVector(np.argmax(class_vector))
return [new_x, new_y] + new_vector
def scramblePoints(points, scramble_range, correctness, num_scrambles):
new_points = []
for point in points:
for _ in range(num_scrambles):
new_point = scramblePoint(point, scramble_range, correctness)
new_points.append(new_point)
return new_points
def plotScrambledPoints(points, new_points):
# Calculate the center of the plot
center_x = width / 2
center_y = height / 2
# Calculate the coordinates of the box
box_x = center_x - width / 2
box_y = center_y - height / 2
# Create the plot
plt.figure(figsize=((width + 2 * padding) / 10, (height + 2 * padding) / 10))
# Add the box to the plot
plt.gca().add_patch(plt.Rectangle((box_x, box_y), width, height, fill=None, edgecolor='black', linewidth=1.5))
# Add the original points to the plot
for point in points:
x, y = point[:2]
class_vector = point[2:]
label = np.argmax(class_vector)
target, color, _ = targets[label]
plt.scatter(x, y, color=color, marker='*', label=target)
# Add the new points to the plot
for point in new_points:
x, y = point[:2]
class_vector = point[2:]
label = np.argmax(class_vector)
target, color, marker = targets[label]
plt.scatter(x, y, color=color, marker=marker)
plt.legend(title="Target Types")
# Set the limits of the plot with padding
plt.xlim(box_x - padding, box_x + width + padding)
plt.ylim(box_y - padding, box_y + height + padding)
plt.grid(True)
plt.title('Randomly Generated Airdrop Targets')
# Show the plot
#plt.show()
def clusterPoints(points, n_clusters=4):
# Convert the points to a numpy array
data = np.array(points)
# Perform K-Means clustering
kmeans = KMeans(n_clusters=n_clusters, random_state=0).fit(data)
# Get the cluster labels
labels = kmeans.labels_
# Add cluster labels to the points
for point in points:
point += [labels[points.index(point)]]
return points
def plotClusteredPoints(points, clusteredPoints):
# Calculate the center of the plot
center_x = width / 2
center_y = height / 2
# Calculate the coordinates of the box
box_x = center_x - width / 2
box_y = center_y - height / 2
# Create the plot
plt.figure(figsize=((width + 2 * padding) / 10, (height + 2 * padding) / 10))
# Add the box to the plot
plt.gca().add_patch(plt.Rectangle((box_x, box_y), width, height, fill=None, edgecolor='black', linewidth=1.5))
# Add the points to the plot
for point in points:
x, y = point[:2]
class_vector = point[2:]
label = np.argmax(class_vector)
target, color, _ = targets[label]
plt.scatter(x, y, color=color, marker='*', label=target)
# Add the clusters to the plot
for point in clusteredPoints:
x, y = point[:2]
class_vector = point[2:-1]
label = point[-1]
plt.scatter(x, y, color='black', marker='x')
plt.legend(title="Target Types")
# Set the limits of the plot with padding
plt.xlim(box_x - padding, box_x + width + padding)
plt.ylim(box_y - padding, box_y + height + padding)
plt.grid(True)
plt.title('Randomly Generated Airdrop Targets')
# Show the plot
plt.show()
def findCentroid(clusteredPoints, cluster):
# Filter the points that belong to the cluster
cluster_points = [point for point in clusteredPoints if point[-1] == cluster]
centroid = np.zeros(17)
for point in cluster_points:
centroid += np.array(point[:-1])
return centroid / len(cluster_points)
def plotCentroids(points, clusteredPoints, n_clusters=4):
# Calculate the center of the plot
center_x = width / 2
center_y = height / 2
# Calculate the coordinates of the box
box_x = center_x - width / 2
box_y = center_y - height / 2
# Create the plot
plt.figure(figsize=((width + 2 * padding) / 10, (height + 2 * padding) / 10))
# Add the box to the plot
plt.gca().add_patch(plt.Rectangle((box_x, box_y), width, height, fill=None, edgecolor='black', linewidth=1.5))
for cluster in range(n_clusters):
centroid = findCentroid(clusteredPoints, cluster)
x, y = centroid[:2]
class_vector = centroid[2:-1]
label = np.argmax(class_vector)
target, color, marker = targets[label]
plt.scatter(x, y, color=color, marker=marker, label=f'Cluster {cluster}')
for point in points:
x, y = point[:2]
class_vector = point[2:]
label = np.argmax(class_vector)
target, color, _ = targets[label]
plt.scatter(x, y, color=color, marker='*', label=target)
error = calculateError(points, clusteredPoints)
plt.title(f'Error: {error}m')
plt.legend(title="Target Types")
plt.show()
def calculateError(points, clusteredPoints):
centroids = []
for cluster in range(4):
centroid = findCentroid(clusteredPoints, cluster)
centroids.append(centroid)
error = 0
# for each centroid
for centroid in centroids:
# find its class
class_vector = centroid[2:-1]
label = np.argmax(class_vector)
match = False
# find the point that matches the centroid
for point in points:
if np.argmax(point[2:]) == label:
# add the distance between the point and the centroid to the error
error += np.linalg.norm(centroid - point)
match = True
# If the centroid does not match any of the points
if not match:
error += 1
# return the average error in meters
return error / len(centroids)
def testScrambleCount(min_scrambles, max_scrambles, num_tests, scramble_range=5, correctness=0.8, num_clusters=4):
errors = []
for i in range(min_scrambles, max_scrambles + 1):
error = 0
for _ in range(num_tests):
points = generateTargets()
new_points = scramblePoints(points, scramble_range, correctness, i)
clusteredPoints = clusterPoints(new_points, num_clusters)
error += calculateError(points, clusteredPoints)
print(f"Percent complete: {i * 100 // max_scrambles}%", end='\r')
errors.append(error / num_tests)
print(errors)
plt.plot(range(min_scrambles, max_scrambles + 1), errors)
plt.xlabel('Number of scrambles')
plt.ylabel('Average error (m)')
plt.title('Effect of more samples on clustering accuracy')
plt.show()
def testScrambleRange(min_range, max_range, num_tests, scrambles=10, correctness=0.8, num_clusters=4):
errors = []
for i in range(min_range, max_range + 1):
error = 0
for _ in range(num_tests):
points = generateTargets()
new_points = scramblePoints(points, i, correctness, scrambles)
clusteredPoints = clusterPoints(new_points, num_clusters)
error += calculateError(points, clusteredPoints)
print(f"Percent complete: {i * 100 // max_range}%", end='\r')
errors.append(error / num_tests)
print(errors)
plt.plot(range(min_range, max_range + 1), errors)
plt.xlabel('Scramble range')
plt.ylabel('Average error (m)')
plt.title('Effect of spatial accuracy on clustering error')
plt.show()
def testScrambleCorrectness(min_correctness, max_correctness, num_tests, scrambles=10, scramble_range=5, num_clusters=4):
errors = []
accuracies = []
for i in range(min_correctness, max_correctness + 1):
error = 0
correct = 0
for _ in range(num_tests):
points = generateTargets()
new_points = scramblePoints(points, scramble_range, i / 10, scrambles)
clusteredPoints = clusterPoints(new_points, num_clusters)
error += calculateError(points, clusteredPoints)
# Calculate the accuracy of the label
true_labels = [np.argmax(point[2:]) for point in points]
predicted_labels = [np.argmax(point[2:-1]) for point in clusteredPoints]
# for each true label
for true_label in true_labels:
if true_label in predicted_labels:
correct += 1
print(f"Percent complete: {i * 100 // max_correctness}%", end='\r')
accuracies.append(correct / (num_tests * 4) * 100)
errors.append(error / num_tests)
print(errors)
plt.plot(range(min_correctness, max_correctness + 1), errors, label='Error')
plt.xlabel('Correctness')
plt.ylabel('Average error (m)')
plt.title('Effect of label accuracy on clustering error')
plt.show()
plt.plot(range(min_correctness, max_correctness + 1), accuracies, label='Accuracy')
plt.xlabel('Correctness')
plt.ylabel('Accuracy (%)')
plt.title('Effect of label accuracy on clustering accuracy')
plt.show()
def main():
'''points = generateTargets()
new_points = scramblePoints(points, 5, 0.8, 10)
#plotScrambledPoints(points, new_points)
clusteredPoints = clusterPoints(new_points, n_clusters=4)
plotClusteredPoints(points, clusteredPoints)
plotCentroids(points, clusteredPoints, n_clusters=4)
'''
testScrambleCorrectness(1, 10, 1000)
if __name__ == "__main__":
main()