File size: 26,275 Bytes
4cb3b34
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4cb3b34
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
b52efb4
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b52efb4
fe7bebc
be0507f
 
fe7bebc
 
 
 
1b32d00
fe7bebc
b52efb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe7bebc
 
 
 
b52efb4
 
 
 
 
fe7bebc
be0507f
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
b52efb4
 
fe7bebc
be0507f
fe7bebc
b52efb4
be0507f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe7bebc
 
be0507f
 
 
fe7bebc
 
 
be0507f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe7bebc
 
b52efb4
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be0507f
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b52efb4
fe7bebc
 
 
 
 
 
 
 
b52efb4
fe7bebc
 
 
 
 
 
 
b52efb4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be0507f
fe7bebc
 
be0507f
fe7bebc
 
 
be0507f
fe7bebc
 
 
 
 
 
 
 
 
be0507f
 
 
 
 
 
 
 
 
 
 
fe7bebc
be0507f
fe7bebc
 
 
 
 
 
be0507f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fe7bebc
 
 
 
 
be0507f
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
be0507f
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b52efb4
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
b52efb4
fe7bebc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b52efb4
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
---
pretty_name: Stochastic Depth Thesis Benchmark Datasets
license: other
task_categories:
- image-classification
tags:
- computer-vision
- image-classification
- benchmark
- resnet
- stochastic-depth
- reproducibility
- pytorch
- imagefolder
- academic
size_categories:
- 100K<n<1M
---

<div align="center">

# Stochastic Depth Thesis Benchmark Datasets

### Five reproducibly prepared image-classification benchmarks for controlled ResNet and stochastic-depth experiments

