Delete cifar10_lt.py
Browse files- cifar10_lt.py +0 -221
cifar10_lt.py
DELETED
|
@@ -1,221 +0,0 @@
|
|
| 1 |
-
# coding=utf-8
|
| 2 |
-
# Copyright 2020 …
|
| 3 |
-
# (license header unchanged)
|
| 4 |
-
|
| 5 |
-
"""CIFAR-10-LT Dataset (HF Datasets 3.6 compatible)"""
|
| 6 |
-
|
| 7 |
-
import os
|
| 8 |
-
import pickle
|
| 9 |
-
from typing import Dict, Iterator, List, Tuple
|
| 10 |
-
|
| 11 |
-
import numpy as np
|
| 12 |
-
import datasets
|
| 13 |
-
|
| 14 |
-
_CITATION = """\
|
| 15 |
-
@TECHREPORT{Krizhevsky09learningmultiple,
|
| 16 |
-
author = {Alex Krizhevsky},
|
| 17 |
-
title = {Learning multiple layers of features from tiny images},
|
| 18 |
-
institution = {},
|
| 19 |
-
year = {2009}
|
| 20 |
-
}
|
| 21 |
-
"""
|
| 22 |
-
|
| 23 |
-
_DESCRIPTION = """\
|
| 24 |
-
The CIFAR-10-LT imbalanced dataset is comprised of under 60,000 color images (32×32),
|
| 25 |
-
across 10 classes. The test set has 10,000 images (1,000 per class).
|
| 26 |
-
The training set is imbalanced with exponential factors of 10, 20, 50, 100, or 200.
|
| 27 |
-
"""
|
| 28 |
-
|
| 29 |
-
_DATA_URL = "https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz"
|
| 30 |
-
|
| 31 |
-
_NAMES = [
|
| 32 |
-
"airplane",
|
| 33 |
-
"automobile",
|
| 34 |
-
"bird",
|
| 35 |
-
"cat",
|
| 36 |
-
"deer",
|
| 37 |
-
"dog",
|
| 38 |
-
"frog",
|
| 39 |
-
"horse",
|
| 40 |
-
"ship",
|
| 41 |
-
"truck",
|
| 42 |
-
]
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
class Cifar10LTConfig(datasets.BuilderConfig):
|
| 46 |
-
"""BuilderConfig for CIFAR-10-LT."""
|
| 47 |
-
|
| 48 |
-
def __init__(
|
| 49 |
-
self,
|
| 50 |
-
imb_type: str,
|
| 51 |
-
imb_factor: float,
|
| 52 |
-
rand_number: int = 0,
|
| 53 |
-
cls_num: int = 10,
|
| 54 |
-
**kwargs
|
| 55 |
-
):
|
| 56 |
-
super().__init__(version=datasets.Version("1.0.1"), **kwargs)
|
| 57 |
-
self.imb_type = imb_type
|
| 58 |
-
self.imb_factor = float(imb_factor)
|
| 59 |
-
self.rand_number = int(rand_number)
|
| 60 |
-
self.cls_num = int(cls_num)
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
class Cifar10(datasets.GeneratorBasedBuilder):
|
| 64 |
-
"""CIFAR-10-LT Dataset"""
|
| 65 |
-
|
| 66 |
-
BUILDER_CONFIGS = [
|
| 67 |
-
Cifar10LTConfig(
|
| 68 |
-
name="r-10", description="CIFAR-10-LT-r-10", imb_type="exp", imb_factor=1 / 10
|
| 69 |
-
),
|
| 70 |
-
Cifar10LTConfig(
|
| 71 |
-
name="r-20", description="CIFAR-10-LT-r-20", imb_type="exp", imb_factor=1 / 20
|
| 72 |
-
),
|
| 73 |
-
Cifar10LTConfig(
|
| 74 |
-
name="r-50", description="CIFAR-10-LT-r-50", imb_type="exp", imb_factor=1 / 50
|
| 75 |
-
),
|
| 76 |
-
Cifar10LTConfig(
|
| 77 |
-
name="r-100", description="CIFAR-10-LT-r-100", imb_type="exp", imb_factor=1 / 100
|
| 78 |
-
),
|
| 79 |
-
Cifar10LTConfig(
|
| 80 |
-
name="r-200", description="CIFAR-10-LT-r-200", imb_type="exp", imb_factor=1 / 200
|
| 81 |
-
),
|
| 82 |
-
]
|
| 83 |
-
|
| 84 |
-
def _info(self) -> datasets.DatasetInfo:
|
| 85 |
-
return datasets.DatasetInfo(
|
| 86 |
-
description=_DESCRIPTION,
|
| 87 |
-
features=datasets.Features(
|
| 88 |
-
{
|
| 89 |
-
"img": datasets.Image(), # stores HWC uint8
|
| 90 |
-
"label": datasets.ClassLabel(names=_NAMES),
|
| 91 |
-
}
|
| 92 |
-
),
|
| 93 |
-
supervised_keys=None,
|
| 94 |
-
homepage="https://www.cs.toronto.edu/~kriz/cifar.html",
|
| 95 |
-
citation=_CITATION,
|
| 96 |
-
)
|
| 97 |
-
|
| 98 |
-
# ---------- split planning / index generation ----------
|
| 99 |
-
|
| 100 |
-
def _split_generators(self, dl_manager: datasets.DownloadManager):
|
| 101 |
-
# Extract once to a directory; avoids relying on iter_archive inside generators.
|
| 102 |
-
extracted_dir = dl_manager.download_and_extract(_DATA_URL)
|
| 103 |
-
|
| 104 |
-
# Inside the tar, CIFAR lives under "cifar-10-batches-py"
|
| 105 |
-
data_root = os.path.join(extracted_dir, "cifar-10-batches-py")
|
| 106 |
-
|
| 107 |
-
# Precompute LT indices for the train split deterministically
|
| 108 |
-
train_labels = self._collect_labels_from_dir(data_root, split="train")
|
| 109 |
-
img_num_per_cls = self._get_img_num_per_cls(len(train_labels))
|
| 110 |
-
rs = np.random.RandomState(self.config.rand_number)
|
| 111 |
-
train_indices, _ = self._gen_imbalanced_data(img_num_per_cls, train_labels, rs)
|
| 112 |
-
|
| 113 |
-
return [
|
| 114 |
-
datasets.SplitGenerator(
|
| 115 |
-
name=datasets.Split.TRAIN,
|
| 116 |
-
gen_kwargs={
|
| 117 |
-
"data_root": data_root,
|
| 118 |
-
"split": "train",
|
| 119 |
-
# Pass a JSON-serializable type; we'll cast to set later for speed.
|
| 120 |
-
"selected_indices": sorted(int(i) for i in train_indices),
|
| 121 |
-
},
|
| 122 |
-
),
|
| 123 |
-
datasets.SplitGenerator(
|
| 124 |
-
name=datasets.Split.TEST,
|
| 125 |
-
gen_kwargs={"data_root": data_root, "split": "test", "selected_indices": None},
|
| 126 |
-
),
|
| 127 |
-
]
|
| 128 |
-
|
| 129 |
-
@staticmethod
|
| 130 |
-
def _batch_files_in_dir(data_root: str, split: str) -> List[str]:
|
| 131 |
-
if split == "train":
|
| 132 |
-
batches = ["data_batch_1", "data_batch_2", "data_batch_3", "data_batch_4", "data_batch_5"]
|
| 133 |
-
elif split == "test":
|
| 134 |
-
batches = ["test_batch"]
|
| 135 |
-
else:
|
| 136 |
-
raise ValueError(f"Unknown split: {split}")
|
| 137 |
-
return [os.path.join(data_root, b) for b in batches]
|
| 138 |
-
|
| 139 |
-
def _collect_labels_from_dir(self, data_root: str, split: str) -> List[int]:
|
| 140 |
-
"""Read labels across all CIFAR batches for a split (from extracted files)."""
|
| 141 |
-
labels_all: List[int] = []
|
| 142 |
-
for path in self._batch_files_in_dir(data_root, split):
|
| 143 |
-
with open(path, "rb") as fo:
|
| 144 |
-
d = pickle.load(fo, encoding="latin1")
|
| 145 |
-
# Handle both bytes and str keys robustly
|
| 146 |
-
labels = d.get("labels", d.get(b"labels"))
|
| 147 |
-
if labels is None:
|
| 148 |
-
raise KeyError(f"'labels' not found in {path}")
|
| 149 |
-
labels_all.extend(labels)
|
| 150 |
-
return labels_all
|
| 151 |
-
|
| 152 |
-
def _get_img_num_per_cls(self, data_length: int) -> List[int]:
|
| 153 |
-
"""Number of images per class given imbalance ratio and total length."""
|
| 154 |
-
img_max = data_length / self.config.cls_num
|
| 155 |
-
img_num_per_cls: List[int] = []
|
| 156 |
-
if self.config.imb_type == "exp":
|
| 157 |
-
for cls_idx in range(self.config.cls_num):
|
| 158 |
-
num = img_max * (self.config.imb_factor ** (cls_idx / (self.config.cls_num - 1.0)))
|
| 159 |
-
img_num_per_cls.append(int(num))
|
| 160 |
-
elif self.config.imb_type == "step":
|
| 161 |
-
for _ in range(self.config.cls_num // 2):
|
| 162 |
-
img_num_per_cls.append(int(img_max))
|
| 163 |
-
for _ in range(self.config.cls_num // 2):
|
| 164 |
-
img_num_per_cls.append(int(img_max * self.config.imb_factor))
|
| 165 |
-
else:
|
| 166 |
-
img_num_per_cls.extend([int(img_max)] * self.config.cls_num)
|
| 167 |
-
return img_num_per_cls
|
| 168 |
-
|
| 169 |
-
def _gen_imbalanced_data(
|
| 170 |
-
self, img_num_per_cls: List[int], targets: List[int], rs: np.random.RandomState
|
| 171 |
-
) -> Tuple[List[int], Dict[int, int]]:
|
| 172 |
-
"""Return selected indices (global over concatenated train set) and per-class counts."""
|
| 173 |
-
new_indices: List[int] = []
|
| 174 |
-
targets_np = np.array(targets, dtype=np.int64)
|
| 175 |
-
classes = np.unique(targets_np)
|
| 176 |
-
num_per_cls_dict: Dict[int, int] = {}
|
| 177 |
-
for the_class, the_img_num in zip(classes, img_num_per_cls):
|
| 178 |
-
num_per_cls_dict[int(the_class)] = int(the_img_num)
|
| 179 |
-
idx = np.where(targets_np == the_class)[0]
|
| 180 |
-
rs.shuffle(idx)
|
| 181 |
-
selec_idx = idx[:the_img_num]
|
| 182 |
-
new_indices.extend(selec_idx.tolist())
|
| 183 |
-
return new_indices, num_per_cls_dict
|
| 184 |
-
|
| 185 |
-
# ---------- example generation ----------
|
| 186 |
-
|
| 187 |
-
def _generate_examples(self, data_root: str, split: str, selected_indices=None):
|
| 188 |
-
"""
|
| 189 |
-
Yields (key, example) pairs.
|
| 190 |
-
For train: only indices in `selected_indices` are yielded (LT subset).
|
| 191 |
-
For test: all examples are yielded.
|
| 192 |
-
"""
|
| 193 |
-
batch_paths = self._batch_files_in_dir(data_root, split)
|
| 194 |
-
|
| 195 |
-
# For quick membership checks
|
| 196 |
-
selected_set = set(selected_indices) if selected_indices is not None else None
|
| 197 |
-
|
| 198 |
-
global_idx = 0 # global index across all batches in CIFAR order
|
| 199 |
-
|
| 200 |
-
for path in batch_paths:
|
| 201 |
-
with open(path, "rb") as fo:
|
| 202 |
-
d = pickle.load(fo, encoding="latin1")
|
| 203 |
-
|
| 204 |
-
labels = d.get("labels", d.get(b"labels"))
|
| 205 |
-
data = d.get("data", d.get(b"data"))
|
| 206 |
-
if labels is None or data is None:
|
| 207 |
-
raise KeyError(f"Missing 'labels' or 'data' in {path}")
|
| 208 |
-
|
| 209 |
-
# (N, 3072) CHW packed uint8
|
| 210 |
-
num_in_batch = len(labels)
|
| 211 |
-
for i in range(num_in_batch):
|
| 212 |
-
# Train split: only yield if selected
|
| 213 |
-
if selected_set is not None and (global_idx not in selected_set):
|
| 214 |
-
global_idx += 1
|
| 215 |
-
continue
|
| 216 |
-
|
| 217 |
-
# reshape to HWC uint8
|
| 218 |
-
img = np.reshape(data[i], (3, 32, 32)).transpose(1, 2, 0)
|
| 219 |
-
|
| 220 |
-
yield f"{os.path.basename(path)}_{i}", {"img": img, "label": int(labels[i])}
|
| 221 |
-
global_idx += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|