File size: 6,645 Bytes
9351b33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Explore the Flowers102 dataset: class balance, missing files, image sizes, outliers, and colors.

Usage:
    python explore.py

Tables and plots are saved to outputs/eda/.
"""
from pathlib import Path

import matplotlib.pyplot as plt
import pandas as pd
import torch
from PIL import Image
from torchvision import transforms

from data_setup import (IMAGENET_MEAN, IMAGENET_STD, RANDOM_SEED, SPLITS, TEST_TRANSFORM,
                        TRAIN_TRANSFORM, load_split)

OUTPUT_DIR = Path(__file__).resolve().parent / "outputs" / "eda"


def to_display(image_tensor):
    # Undo normalization so matplotlib shows the original colors
    image_tensor = image_tensor.permute(1, 2, 0) * torch.tensor(IMAGENET_STD) + torch.tensor(IMAGENET_MEAN)
    return image_tensor.clamp(0, 1)


def main():
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    split_data = {split: load_split(split) for split in SPLITS}
    train_data = split_data["train"]
    class_names = train_data.classes

    image, label = train_data[0]
    for split, dataset in split_data.items():
        print(f"{split} samples: {len(dataset):,}")
    print(f"Classes: {len(class_names)}")
    print(f"First sample: {image.size[0]} x {image.size[1]} {image.mode} image, label {label} ({class_names[label]})\n")

    # Count images per class in each split; _labels holds every target without opening the images
    class_counts = pd.DataFrame({
        split: pd.Series(dataset._labels).value_counts().sort_index()
        for split, dataset in split_data.items()
    })
    class_counts.index = class_names
    class_counts.to_csv(OUTPUT_DIR / "class_counts.csv", index_label="class")
    print("Images per class:")
    print(class_counts.describe().round(1).to_string(), "\n")

    # Plot test images per class from most to fewest
    test_counts = class_counts["test"].sort_values(ascending=False)
    fig, ax = plt.subplots(figsize=(16, 5))
    ax.bar(range(len(test_counts)), test_counts.values)
    ax.set_xticks(range(len(test_counts)), test_counts.index, rotation=90, fontsize=6)
    ax.set_xlim(-1, len(test_counts))
    ax.set_ylabel("Test images")
    ax.set_title("Test images per class (training and validation have 10 per class)")
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "class_distribution.png", dpi=120)
    plt.close(fig)
    print("Most test images:", test_counts.head(3).to_dict())
    print("Fewest test images:", test_counts.tail(3).to_dict(), "\n")

    # Check for missing image files, then record each image's size and color mode
    missing_files = [
        image_file for dataset in split_data.values()
        for image_file in dataset._image_files if not image_file.exists()
    ]
    print(f"Missing image files: {len(missing_files)}")

    image_records = []
    for split, dataset in split_data.items():
        for image_file in dataset._image_files:
            with Image.open(image_file) as image:
                image_records.append({
                    "split": split, "width": image.width,
                    "height": image.height, "mode": image.mode
                })
    image_info = pd.DataFrame(image_records)
    image_info["shorter_side"] = image_info[["width", "height"]].min(axis=1)
    image_info["aspect_ratio"] = image_info["width"] / image_info["height"]
    size_summary = image_info[["width", "height", "shorter_side", "aspect_ratio"]].describe().round(2)
    size_summary.to_csv(OUTPUT_DIR / "image_size_summary.csv")
    print(f"Color modes: {image_info['mode'].value_counts().to_dict()}")
    print(size_summary.to_string(), "\n")

    # Plot image width, height, and aspect-ratio distributions
    fig, axes = plt.subplots(1, 3, figsize=(15, 4))
    for ax, column in zip(axes, ["width", "height", "aspect_ratio"]):
        ax.hist(image_info[column], bins=40)
        ax.set_title(f"Image {column.replace('_', ' ')}")
        ax.set_xlabel(column.replace("_", " "))
        ax.set_ylabel("Images")
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "image_sizes.png", dpi=120)
    plt.close(fig)

    # Flag aspect-ratio outliers with the 1.5 x IQR rule
    q1, q3 = image_info["aspect_ratio"].quantile([0.25, 0.75])
    iqr = q3 - q1
    lower_bound, upper_bound = q1 - 1.5 * iqr, q3 + 1.5 * iqr
    outliers = image_info[
        (image_info["aspect_ratio"] < lower_bound) | (image_info["aspect_ratio"] > upper_bound)
    ]
    print(f"Aspect-ratio IQR bounds: {lower_bound:.2f} to {upper_bound:.2f}")
    print(f"Aspect-ratio outliers: {len(outliers):,} of {len(image_info):,} images")
    print(f"Aspect-ratio range: {image_info['aspect_ratio'].min():.2f} to {image_info['aspect_ratio'].max():.2f}\n")

    # Visualize twelve reproducible training samples
    sample_indices = torch.randperm(
        len(train_data), generator=torch.Generator().manual_seed(RANDOM_SEED)
    )[:12]
    fig, axes = plt.subplots(3, 4, figsize=(14, 10))
    for ax, index in zip(axes.flat, sample_indices):
        image, label = train_data[index.item()]
        ax.imshow(image)
        ax.set_title(f"{label}: {class_names[label]}", fontsize=10)
        ax.axis("off")
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "training_samples.png", dpi=100)
    plt.close(fig)

    # Show one training photo's evaluation view and four random augmented views
    image, label = train_data[sample_indices[0].item()]
    torch.manual_seed(RANDOM_SEED)
    fig, axes = plt.subplots(1, 5, figsize=(16, 4))
    axes[0].imshow(to_display(TEST_TRANSFORM(image)))
    axes[0].set_title("Evaluation view")
    for ax in axes[1:]:
        ax.imshow(to_display(TRAIN_TRANSFORM(image)))
        ax.set_title("Augmented training view")
    for ax in axes:
        ax.axis("off")
    fig.suptitle(class_names[label])
    fig.tight_layout()
    fig.savefig(OUTPUT_DIR / "augmentation.png", dpi=100)
    plt.close(fig)

    # Compare training-set RGB channel statistics with the ImageNet values used for normalization
    small_tensor = transforms.Compose([transforms.Resize((64, 64)), transforms.ToTensor()])
    train_pixels = torch.stack([small_tensor(image) for image, _ in train_data])
    channel_stats = pd.DataFrame({
        "Flowers102 mean": train_pixels.mean(dim=(0, 2, 3)).tolist(),
        "Flowers102 std": train_pixels.std(dim=(0, 2, 3)).tolist(),
        "ImageNet mean": IMAGENET_MEAN,
        "ImageNet std": IMAGENET_STD
    }, index=["red", "green", "blue"]).round(3)
    channel_stats.to_csv(OUTPUT_DIR / "channel_stats.csv", index_label="channel")
    print("RGB channel statistics:")
    print(channel_stats.to_string())
    print(f"\nSaved tables and plots to {OUTPUT_DIR}")


if __name__ == "__main__":
    main()