[![Hugging Face Dataset](https://img.shields.io/badge/Hugging%20Face-Dataset-FFD21E?logo=huggingface&logoColor=black)](https://huggingface.co/datasets/hermanhugging/thesis_stochastic_depth)
[![PyTorch](https://img.shields.io/badge/PyTorch-Compatible-EE4C2C?logo=pytorch&logoColor=white)](https://pytorch.org/)
[![Task](https://img.shields.io/badge/Task-Image%20Classification-blue)](#dataset-overview)
[![License](https://img.shields.io/badge/License-Mixed%20%2F%20Other-lightgrey)](#licensing)

**Prepared for the bachelor thesis  
_A Study of “Stochastic Depth” for Regularizing Residual Convolutional Neural Networks_**

</div>

---

## Dataset summary

This repository contains the exact dataset variants used to compare a baseline ResNet with batch-level and sample-level stochastic-depth implementations. It is a **collection of five independent classification benchmarks**, not one merged label space.

The preparation pipeline was designed for reproducibility:

- all generated splits use a dedicated split seed of `42`;
- the split seed is independent of model-training seeds;
- unreadable files are recorded;
- exact duplicates are detected deterministically;
- duplicate handling is documented separately for every dataset;
- large images are converted to a common RGB `224 Г— 224` representation;
- training, validation, and test membership is recorded in machine-readable manifests;
- dataset-specific RGB normalization statistics are estimated only from each final training split and stored in `normalization.json`;
- validation and test images are never used to estimate normalization parameters;
- the test split is kept separate from checkpoint selection.

The source code used to prepare and load the datasets is available in the accompanying project repository:

> **Code:** https://github.com/gerageragera39/A-Study-of-Stochastic-Depth-for-Regularizing-Residual-Convolutional-Neural-Networks

## Published thesis results

In addition to the prepared datasets, this repository contains the experimental artifacts reported in the thesis under [`results/`](./results/).

All final main experiments used one NVIDIA A40 GPU per SLURM task, batch size 256, 300 epochs, `pL = 0.5`, and training seeds `20917`, `723421`, and `901344`. Each dataset includes four conditions: `no_sd`, `sd_per_batch`, `sd_per_sample`, and `dropout`.

| Dataset | Architecture | Precision |
|---|---|---|
| CIFAR-100 | CIFAR-style full pre-activation ResNet-110 | FP32 |
| Caltech-256 | full pre-activation ResNet-101 | BF16 CUDA autocast without gradient scaling |
| Google Scraped Image Dataset | full pre-activation ResNet-101 | BF16 CUDA autocast without gradient scaling |
| Oxford Flowers-102 | full pre-activation ResNet-101 | FP32 |
| Stanford Dogs | full pre-activation ResNet-101 | FP32 |

The separate CIFAR-100 bias–variance analysis is stored under [`results/bias_variance/cifar100/resnet110/batch_256/fp32/pL_0.5/`](./results/bias_variance/cifar100/resnet110/batch_256/fp32/pL_0.5/). It uses the 45,000/5,000 training/validation split, excludes the official test set from the diagnostic analysis, and compares `no_sd` with `sd_per_sample` over seeds `111111`, `129143`, `222222`, `363801`, and `548357`.

## Dataset overview

| Dataset ID | Benchmark | Classes | Experimental split | Stored resolution | Main preparation rule |
|---|---:|---:|---|---:|---|
| `cifar100` | CIFAR-100 | 100 | 45,000 train / 5,000 validation / 10,000 official test | `32 Г— 32` | Official test preserved; exact-image anomalies are diagnostic only |
| `caltech256` | Caltech-256 | 256 | 20,839 train / 4,510 validation / 4,414 test | `224 Г— 224` RGB | Clutter excluded; exact duplicates handled before splitting |
| `google4` | Google Scraped Image Dataset | 4 | 27,298 train / 3,413 validation / 3,412 test | `224 Г— 224` RGB | Source train/test folders merged; class aliases normalized |
| `oxford102` | Oxford Flowers-102 | 102 | 6,551 train / 818 validation / 819 test | `224 Г— 224` RGB | Cross-split exact duplicates removed without random resplitting |
| `stanford120` | Stanford Dogs | 120 | 10,802 train / 1,198 validation / 8,580 official test | `224 Г— 224` RGB | Official metadata required; test membership is preserved |

The final counts above are also stored in each dataset's `split_summary.csv` and `split_config.json`. These generated files are the authoritative source for the published release.

## Important distinction: preprocessing vs. augmentation

The images stored in this repository contain only **deterministic offline preprocessing**. Random augmentation is **not baked into the files**.

### Deterministic offline preprocessing

For Caltech-256, Google-4, Oxford Flowers-102, and Stanford Dogs:

1. verify that the image can be decoded;
2. convert it to RGB;
3. resize with bilinear interpolation so that the shorter side becomes 224 pixels;
4. take a centered `224 Г— 224` crop;
5. preserve already compatible RGB `224 Г— 224` files without unnecessary re-encoding.

### Dataset-specific normalization and online augmentation

The thesis models for the four `224 Г— 224` datasets are trained from randomly initialized weights. No ImageNet-pretrained parameters are used, and ImageNet normalization constants are not part of the final protocol.

Instead, each higher-resolution dataset has its own `normalization.json`. The channel-wise mean and population standard deviation were calculated from the **final prepared training split only**, after deterministic RGB conversion, resizing, and center cropping, but before random augmentation. Validation and test images were not used to estimate these values.

For each RGB channel, normalization is applied as:

```text
normalized_channel = (channel - mean) / std
```

The published values are:

| Dataset ID | Training images used | Mean `(R, G, B)` | Population std `(R, G, B)` |
|---|---:|---|---|
| `caltech256` | 20,839 | `(0.549342, 0.527082, 0.498657)` | `(0.312259, 0.308552, 0.321477)` |
| `google4` | 27,298 | `(0.493377, 0.434710, 0.377280)` | `(0.279901, 0.274272, 0.289370)` |
| `oxford102` | 6,551 | `(0.475326, 0.393880, 0.307287)` | `(0.297811, 0.246210, 0.276400)` |
| `stanford120` | 10,802 | `(0.479285, 0.450474, 0.391284)` | `(0.259824, 0.253940, 0.257219)` |

The table rounds values to six decimal places for readability. The corresponding `normalization.json` files retain full numerical precision and should be treated as the authoritative values used by the data loaders.

The training code applies random augmentation before tensor conversion and normalization. Validation and test use the same training-derived normalization constants but no random augmentation:

```python
import json
from pathlib import Path

from torchvision import transforms


def load_normalization(path: str | Path) -> tuple[list[float], list[float]]:
    data = json.loads(Path(path).read_text(encoding="utf-8"))
    mean = data["mean"]
    std = data["std"]

    if len(mean) != 3 or len(std) != 3:
        raise ValueError(f"Expected three-channel statistics in {path}")
    if any(value <= 0 for value in std):
        raise ValueError(f"Standard deviations must be positive in {path}")

    return mean, std


def make_224_transforms(
    normalization_path: str | Path,
) -> tuple[transforms.Compose, transforms.Compose]:
    mean, std = load_normalization(normalization_path)

    train_transform = transforms.Compose([
        transforms.RandomRotation(15),
        transforms.RandomHorizontalFlip(),
        transforms.ColorJitter(
            brightness=0.2,
            contrast=0.2,
            saturation=0.2,
            hue=0.1,
        ),
        transforms.ToTensor(),
        transforms.Normalize(mean=mean, std=std),
    ])

    eval_transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean=mean, std=std),
    ])

    return train_transform, eval_transform
```

CIFAR-100 uses a separate `32 Г— 32` pipeline and its established CIFAR-100 channel statistics:

```python
from torchvision import transforms

train_transform_cifar = transforms.Compose([
    transforms.RandomCrop(32, padding=4),
    transforms.RandomHorizontalFlip(),
    transforms.ToTensor(),
    transforms.Normalize(
        mean=(0.5071, 0.4867, 0.4408),
        std=(0.2675, 0.2565, 0.2761),
    ),
])

eval_transform_cifar = transforms.Compose([
    transforms.ToTensor(),
    transforms.Normalize(
        mean=(0.5071, 0.4867, 0.4408),
        std=(0.2675, 0.2565, 0.2761),
    ),
])
```

Validation and test images receive no random augmentation. Within a dataset, the same normalization file is used for the baseline ResNet and every regularized model variant.

## Split and duplicate policies

### CIFAR-100

The official 50,000-image training set is divided deterministically into 45,000 training images and 5,000 validation images, with 450 training and 50 validation images per class. The official 10,000-image test set is preserved unchanged.

Exact pixel-array duplicates and label conflicts are reported for diagnostics, but they are not used to remove, relabel, or move official CIFAR-100 samples.

### Caltech-256

The `257.clutter` directory is excluded, leaving 256 object categories. Unreadable files are recorded before splitting.

For a same-label SHA-256 duplicate group, one deterministic representative is retained. If the same exact file hash appears under different class labels, every member of that conflicting group is excluded. The cleaned data are then divided using a class-stratified `70 / 15 / 15` split.

### Google-4

The labelled source folders originally named `train` and `test` are merged before creating the experimental split. Directory-name variants and misspellings are normalized to four canonical classes:

- `architecture`
- `art and culture`
- `food`
- `travel and adventure`

Unlabelled demonstration images are excluded from quantitative evaluation. Exact duplicate handling follows the same pre-split policy as Caltech-256. The cleaned collection is divided using a class-stratified `80 / 10 / 10` split.

### Oxford Flowers-102

The source package's train, validation, and test membership is preserved; no random resplitting is performed.

When a same-label exact duplicate occurs in more than one split, the retained split is selected according to:

```text
test > validation > training
```

Copies in lower-priority splits are excluded, and no image is moved between splits. Cross-label exact duplicates are treated as blocking conflicts requiring manual review.

### Stanford Dogs

The official Stanford Dogs metadata is required. The official 12,000-image training set is divided approximately `90 / 10` into training and validation subsets. The official 8,580-image test set is preserved.

Exact-hash groups from the official training data are kept within one generated split. Anomalies involving official benchmark membership are reported diagnostically rather than used to silently modify the benchmark.

## Reproducibility metadata

Each prepared dataset is accompanied by machine-readable metadata. Depending on the dataset-specific policy, the repository may contain:

| File | Purpose |
|---|---|
| `split_manifest.csv` | One row per retained sample, including class, split, source path, processed path, and SHA-256 hashes |
| `split_summary.csv` | Per-class sample counts for each split |
| `class_to_idx.json` | Deterministic mapping from class names to integer labels |
| `split_config.json` | Split policy, seed, image-preparation settings, counts, warnings, and dataset-specific decisions |
| `normalization.json` | Training-split RGB mean and population standard deviation used by the `224 Г— 224` data loader |
| `corrupt_images.json` | Source files that could not be decoded |
| `duplicates.json` | Detected same-label exact-duplicate groups |
| `label_conflicts.json` | Exact hashes observed under more than one label |
| `excluded_same_label_duplicates.csv` | Same-label copies removed before splitting where applicable |
| `excluded_cross_split_duplicates.csv` | Oxford copies removed to prevent split leakage |
| `excluded_conflicts.csv` | Files excluded because of cross-label exact conflicts |
| `train_indices.npy` / `val_indices.npy` | Deterministic CIFAR-100 split indices |

An “exact duplicate” in the folder-based datasets means an identical SHA-256 hash of the source file. This method does not detect perceptually similar images that were recompressed, resized, cropped, rotated, or otherwise modified.

## Repository layout

The preparation code produces the following logical layout:

```text
data/
в”њв”Ђв”Ђ processed/
в”‚   в”њв”Ђв”Ђ cifar100/
в”‚   в”‚   в””в”Ђв”Ђ cifar-100-python/
в”‚   в”њв”Ђв”Ђ caltech256/
в”‚   в”‚   в”њв”Ђв”Ђ train/<class>/*
в”‚   в”‚   в”њв”Ђв”Ђ val/<class>/*
в”‚   в”‚   в””в”Ђв”Ђ test/<class>/*
в”‚   в”њв”Ђв”Ђ google4/
в”‚   в”‚   в”њв”Ђв”Ђ train/<class>/*
в”‚   в”‚   в”њв”Ђв”Ђ val/<class>/*
в”‚   в”‚   в””в”Ђв”Ђ test/<class>/*
в”‚   в”њв”Ђв”Ђ oxford102/
в”‚   в”‚   в”њв”Ђв”Ђ train/<class>/*
в”‚   в”‚   в”њв”Ђв”Ђ val/<class>/*
в”‚   в”‚   в””в”Ђв”Ђ test/<class>/*
в”‚   в””в”Ђв”Ђ stanford120/
в”‚       в”њв”Ђв”Ђ train/<class>/*
в”‚       в”њв”Ђв”Ђ val/<class>/*
в”‚       в””в”Ђв”Ђ test/<class>/*
в””в”Ђв”Ђ splits/
    в”њв”Ђв”Ђ cifar100/
    в”‚   в”њв”Ђв”Ђ train_indices.npy
    в”‚   в””в”Ђв”Ђ val_indices.npy
    в”њв”Ђв”Ђ caltech256/
    в”‚   в””в”Ђв”Ђ normalization.json
    в”њв”Ђв”Ђ google4/
    в”‚   в””в”Ђв”Ђ normalization.json
    в”њв”Ђв”Ђ oxford102/
    в”‚   в””в”Ђв”Ђ normalization.json
    в””в”Ђв”Ђ stanford120/
        в””в”Ђв”Ђ normalization.json
```

If the Hub upload uses a flatter directory structure, the dataset identifiers and metadata filenames remain the same.

## Download

Install the required client:

```bash
pip install -U huggingface_hub
```

Download the complete repository:

```python
from huggingface_hub import snapshot_download

local_path = snapshot_download(
    repo_id="hermanhugging/thesis_stochastic_depth",
    repo_type="dataset",
)

print(local_path)
```

Download only one subset and its metadata:

```python
from huggingface_hub import snapshot_download

local_path = snapshot_download(
    repo_id="hermanhugging/thesis_stochastic_depth",
    repo_type="dataset",
    allow_patterns=[
        "data/processed/caltech256/**",
        "data/splits/caltech256/**",
        "caltech256/**",
        "splits/caltech256/**",
    ],
)

print(local_path)
```

## Loading the higher-resolution datasets with PyTorch

The four higher-resolution datasets use an `ImageFolder`-compatible split layout. Each dataset must be loaded with its own published `normalization.json`.

```python
import json
from pathlib import Path

from huggingface_hub import snapshot_download
from torchvision import transforms
from torchvision.datasets import ImageFolder

repo_dir = Path(
    snapshot_download(
        repo_id="hermanhugging/thesis_stochastic_depth",
        repo_type="dataset",
    )
)


def first_existing(*paths: Path) -> Path:
    for path in paths:
        if path.exists():
            return path
    raise FileNotFoundError(
        "None of the expected paths exists: "
        + ", ".join(str(path) for path in paths)
    )


def find_dataset_root(repo: Path, dataset_id: str) -> Path:
    return first_existing(
        repo / "data" / "processed" / dataset_id,
        repo / "processed" / dataset_id,
        repo / dataset_id,
    )


def find_split_root(repo: Path, dataset_id: str) -> Path:
    return first_existing(
        repo / "data" / "splits" / dataset_id,
        repo / "splits" / dataset_id,
        repo / dataset_id / "metadata",
        repo / dataset_id,
    )


def load_normalization(path: Path) -> tuple[list[float], list[float]]:
    data = json.loads(path.read_text(encoding="utf-8"))
    mean = data["mean"]
    std = data["std"]

    if len(mean) != 3 or len(std) != 3:
        raise ValueError(f"Expected RGB statistics in {path}")
    if any(value <= 0 for value in std):
        raise ValueError(f"Invalid standard deviation in {path}: {std}")

    return mean, std


def make_transforms(
    normalization_path: Path,
) -> tuple[transforms.Compose, transforms.Compose]:
    mean, std = load_normalization(normalization_path)

    train_transform = transforms.Compose([
        transforms.RandomRotation(15),
        transforms.RandomHorizontalFlip(),
        transforms.ColorJitter(
            brightness=0.2,
            contrast=0.2,
            saturation=0.2,
            hue=0.1,
        ),
        transforms.ToTensor(),
        transforms.Normalize(mean=mean, std=std),
    ])

    eval_transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.Normalize(mean=mean, std=std),
    ])

    return train_transform, eval_transform


dataset_id = "caltech256"  # google4, oxford102, or stanford120
root = find_dataset_root(repo_dir, dataset_id)
split_root = find_split_root(repo_dir, dataset_id)

train_transform, eval_transform = make_transforms(
    split_root / "normalization.json"
)

train_dataset = ImageFolder(root / "train", transform=train_transform)
val_dataset = ImageFolder(root / "val", transform=eval_transform)
test_dataset = ImageFolder(root / "test", transform=eval_transform)

print(len(train_dataset), len(val_dataset), len(test_dataset))
print(train_dataset.class_to_idx)
```

Replace `caltech256` with `google4`, `oxford102`, or `stanford120`. Do not reuse one dataset's normalization file for another dataset.

## Loading CIFAR-100 with the prepared indices

CIFAR-100 remains compatible with the official Python pickle format. The repository adds deterministic training and validation index arrays.

```python
from pathlib import Path

import numpy as np
from huggingface_hub import snapshot_download
from torch.utils.data import Subset
from torchvision.datasets import CIFAR100

repo_dir = Path(
    snapshot_download(
        repo_id="hermanhugging/thesis_stochastic_depth",
        repo_type="dataset",
    )
)

def first_existing(*paths: Path) -> Path:
    for path in paths:
        if path.exists():
            return path
    raise FileNotFoundError(
        "None of the expected paths exists: "
        + ", ".join(str(path) for path in paths)
    )

cifar_root = first_existing(
    repo_dir / "data" / "processed" / "cifar100",
    repo_dir / "processed" / "cifar100",
    repo_dir / "cifar100",
)

split_root = first_existing(
    repo_dir / "data" / "splits" / "cifar100",
    repo_dir / "splits" / "cifar100",
)

official_train_for_training = CIFAR100(
    root=str(cifar_root),
    train=True,
    transform=train_transform_cifar,
    download=False,
)

official_train_for_validation = CIFAR100(
    root=str(cifar_root),
    train=True,
    transform=eval_transform_cifar,
    download=False,
)

official_test = CIFAR100(
    root=str(cifar_root),
    train=False,
    transform=eval_transform_cifar,
    download=False,
)

train_indices = np.load(split_root / "train_indices.npy")
val_indices = np.load(split_root / "val_indices.npy")

train_dataset = Subset(official_train_for_training, train_indices)
val_dataset = Subset(official_train_for_validation, val_indices)
test_dataset = official_test

print(len(train_dataset), len(val_dataset), len(test_dataset))
```

Separate CIFAR-100 dataset objects are intentionally used for training and validation so that validation samples do not inherit random crop or horizontal-flip transforms.

## Recommended evaluation protocol

For results comparable with the thesis experiments:

1. use the published training split for optimization;
2. use validation accuracy for checkpoint selection;
3. do not tune hyperparameters on the test split;
4. load the checkpoint with the best validation top-1 accuracy;
5. evaluate the test split only after model selection;
6. report the training seed, architecture, batch size, optimizer configuration, and stochastic-depth variant.

## Intended uses

This collection is intended for:

- academic image-classification experiments;
- reproducibility studies;
- controlled comparisons of ResNet regularization methods;
- investigation of batch-level and sample-level stochastic depth;
- teaching and demonstration of deterministic dataset preparation;
- benchmarking under fixed train/validation/test membership.

## Out-of-scope uses

This repository is not designed or validated for:

- biometric identification or surveillance;
- safety-critical or high-stakes decision making;
- claims about human populations or demographic groups;
- commercial deployment without an independent rights review;
- treating accuracy across different datasets as directly comparable without accounting for differences in class count, difficulty, and source distribution.

## Limitations and known risks

- SHA-256 detects byte-identical files, not perceptual near-duplicates.
- Central cropping can remove content near the edge of an original image.
- The higher-resolution datasets have different collection processes and class distributions.
- Web-sourced datasets may contain unknown provenance, copyright restrictions, trademarks, artworks, or identifiable people.
- The Google-4 collection may reflect search-engine and web-publication biases.
- Caltech-256, Oxford Flowers-102, and Stanford Dogs contain class imbalance or fine-grained visual similarity that can affect metric interpretation.
- CIFAR-100 retains the official benchmark even when exact-image anomalies are detected.
- The collection was prepared for a specific thesis protocol and should not be interpreted as a universally optimal preprocessing scheme.
- The published normalization statistics are tied to the final prepared training split of each dataset and must be recomputed if the split membership or deterministic image preprocessing changes.

## Licensing

**Hugging Face metadata for this repository is intentionally set to `license: other`.**

This repository combines several third-party datasets with different or insufficiently explicit licensing information. A single permissive license such as MIT, Apache-2.0, CC0, or CC BY must not be presented as covering all image files.

The original images and source labels remain subject to the terms, restrictions, and rights of their respective sources and copyright holders. The repository's curation does not create new rights over third-party images.

See [`LICENSE.md`](./LICENSE.md) for the repository-wide licensing notice and dataset-specific source information.

For the most conservative distribution model, publish the split manifests, indices, preparation code, and checksums while requiring users to obtain the original image data from the official or cited sources. If image files are redistributed, the uploader is responsible for confirming that redistribution is permitted.

## Source datasets

| Dataset | Primary or used source |
|---|---|
| CIFAR-100 | https://www.cs.toronto.edu/~kriz/cifar.html |
| Caltech-256 | https://data.caltech.edu/records/nyy15-4j048 |
| Google Scraped Image Dataset | https://www.kaggle.com/datasets/duttadebadri/image-classification |
| Oxford Flowers-102 | https://www.robots.ox.ac.uk/~vgg/data/flowers/102/ |
| Oxford package used in the experiments | https://www.kaggle.com/datasets/yousefmohamed20/oxford-102-flower-dataset |
| Stanford Dogs | http://vision.stanford.edu/aditya86/ImageNetDogs/ |
| Stanford Dogs package used in the experiments | https://www.kaggle.com/datasets/jessicali9530/stanford-dogs-dataset |

## Citation

When using this prepared collection, please cite both the thesis and the original dataset relevant to your experiment.

### Thesis

```bibtex
@thesis{dihtenko2026stochasticdepth,
  author  = {Herman Dihtenko},
  title   = {A Study of ``Stochastic Depth'' for Regularizing Residual Convolutional Neural Networks},
  school  = {Catholic University of Eichstätt-Ingolstadt},
  type    = {Bachelor's thesis},
  year    = {2026}
}
```

### CIFAR-100

```bibtex
@techreport{krizhevsky2009learning,
  author = {Alex Krizhevsky},
  title  = {Learning Multiple Layers of Features from Tiny Images},
  year   = {2009}
}
```

### Caltech-256

```bibtex
@techreport{griffin2007caltech,
  author      = {Gregory Griffin and Alex Holub and Pietro Perona},
  title       = {Caltech-256 Object Category Dataset},
  institution = {California Institute of Technology},
  year        = {2007}
}
```

### Oxford Flowers-102

```bibtex
@inproceedings{nilsback2008automated,
  author    = {Maria-Elena Nilsback and Andrew Zisserman},
  title     = {Automated Flower Classification over a Large Number of Classes},
  booktitle = {Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing},
  year      = {2008}
}
```

### Stanford Dogs

```bibtex
@inproceedings{khosla2011novel,
  author    = {Aditya Khosla and Nityananda Jayadevaprakash and Bangpeng Yao and Li Fei-Fei},
  title     = {Novel Dataset for Fine-Grained Image Categorization: Stanford Dogs},
  booktitle = {CVPR Workshop on Fine-Grained Visual Categorization},
  year      = {2011}
}
```

## Maintainer

**Herman Dihtenko**

For questions about split generation, preprocessing, or the thesis experiments, please use the issue tracker in the accompanying GitHub repository.