File size: 2,784 Bytes
ef987bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import csv
import math
from PIL import Image

rows = list(csv.DictReader(open('cifar_tiny.csv', encoding='utf-8-sig')))
features = [(r['image_id'], (float(r['r']), float(r['g']), float(r['b']))) for r in rows]
points = [point for _, point in features]
k = min(3, len(points))
centers = [points[0]]
while len(centers) < k:
    centers.append(max(points, key=lambda p: min(math.dist(p, c) for c in centers)))
for _ in range(50):
    groups = [[] for _ in centers]
    for point in points:
        groups[min(range(k), key=lambda i: (math.dist(point, centers[i]), i))].append(point)
    updated = [tuple(sum(p[j] for p in group) / len(group) for j in range(3)) if group else centers[i]
               for i, group in enumerate(groups)]
    if updated == centers:
        break
    centers = updated
scored = [(min(math.dist(point, center) for center in centers), image_id) for image_id, point in features]
scored.sort(key=lambda item: (-item[0], item[1]))
chosen = scored[:max(1, math.ceil(len(scored) * 0.05))]
with open('anomalies.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f); writer.writerow(['image_id', 'distance'])
    for dist, image_id in chosen: writer.writerow([image_id, round(dist, 3)])
with open('cluster_centers.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f); writer.writerow(['cluster', 'r', 'g', 'b'])
    for i, center in enumerate(centers): writer.writerow([i, *[round(value, 3) for value in center]])
by_id = {row['image_id']: row for row in rows}
grid = Image.new('RGB', (128, 64 * len(chosen)))
for index, (_, image_id) in enumerate(chosen):
    row = by_id[image_id]
    source = Image.open(row['path']).convert('RGB')
    grid.paste(source.resize((64, 64), Image.Resampling.NEAREST), (0, 64 * index))
    point = (float(row['r']), float(row['g']), float(row['b']))
    nearest = min(centers, key=lambda center: math.dist(point, center))
    swatch = tuple(round(value) for value in nearest)
    grid.paste(Image.new('RGB', (64, 64), swatch), (64, 64 * index))
grid.save('anomaly_grid.png')
open('report.html', 'w', encoding='utf-8').write(
    '<html><body><h1>CIFAR tiny K-Means cluster anomaly report</h1>'
    f'<p>K={k} retains three coarse color groups with fewer clusters than samples; farthest 5% from learned cluster centers: '
    + ', '.join(image_id for _, image_id in chosen)
    + '.</p><p>The farthest sample differs in RGB color from its nearest learned center. '
    'This color-feature distance identifies a statistical outlier, not necessarily a corrupt image; '
    'the original image and center swatch below support that visual comparison.</p>'
    '<img src="anomaly_grid.png" alt="Original anomaly images on the left; nearest RGB cluster centers on the right">'
    '</body></html>'
)