TNauen commited on
Commit
57e1c5c
·
verified ·
1 Parent(s): 32e4aee

Create ForNet.py

Browse files
Files changed (1) hide show
  1. ForNet.py +1690 -0
ForNet.py ADDED
@@ -0,0 +1,1690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gzip
2
+ import itertools
3
+ import json
4
+ import multiprocessing
5
+ import os
6
+ import pickle
7
+ import queue
8
+ import re
9
+ import urllib
10
+ import zipfile
11
+ from collections import OrderedDict
12
+ from math import floor
13
+ from typing import Optional
14
+
15
+ import datasets
16
+ import numpy as np
17
+ from datasets import config
18
+ from datasets.arrow_dataset import Dataset
19
+ from datasets.arrow_reader import ArrowReader
20
+ from datasets.fingerprint import Hasher
21
+ from PIL import ImageFilter
22
+ from torchvision import transforms as T
23
+ from tqdm import tqdm
24
+
25
+ logger = datasets.logging.get_logger(__name__)
26
+
27
+
28
+ # taken from https://huggingface.co/datasets/ILSVRC/imagenet-1k/blob/main/classes.py
29
+ IMAGENET2012_CLASSES = OrderedDict(
30
+ {
31
+ "n01440764": "tench, Tinca tinca",
32
+ "n01443537": "goldfish, Carassius auratus",
33
+ "n01484850": "great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias",
34
+ "n01491361": "tiger shark, Galeocerdo cuvieri",
35
+ "n01494475": "hammerhead, hammerhead shark",
36
+ "n01496331": "electric ray, crampfish, numbfish, torpedo",
37
+ "n01498041": "stingray",
38
+ "n01514668": "cock",
39
+ "n01514859": "hen",
40
+ "n01518878": "ostrich, Struthio camelus",
41
+ "n01530575": "brambling, Fringilla montifringilla",
42
+ "n01531178": "goldfinch, Carduelis carduelis",
43
+ "n01532829": "house finch, linnet, Carpodacus mexicanus",
44
+ "n01534433": "junco, snowbird",
45
+ "n01537544": "indigo bunting, indigo finch, indigo bird, Passerina cyanea",
46
+ "n01558993": "robin, American robin, Turdus migratorius",
47
+ "n01560419": "bulbul",
48
+ "n01580077": "jay",
49
+ "n01582220": "magpie",
50
+ "n01592084": "chickadee",
51
+ "n01601694": "water ouzel, dipper",
52
+ "n01608432": "kite",
53
+ "n01614925": "bald eagle, American eagle, Haliaeetus leucocephalus",
54
+ "n01616318": "vulture",
55
+ "n01622779": "great grey owl, great gray owl, Strix nebulosa",
56
+ "n01629819": "European fire salamander, Salamandra salamandra",
57
+ "n01630670": "common newt, Triturus vulgaris",
58
+ "n01631663": "eft",
59
+ "n01632458": "spotted salamander, Ambystoma maculatum",
60
+ "n01632777": "axolotl, mud puppy, Ambystoma mexicanum",
61
+ "n01641577": "bullfrog, Rana catesbeiana",
62
+ "n01644373": "tree frog, tree-frog",
63
+ "n01644900": "tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui",
64
+ "n01664065": "loggerhead, loggerhead turtle, Caretta caretta",
65
+ "n01665541": "leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea",
66
+ "n01667114": "mud turtle",
67
+ "n01667778": "terrapin",
68
+ "n01669191": "box turtle, box tortoise",
69
+ "n01675722": "banded gecko",
70
+ "n01677366": "common iguana, iguana, Iguana iguana",
71
+ "n01682714": "American chameleon, anole, Anolis carolinensis",
72
+ "n01685808": "whiptail, whiptail lizard",
73
+ "n01687978": "agama",
74
+ "n01688243": "frilled lizard, Chlamydosaurus kingi",
75
+ "n01689811": "alligator lizard",
76
+ "n01692333": "Gila monster, Heloderma suspectum",
77
+ "n01693334": "green lizard, Lacerta viridis",
78
+ "n01694178": "African chameleon, Chamaeleo chamaeleon",
79
+ "n01695060": "Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis",
80
+ "n01697457": "African crocodile, Nile crocodile, Crocodylus niloticus",
81
+ "n01698640": "American alligator, Alligator mississipiensis",
82
+ "n01704323": "triceratops",
83
+ "n01728572": "thunder snake, worm snake, Carphophis amoenus",
84
+ "n01728920": "ringneck snake, ring-necked snake, ring snake",
85
+ "n01729322": "hognose snake, puff adder, sand viper",
86
+ "n01729977": "green snake, grass snake",
87
+ "n01734418": "king snake, kingsnake",
88
+ "n01735189": "garter snake, grass snake",
89
+ "n01737021": "water snake",
90
+ "n01739381": "vine snake",
91
+ "n01740131": "night snake, Hypsiglena torquata",
92
+ "n01742172": "boa constrictor, Constrictor constrictor",
93
+ "n01744401": "rock python, rock snake, Python sebae",
94
+ "n01748264": "Indian cobra, Naja naja",
95
+ "n01749939": "green mamba",
96
+ "n01751748": "sea snake",
97
+ "n01753488": "horned viper, cerastes, sand viper, horned asp, Cerastes cornutus",
98
+ "n01755581": "diamondback, diamondback rattlesnake, Crotalus adamanteus",
99
+ "n01756291": "sidewinder, horned rattlesnake, Crotalus cerastes",
100
+ "n01768244": "trilobite",
101
+ "n01770081": "harvestman, daddy longlegs, Phalangium opilio",
102
+ "n01770393": "scorpion",
103
+ "n01773157": "black and gold garden spider, Argiope aurantia",
104
+ "n01773549": "barn spider, Araneus cavaticus",
105
+ "n01773797": "garden spider, Aranea diademata",
106
+ "n01774384": "black widow, Latrodectus mactans",
107
+ "n01774750": "tarantula",
108
+ "n01775062": "wolf spider, hunting spider",
109
+ "n01776313": "tick",
110
+ "n01784675": "centipede",
111
+ "n01795545": "black grouse",
112
+ "n01796340": "ptarmigan",
113
+ "n01797886": "ruffed grouse, partridge, Bonasa umbellus",
114
+ "n01798484": "prairie chicken, prairie grouse, prairie fowl",
115
+ "n01806143": "peacock",
116
+ "n01806567": "quail",
117
+ "n01807496": "partridge",
118
+ "n01817953": "African grey, African gray, Psittacus erithacus",
119
+ "n01818515": "macaw",
120
+ "n01819313": "sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita",
121
+ "n01820546": "lorikeet",
122
+ "n01824575": "coucal",
123
+ "n01828970": "bee eater",
124
+ "n01829413": "hornbill",
125
+ "n01833805": "hummingbird",
126
+ "n01843065": "jacamar",
127
+ "n01843383": "toucan",
128
+ "n01847000": "drake",
129
+ "n01855032": "red-breasted merganser, Mergus serrator",
130
+ "n01855672": "goose",
131
+ "n01860187": "black swan, Cygnus atratus",
132
+ "n01871265": "tusker",
133
+ "n01872401": "echidna, spiny anteater, anteater",
134
+ "n01873310": "platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus",
135
+ "n01877812": "wallaby, brush kangaroo",
136
+ "n01882714": "koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus",
137
+ "n01883070": "wombat",
138
+ "n01910747": "jellyfish",
139
+ "n01914609": "sea anemone, anemone",
140
+ "n01917289": "brain coral",
141
+ "n01924916": "flatworm, platyhelminth",
142
+ "n01930112": "nematode, nematode worm, roundworm",
143
+ "n01943899": "conch",
144
+ "n01944390": "snail",
145
+ "n01945685": "slug",
146
+ "n01950731": "sea slug, nudibranch",
147
+ "n01955084": "chiton, coat-of-mail shell, sea cradle, polyplacophore",
148
+ "n01968897": "chambered nautilus, pearly nautilus, nautilus",
149
+ "n01978287": "Dungeness crab, Cancer magister",
150
+ "n01978455": "rock crab, Cancer irroratus",
151
+ "n01980166": "fiddler crab",
152
+ "n01981276": "king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica",
153
+ "n01983481": "American lobster, Northern lobster, Maine lobster, Homarus americanus",
154
+ "n01984695": "spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish",
155
+ "n01985128": "crayfish, crawfish, crawdad, crawdaddy",
156
+ "n01986214": "hermit crab",
157
+ "n01990800": "isopod",
158
+ "n02002556": "white stork, Ciconia ciconia",
159
+ "n02002724": "black stork, Ciconia nigra",
160
+ "n02006656": "spoonbill",
161
+ "n02007558": "flamingo",
162
+ "n02009229": "little blue heron, Egretta caerulea",
163
+ "n02009912": "American egret, great white heron, Egretta albus",
164
+ "n02011460": "bittern",
165
+ "n02012849": "crane",
166
+ "n02013706": "limpkin, Aramus pictus",
167
+ "n02017213": "European gallinule, Porphyrio porphyrio",
168
+ "n02018207": "American coot, marsh hen, mud hen, water hen, Fulica americana",
169
+ "n02018795": "bustard",
170
+ "n02025239": "ruddy turnstone, Arenaria interpres",
171
+ "n02027492": "red-backed sandpiper, dunlin, Erolia alpina",
172
+ "n02028035": "redshank, Tringa totanus",
173
+ "n02033041": "dowitcher",
174
+ "n02037110": "oystercatcher, oyster catcher",
175
+ "n02051845": "pelican",
176
+ "n02056570": "king penguin, Aptenodytes patagonica",
177
+ "n02058221": "albatross, mollymawk",
178
+ "n02066245": "grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus",
179
+ "n02071294": "killer whale, killer, orca, grampus, sea wolf, Orcinus orca",
180
+ "n02074367": "dugong, Dugong dugon",
181
+ "n02077923": "sea lion",
182
+ "n02085620": "Chihuahua",
183
+ "n02085782": "Japanese spaniel",
184
+ "n02085936": "Maltese dog, Maltese terrier, Maltese",
185
+ "n02086079": "Pekinese, Pekingese, Peke",
186
+ "n02086240": "Shih-Tzu",
187
+ "n02086646": "Blenheim spaniel",
188
+ "n02086910": "papillon",
189
+ "n02087046": "toy terrier",
190
+ "n02087394": "Rhodesian ridgeback",
191
+ "n02088094": "Afghan hound, Afghan",
192
+ "n02088238": "basset, basset hound",
193
+ "n02088364": "beagle",
194
+ "n02088466": "bloodhound, sleuthhound",
195
+ "n02088632": "bluetick",
196
+ "n02089078": "black-and-tan coonhound",
197
+ "n02089867": "Walker hound, Walker foxhound",
198
+ "n02089973": "English foxhound",
199
+ "n02090379": "redbone",
200
+ "n02090622": "borzoi, Russian wolfhound",
201
+ "n02090721": "Irish wolfhound",
202
+ "n02091032": "Italian greyhound",
203
+ "n02091134": "whippet",
204
+ "n02091244": "Ibizan hound, Ibizan Podenco",
205
+ "n02091467": "Norwegian elkhound, elkhound",
206
+ "n02091635": "otterhound, otter hound",
207
+ "n02091831": "Saluki, gazelle hound",
208
+ "n02092002": "Scottish deerhound, deerhound",
209
+ "n02092339": "Weimaraner",
210
+ "n02093256": "Staffordshire bullterrier, Staffordshire bull terrier",
211
+ "n02093428": "American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier",
212
+ "n02093647": "Bedlington terrier",
213
+ "n02093754": "Border terrier",
214
+ "n02093859": "Kerry blue terrier",
215
+ "n02093991": "Irish terrier",
216
+ "n02094114": "Norfolk terrier",
217
+ "n02094258": "Norwich terrier",
218
+ "n02094433": "Yorkshire terrier",
219
+ "n02095314": "wire-haired fox terrier",
220
+ "n02095570": "Lakeland terrier",
221
+ "n02095889": "Sealyham terrier, Sealyham",
222
+ "n02096051": "Airedale, Airedale terrier",
223
+ "n02096177": "cairn, cairn terrier",
224
+ "n02096294": "Australian terrier",
225
+ "n02096437": "Dandie Dinmont, Dandie Dinmont terrier",
226
+ "n02096585": "Boston bull, Boston terrier",
227
+ "n02097047": "miniature schnauzer",
228
+ "n02097130": "giant schnauzer",
229
+ "n02097209": "standard schnauzer",
230
+ "n02097298": "Scotch terrier, Scottish terrier, Scottie",
231
+ "n02097474": "Tibetan terrier, chrysanthemum dog",
232
+ "n02097658": "silky terrier, Sydney silky",
233
+ "n02098105": "soft-coated wheaten terrier",
234
+ "n02098286": "West Highland white terrier",
235
+ "n02098413": "Lhasa, Lhasa apso",
236
+ "n02099267": "flat-coated retriever",
237
+ "n02099429": "curly-coated retriever",
238
+ "n02099601": "golden retriever",
239
+ "n02099712": "Labrador retriever",
240
+ "n02099849": "Chesapeake Bay retriever",
241
+ "n02100236": "German short-haired pointer",
242
+ "n02100583": "vizsla, Hungarian pointer",
243
+ "n02100735": "English setter",
244
+ "n02100877": "Irish setter, red setter",
245
+ "n02101006": "Gordon setter",
246
+ "n02101388": "Brittany spaniel",
247
+ "n02101556": "clumber, clumber spaniel",
248
+ "n02102040": "English springer, English springer spaniel",
249
+ "n02102177": "Welsh springer spaniel",
250
+ "n02102318": "cocker spaniel, English cocker spaniel, cocker",
251
+ "n02102480": "Sussex spaniel",
252
+ "n02102973": "Irish water spaniel",
253
+ "n02104029": "kuvasz",
254
+ "n02104365": "schipperke",
255
+ "n02105056": "groenendael",
256
+ "n02105162": "malinois",
257
+ "n02105251": "briard",
258
+ "n02105412": "kelpie",
259
+ "n02105505": "komondor",
260
+ "n02105641": "Old English sheepdog, bobtail",
261
+ "n02105855": "Shetland sheepdog, Shetland sheep dog, Shetland",
262
+ "n02106030": "collie",
263
+ "n02106166": "Border collie",
264
+ "n02106382": "Bouvier des Flandres, Bouviers des Flandres",
265
+ "n02106550": "Rottweiler",
266
+ "n02106662": "German shepherd, German shepherd dog, German police dog, alsatian",
267
+ "n02107142": "Doberman, Doberman pinscher",
268
+ "n02107312": "miniature pinscher",
269
+ "n02107574": "Greater Swiss Mountain dog",
270
+ "n02107683": "Bernese mountain dog",
271
+ "n02107908": "Appenzeller",
272
+ "n02108000": "EntleBucher",
273
+ "n02108089": "boxer",
274
+ "n02108422": "bull mastiff",
275
+ "n02108551": "Tibetan mastiff",
276
+ "n02108915": "French bulldog",
277
+ "n02109047": "Great Dane",
278
+ "n02109525": "Saint Bernard, St Bernard",
279
+ "n02109961": "Eskimo dog, husky",
280
+ "n02110063": "malamute, malemute, Alaskan malamute",
281
+ "n02110185": "Siberian husky",
282
+ "n02110341": "dalmatian, coach dog, carriage dog",
283
+ "n02110627": "affenpinscher, monkey pinscher, monkey dog",
284
+ "n02110806": "basenji",
285
+ "n02110958": "pug, pug-dog",
286
+ "n02111129": "Leonberg",
287
+ "n02111277": "Newfoundland, Newfoundland dog",
288
+ "n02111500": "Great Pyrenees",
289
+ "n02111889": "Samoyed, Samoyede",
290
+ "n02112018": "Pomeranian",
291
+ "n02112137": "chow, chow chow",
292
+ "n02112350": "keeshond",
293
+ "n02112706": "Brabancon griffon",
294
+ "n02113023": "Pembroke, Pembroke Welsh corgi",
295
+ "n02113186": "Cardigan, Cardigan Welsh corgi",
296
+ "n02113624": "toy poodle",
297
+ "n02113712": "miniature poodle",
298
+ "n02113799": "standard poodle",
299
+ "n02113978": "Mexican hairless",
300
+ "n02114367": "timber wolf, grey wolf, gray wolf, Canis lupus",
301
+ "n02114548": "white wolf, Arctic wolf, Canis lupus tundrarum",
302
+ "n02114712": "red wolf, maned wolf, Canis rufus, Canis niger",
303
+ "n02114855": "coyote, prairie wolf, brush wolf, Canis latrans",
304
+ "n02115641": "dingo, warrigal, warragal, Canis dingo",
305
+ "n02115913": "dhole, Cuon alpinus",
306
+ "n02116738": "African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus",
307
+ "n02117135": "hyena, hyaena",
308
+ "n02119022": "red fox, Vulpes vulpes",
309
+ "n02119789": "kit fox, Vulpes macrotis",
310
+ "n02120079": "Arctic fox, white fox, Alopex lagopus",
311
+ "n02120505": "grey fox, gray fox, Urocyon cinereoargenteus",
312
+ "n02123045": "tabby, tabby cat",
313
+ "n02123159": "tiger cat",
314
+ "n02123394": "Persian cat",
315
+ "n02123597": "Siamese cat, Siamese",
316
+ "n02124075": "Egyptian cat",
317
+ "n02125311": "cougar, puma, catamount, mountain lion, painter, panther, Felis concolor",
318
+ "n02127052": "lynx, catamount",
319
+ "n02128385": "leopard, Panthera pardus",
320
+ "n02128757": "snow leopard, ounce, Panthera uncia",
321
+ "n02128925": "jaguar, panther, Panthera onca, Felis onca",
322
+ "n02129165": "lion, king of beasts, Panthera leo",
323
+ "n02129604": "tiger, Panthera tigris",
324
+ "n02130308": "cheetah, chetah, Acinonyx jubatus",
325
+ "n02132136": "brown bear, bruin, Ursus arctos",
326
+ "n02133161": "American black bear, black bear, Ursus americanus, Euarctos americanus",
327
+ "n02134084": "ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus",
328
+ "n02134418": "sloth bear, Melursus ursinus, Ursus ursinus",
329
+ "n02137549": "mongoose",
330
+ "n02138441": "meerkat, mierkat",
331
+ "n02165105": "tiger beetle",
332
+ "n02165456": "ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle",
333
+ "n02167151": "ground beetle, carabid beetle",
334
+ "n02168699": "long-horned beetle, longicorn, longicorn beetle",
335
+ "n02169497": "leaf beetle, chrysomelid",
336
+ "n02172182": "dung beetle",
337
+ "n02174001": "rhinoceros beetle",
338
+ "n02177972": "weevil",
339
+ "n02190166": "fly",
340
+ "n02206856": "bee",
341
+ "n02219486": "ant, emmet, pismire",
342
+ "n02226429": "grasshopper, hopper",
343
+ "n02229544": "cricket",
344
+ "n02231487": "walking stick, walkingstick, stick insect",
345
+ "n02233338": "cockroach, roach",
346
+ "n02236044": "mantis, mantid",
347
+ "n02256656": "cicada, cicala",
348
+ "n02259212": "leafhopper",
349
+ "n02264363": "lacewing, lacewing fly",
350
+ "n02268443": "dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk",
351
+ "n02268853": "damselfly",
352
+ "n02276258": "admiral",
353
+ "n02277742": "ringlet, ringlet butterfly",
354
+ "n02279972": "monarch, monarch butterfly, milkweed butterfly, Danaus plexippus",
355
+ "n02280649": "cabbage butterfly",
356
+ "n02281406": "sulphur butterfly, sulfur butterfly",
357
+ "n02281787": "lycaenid, lycaenid butterfly",
358
+ "n02317335": "starfish, sea star",
359
+ "n02319095": "sea urchin",
360
+ "n02321529": "sea cucumber, holothurian",
361
+ "n02325366": "wood rabbit, cottontail, cottontail rabbit",
362
+ "n02326432": "hare",
363
+ "n02328150": "Angora, Angora rabbit",
364
+ "n02342885": "hamster",
365
+ "n02346627": "porcupine, hedgehog",
366
+ "n02356798": "fox squirrel, eastern fox squirrel, Sciurus niger",
367
+ "n02361337": "marmot",
368
+ "n02363005": "beaver",
369
+ "n02364673": "guinea pig, Cavia cobaya",
370
+ "n02389026": "sorrel",
371
+ "n02391049": "zebra",
372
+ "n02395406": "hog, pig, grunter, squealer, Sus scrofa",
373
+ "n02396427": "wild boar, boar, Sus scrofa",
374
+ "n02397096": "warthog",
375
+ "n02398521": "hippopotamus, hippo, river horse, Hippopotamus amphibius",
376
+ "n02403003": "ox",
377
+ "n02408429": "water buffalo, water ox, Asiatic buffalo, Bubalus bubalis",
378
+ "n02410509": "bison",
379
+ "n02412080": "ram, tup",
380
+ "n02415577": "bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis",
381
+ "n02417914": "ibex, Capra ibex",
382
+ "n02422106": "hartebeest",
383
+ "n02422699": "impala, Aepyceros melampus",
384
+ "n02423022": "gazelle",
385
+ "n02437312": "Arabian camel, dromedary, Camelus dromedarius",
386
+ "n02437616": "llama",
387
+ "n02441942": "weasel",
388
+ "n02442845": "mink",
389
+ "n02443114": "polecat, fitch, foulmart, foumart, Mustela putorius",
390
+ "n02443484": "black-footed ferret, ferret, Mustela nigripes",
391
+ "n02444819": "otter",
392
+ "n02445715": "skunk, polecat, wood pussy",
393
+ "n02447366": "badger",
394
+ "n02454379": "armadillo",
395
+ "n02457408": "three-toed sloth, ai, Bradypus tridactylus",
396
+ "n02480495": "orangutan, orang, orangutang, Pongo pygmaeus",
397
+ "n02480855": "gorilla, Gorilla gorilla",
398
+ "n02481823": "chimpanzee, chimp, Pan troglodytes",
399
+ "n02483362": "gibbon, Hylobates lar",
400
+ "n02483708": "siamang, Hylobates syndactylus, Symphalangus syndactylus",
401
+ "n02484975": "guenon, guenon monkey",
402
+ "n02486261": "patas, hussar monkey, Erythrocebus patas",
403
+ "n02486410": "baboon",
404
+ "n02487347": "macaque",
405
+ "n02488291": "langur",
406
+ "n02488702": "colobus, colobus monkey",
407
+ "n02489166": "proboscis monkey, Nasalis larvatus",
408
+ "n02490219": "marmoset",
409
+ "n02492035": "capuchin, ringtail, Cebus capucinus",
410
+ "n02492660": "howler monkey, howler",
411
+ "n02493509": "titi, titi monkey",
412
+ "n02493793": "spider monkey, Ateles geoffroyi",
413
+ "n02494079": "squirrel monkey, Saimiri sciureus",
414
+ "n02497673": "Madagascar cat, ring-tailed lemur, Lemur catta",
415
+ "n02500267": "indri, indris, Indri indri, Indri brevicaudatus",
416
+ "n02504013": "Indian elephant, Elephas maximus",
417
+ "n02504458": "African elephant, Loxodonta africana",
418
+ "n02509815": "lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens",
419
+ "n02510455": "giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca",
420
+ "n02514041": "barracouta, snoek",
421
+ "n02526121": "eel",
422
+ "n02536864": "coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch",
423
+ "n02606052": "rock beauty, Holocanthus tricolor",
424
+ "n02607072": "anemone fish",
425
+ "n02640242": "sturgeon",
426
+ "n02641379": "gar, garfish, garpike, billfish, Lepisosteus osseus",
427
+ "n02643566": "lionfish",
428
+ "n02655020": "puffer, pufferfish, blowfish, globefish",
429
+ "n02666196": "abacus",
430
+ "n02667093": "abaya",
431
+ "n02669723": "academic gown, academic robe, judge's robe",
432
+ "n02672831": "accordion, piano accordion, squeeze box",
433
+ "n02676566": "acoustic guitar",
434
+ "n02687172": "aircraft carrier, carrier, flattop, attack aircraft carrier",
435
+ "n02690373": "airliner",
436
+ "n02692877": "airship, dirigible",
437
+ "n02699494": "altar",
438
+ "n02701002": "ambulance",
439
+ "n02704792": "amphibian, amphibious vehicle",
440
+ "n02708093": "analog clock",
441
+ "n02727426": "apiary, bee house",
442
+ "n02730930": "apron",
443
+ "n02747177": "ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin",
444
+ "n02749479": "assault rifle, assault gun",
445
+ "n02769748": "backpack, back pack, knapsack, packsack, rucksack, haversack",
446
+ "n02776631": "bakery, bakeshop, bakehouse",
447
+ "n02777292": "balance beam, beam",
448
+ "n02782093": "balloon",
449
+ "n02783161": "ballpoint, ballpoint pen, ballpen, Biro",
450
+ "n02786058": "Band Aid",
451
+ "n02787622": "banjo",
452
+ "n02788148": "bannister, banister, balustrade, balusters, handrail",
453
+ "n02790996": "barbell",
454
+ "n02791124": "barber chair",
455
+ "n02791270": "barbershop",
456
+ "n02793495": "barn",
457
+ "n02794156": "barometer",
458
+ "n02795169": "barrel, cask",
459
+ "n02797295": "barrow, garden cart, lawn cart, wheelbarrow",
460
+ "n02799071": "baseball",
461
+ "n02802426": "basketball",
462
+ "n02804414": "bassinet",
463
+ "n02804610": "bassoon",
464
+ "n02807133": "bathing cap, swimming cap",
465
+ "n02808304": "bath towel",
466
+ "n02808440": "bathtub, bathing tub, bath, tub",
467
+ "n02814533": "beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon",
468
+ "n02814860": "beacon, lighthouse, beacon light, pharos",
469
+ "n02815834": "beaker",
470
+ "n02817516": "bearskin, busby, shako",
471
+ "n02823428": "beer bottle",
472
+ "n02823750": "beer glass",
473
+ "n02825657": "bell cote, bell cot",
474
+ "n02834397": "bib",
475
+ "n02835271": "bicycle-built-for-two, tandem bicycle, tandem",
476
+ "n02837789": "bikini, two-piece",
477
+ "n02840245": "binder, ring-binder",
478
+ "n02841315": "binoculars, field glasses, opera glasses",
479
+ "n02843684": "birdhouse",
480
+ "n02859443": "boathouse",
481
+ "n02860847": "bobsled, bobsleigh, bob",
482
+ "n02865351": "bolo tie, bolo, bola tie, bola",
483
+ "n02869837": "bonnet, poke bonnet",
484
+ "n02870880": "bookcase",
485
+ "n02871525": "bookshop, bookstore, bookstall",
486
+ "n02877765": "bottlecap",
487
+ "n02879718": "bow",
488
+ "n02883205": "bow tie, bow-tie, bowtie",
489
+ "n02892201": "brass, memorial tablet, plaque",
490
+ "n02892767": "brassiere, bra, bandeau",
491
+ "n02894605": "breakwater, groin, groyne, mole, bulwark, seawall, jetty",
492
+ "n02895154": "breastplate, aegis, egis",
493
+ "n02906734": "broom",
494
+ "n02909870": "bucket, pail",
495
+ "n02910353": "buckle",
496
+ "n02916936": "bulletproof vest",
497
+ "n02917067": "bullet train, bullet",
498
+ "n02927161": "butcher shop, meat market",
499
+ "n02930766": "cab, hack, taxi, taxicab",
500
+ "n02939185": "caldron, cauldron",
501
+ "n02948072": "candle, taper, wax light",
502
+ "n02950826": "cannon",
503
+ "n02951358": "canoe",
504
+ "n02951585": "can opener, tin opener",
505
+ "n02963159": "cardigan",
506
+ "n02965783": "car mirror",
507
+ "n02966193": "carousel, carrousel, merry-go-round, roundabout, whirligig",
508
+ "n02966687": "carpenter's kit, tool kit",
509
+ "n02971356": "carton",
510
+ "n02974003": "car wheel",
511
+ "n02977058": "cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM",
512
+ "n02978881": "cassette",
513
+ "n02979186": "cassette player",
514
+ "n02980441": "castle",
515
+ "n02981792": "catamaran",
516
+ "n02988304": "CD player",
517
+ "n02992211": "cello, violoncello",
518
+ "n02992529": "cellular telephone, cellular phone, cellphone, cell, mobile phone",
519
+ "n02999410": "chain",
520
+ "n03000134": "chainlink fence",
521
+ "n03000247": "chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour",
522
+ "n03000684": "chain saw, chainsaw",
523
+ "n03014705": "chest",
524
+ "n03016953": "chiffonier, commode",
525
+ "n03017168": "chime, bell, gong",
526
+ "n03018349": "china cabinet, china closet",
527
+ "n03026506": "Christmas stocking",
528
+ "n03028079": "church, church building",
529
+ "n03032252": "cinema, movie theater, movie theatre, movie house, picture palace",
530
+ "n03041632": "cleaver, meat cleaver, chopper",
531
+ "n03042490": "cliff dwelling",
532
+ "n03045698": "cloak",
533
+ "n03047690": "clog, geta, patten, sabot",
534
+ "n03062245": "cocktail shaker",
535
+ "n03063599": "coffee mug",
536
+ "n03063689": "coffeepot",
537
+ "n03065424": "coil, spiral, volute, whorl, helix",
538
+ "n03075370": "combination lock",
539
+ "n03085013": "computer keyboard, keypad",
540
+ "n03089624": "confectionery, confectionary, candy store",
541
+ "n03095699": "container ship, containership, container vessel",
542
+ "n03100240": "convertible",
543
+ "n03109150": "corkscrew, bottle screw",
544
+ "n03110669": "cornet, horn, trumpet, trump",
545
+ "n03124043": "cowboy boot",
546
+ "n03124170": "cowboy hat, ten-gallon hat",
547
+ "n03125729": "cradle",
548
+ "n03126707": "crane2",
549
+ "n03127747": "crash helmet",
550
+ "n03127925": "crate",
551
+ "n03131574": "crib, cot",
552
+ "n03133878": "Crock Pot",
553
+ "n03134739": "croquet ball",
554
+ "n03141823": "crutch",
555
+ "n03146219": "cuirass",
556
+ "n03160309": "dam, dike, dyke",
557
+ "n03179701": "desk",
558
+ "n03180011": "desktop computer",
559
+ "n03187595": "dial telephone, dial phone",
560
+ "n03188531": "diaper, nappy, napkin",
561
+ "n03196217": "digital clock",
562
+ "n03197337": "digital watch",
563
+ "n03201208": "dining table, board",
564
+ "n03207743": "dishrag, dishcloth",
565
+ "n03207941": "dishwasher, dish washer, dishwashing machine",
566
+ "n03208938": "disk brake, disc brake",
567
+ "n03216828": "dock, dockage, docking facility",
568
+ "n03218198": "dogsled, dog sled, dog sleigh",
569
+ "n03220513": "dome",
570
+ "n03223299": "doormat, welcome mat",
571
+ "n03240683": "drilling platform, offshore rig",
572
+ "n03249569": "drum, membranophone, tympan",
573
+ "n03250847": "drumstick",
574
+ "n03255030": "dumbbell",
575
+ "n03259280": "Dutch oven",
576
+ "n03271574": "electric fan, blower",
577
+ "n03272010": "electric guitar",
578
+ "n03272562": "electric locomotive",
579
+ "n03290653": "entertainment center",
580
+ "n03291819": "envelope",
581
+ "n03297495": "espresso maker",
582
+ "n03314780": "face powder",
583
+ "n03325584": "feather boa, boa",
584
+ "n03337140": "file, file cabinet, filing cabinet",
585
+ "n03344393": "fireboat",
586
+ "n03345487": "fire engine, fire truck",
587
+ "n03347037": "fire screen, fireguard",
588
+ "n03355925": "flagpole, flagstaff",
589
+ "n03372029": "flute, transverse flute",
590
+ "n03376595": "folding chair",
591
+ "n03379051": "football helmet",
592
+ "n03384352": "forklift",
593
+ "n03388043": "fountain",
594
+ "n03388183": "fountain pen",
595
+ "n03388549": "four-poster",
596
+ "n03393912": "freight car",
597
+ "n03394916": "French horn, horn",
598
+ "n03400231": "frying pan, frypan, skillet",
599
+ "n03404251": "fur coat",
600
+ "n03417042": "garbage truck, dustcart",
601
+ "n03424325": "gasmask, respirator, gas helmet",
602
+ "n03425413": "gas pump, gasoline pump, petrol pump, island dispenser",
603
+ "n03443371": "goblet",
604
+ "n03444034": "go-kart",
605
+ "n03445777": "golf ball",
606
+ "n03445924": "golfcart, golf cart",
607
+ "n03447447": "gondola",
608
+ "n03447721": "gong, tam-tam",
609
+ "n03450230": "gown",
610
+ "n03452741": "grand piano, grand",
611
+ "n03457902": "greenhouse, nursery, glasshouse",
612
+ "n03459775": "grille, radiator grille",
613
+ "n03461385": "grocery store, grocery, food market, market",
614
+ "n03467068": "guillotine",
615
+ "n03476684": "hair slide",
616
+ "n03476991": "hair spray",
617
+ "n03478589": "half track",
618
+ "n03481172": "hammer",
619
+ "n03482405": "hamper",
620
+ "n03483316": "hand blower, blow dryer, blow drier, hair dryer, hair drier",
621
+ "n03485407": "hand-held computer, hand-held microcomputer",
622
+ "n03485794": "handkerchief, hankie, hanky, hankey",
623
+ "n03492542": "hard disc, hard disk, fixed disk",
624
+ "n03494278": "harmonica, mouth organ, harp, mouth harp",
625
+ "n03495258": "harp",
626
+ "n03496892": "harvester, reaper",
627
+ "n03498962": "hatchet",
628
+ "n03527444": "holster",
629
+ "n03529860": "home theater, home theatre",
630
+ "n03530642": "honeycomb",
631
+ "n03532672": "hook, claw",
632
+ "n03534580": "hoopskirt, crinoline",
633
+ "n03535780": "horizontal bar, high bar",
634
+ "n03538406": "horse cart, horse-cart",
635
+ "n03544143": "hourglass",
636
+ "n03584254": "iPod",
637
+ "n03584829": "iron, smoothing iron",
638
+ "n03590841": "jack-o'-lantern",
639
+ "n03594734": "jean, blue jean, denim",
640
+ "n03594945": "jeep, landrover",
641
+ "n03595614": "jersey, T-shirt, tee shirt",
642
+ "n03598930": "jigsaw puzzle",
643
+ "n03599486": "jinrikisha, ricksha, rickshaw",
644
+ "n03602883": "joystick",
645
+ "n03617480": "kimono",
646
+ "n03623198": "knee pad",
647
+ "n03627232": "knot",
648
+ "n03630383": "lab coat, laboratory coat",
649
+ "n03633091": "ladle",
650
+ "n03637318": "lampshade, lamp shade",
651
+ "n03642806": "laptop, laptop computer",
652
+ "n03649909": "lawn mower, mower",
653
+ "n03657121": "lens cap, lens cover",
654
+ "n03658185": "letter opener, paper knife, paperknife",
655
+ "n03661043": "library",
656
+ "n03662601": "lifeboat",
657
+ "n03666591": "lighter, light, igniter, ignitor",
658
+ "n03670208": "limousine, limo",
659
+ "n03673027": "liner, ocean liner",
660
+ "n03676483": "lipstick, lip rouge",
661
+ "n03680355": "Loafer",
662
+ "n03690938": "lotion",
663
+ "n03691459": "loudspeaker, speaker, speaker unit, loudspeaker system, speaker system",
664
+ "n03692522": "loupe, jeweler's loupe",
665
+ "n03697007": "lumbermill, sawmill",
666
+ "n03706229": "magnetic compass",
667
+ "n03709823": "mailbag, postbag",
668
+ "n03710193": "mailbox, letter box",
669
+ "n03710637": "maillot",
670
+ "n03710721": "maillot, tank suit",
671
+ "n03717622": "manhole cover",
672
+ "n03720891": "maraca",
673
+ "n03721384": "marimba, xylophone",
674
+ "n03724870": "mask",
675
+ "n03729826": "matchstick",
676
+ "n03733131": "maypole",
677
+ "n03733281": "maze, labyrinth",
678
+ "n03733805": "measuring cup",
679
+ "n03742115": "medicine chest, medicine cabinet",
680
+ "n03743016": "megalith, megalithic structure",
681
+ "n03759954": "microphone, mike",
682
+ "n03761084": "microwave, microwave oven",
683
+ "n03763968": "military uniform",
684
+ "n03764736": "milk can",
685
+ "n03769881": "minibus",
686
+ "n03770439": "miniskirt, mini",
687
+ "n03770679": "minivan",
688
+ "n03773504": "missile",
689
+ "n03775071": "mitten",
690
+ "n03775546": "mixing bowl",
691
+ "n03776460": "mobile home, manufactured home",
692
+ "n03777568": "Model T",
693
+ "n03777754": "modem",
694
+ "n03781244": "monastery",
695
+ "n03782006": "monitor",
696
+ "n03785016": "moped",
697
+ "n03786901": "mortar",
698
+ "n03787032": "mortarboard",
699
+ "n03788195": "mosque",
700
+ "n03788365": "mosquito net",
701
+ "n03791053": "motor scooter, scooter",
702
+ "n03792782": "mountain bike, all-terrain bike, off-roader",
703
+ "n03792972": "mountain tent",
704
+ "n03793489": "mouse, computer mouse",
705
+ "n03794056": "mousetrap",
706
+ "n03796401": "moving van",
707
+ "n03803284": "muzzle",
708
+ "n03804744": "nail",
709
+ "n03814639": "neck brace",
710
+ "n03814906": "necklace",
711
+ "n03825788": "nipple",
712
+ "n03832673": "notebook, notebook computer",
713
+ "n03837869": "obelisk",
714
+ "n03838899": "oboe, hautboy, hautbois",
715
+ "n03840681": "ocarina, sweet potato",
716
+ "n03841143": "odometer, hodometer, mileometer, milometer",
717
+ "n03843555": "oil filter",
718
+ "n03854065": "organ, pipe organ",
719
+ "n03857828": "oscilloscope, scope, cathode-ray oscilloscope, CRO",
720
+ "n03866082": "overskirt",
721
+ "n03868242": "oxcart",
722
+ "n03868863": "oxygen mask",
723
+ "n03871628": "packet",
724
+ "n03873416": "paddle, boat paddle",
725
+ "n03874293": "paddlewheel, paddle wheel",
726
+ "n03874599": "padlock",
727
+ "n03876231": "paintbrush",
728
+ "n03877472": "pajama, pyjama, pj's, jammies",
729
+ "n03877845": "palace",
730
+ "n03884397": "panpipe, pandean pipe, syrinx",
731
+ "n03887697": "paper towel",
732
+ "n03888257": "parachute, chute",
733
+ "n03888605": "parallel bars, bars",
734
+ "n03891251": "park bench",
735
+ "n03891332": "parking meter",
736
+ "n03895866": "passenger car, coach, carriage",
737
+ "n03899768": "patio, terrace",
738
+ "n03902125": "pay-phone, pay-station",
739
+ "n03903868": "pedestal, plinth, footstall",
740
+ "n03908618": "pencil box, pencil case",
741
+ "n03908714": "pencil sharpener",
742
+ "n03916031": "perfume, essence",
743
+ "n03920288": "Petri dish",
744
+ "n03924679": "photocopier",
745
+ "n03929660": "pick, plectrum, plectron",
746
+ "n03929855": "pickelhaube",
747
+ "n03930313": "picket fence, paling",
748
+ "n03930630": "pickup, pickup truck",
749
+ "n03933933": "pier",
750
+ "n03935335": "piggy bank, penny bank",
751
+ "n03937543": "pill bottle",
752
+ "n03938244": "pillow",
753
+ "n03942813": "ping-pong ball",
754
+ "n03944341": "pinwheel",
755
+ "n03947888": "pirate, pirate ship",
756
+ "n03950228": "pitcher, ewer",
757
+ "n03954731": "plane, carpenter's plane, woodworking plane",
758
+ "n03956157": "planetarium",
759
+ "n03958227": "plastic bag",
760
+ "n03961711": "plate rack",
761
+ "n03967562": "plow, plough",
762
+ "n03970156": "plunger, plumber's helper",
763
+ "n03976467": "Polaroid camera, Polaroid Land camera",
764
+ "n03976657": "pole",
765
+ "n03977966": "police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria",
766
+ "n03980874": "poncho",
767
+ "n03982430": "pool table, billiard table, snooker table",
768
+ "n03983396": "pop bottle, soda bottle",
769
+ "n03991062": "pot, flowerpot",
770
+ "n03992509": "potter's wheel",
771
+ "n03995372": "power drill",
772
+ "n03998194": "prayer rug, prayer mat",
773
+ "n04004767": "printer",
774
+ "n04005630": "prison, prison house",
775
+ "n04008634": "projectile, missile",
776
+ "n04009552": "projector",
777
+ "n04019541": "puck, hockey puck",
778
+ "n04023962": "punching bag, punch bag, punching ball, punchball",
779
+ "n04026417": "purse",
780
+ "n04033901": "quill, quill pen",
781
+ "n04033995": "quilt, comforter, comfort, puff",
782
+ "n04037443": "racer, race car, racing car",
783
+ "n04039381": "racket, racquet",
784
+ "n04040759": "radiator",
785
+ "n04041544": "radio, wireless",
786
+ "n04044716": "radio telescope, radio reflector",
787
+ "n04049303": "rain barrel",
788
+ "n04065272": "recreational vehicle, RV, R.V.",
789
+ "n04067472": "reel",
790
+ "n04069434": "reflex camera",
791
+ "n04070727": "refrigerator, icebox",
792
+ "n04074963": "remote control, remote",
793
+ "n04081281": "restaurant, eating house, eating place, eatery",
794
+ "n04086273": "revolver, six-gun, six-shooter",
795
+ "n04090263": "rifle",
796
+ "n04099969": "rocking chair, rocker",
797
+ "n04111531": "rotisserie",
798
+ "n04116512": "rubber eraser, rubber, pencil eraser",
799
+ "n04118538": "rugby ball",
800
+ "n04118776": "rule, ruler",
801
+ "n04120489": "running shoe",
802
+ "n04125021": "safe",
803
+ "n04127249": "safety pin",
804
+ "n04131690": "saltshaker, salt shaker",
805
+ "n04133789": "sandal",
806
+ "n04136333": "sarong",
807
+ "n04141076": "sax, saxophone",
808
+ "n04141327": "scabbard",
809
+ "n04141975": "scale, weighing machine",
810
+ "n04146614": "school bus",
811
+ "n04147183": "schooner",
812
+ "n04149813": "scoreboard",
813
+ "n04152593": "screen, CRT screen",
814
+ "n04153751": "screw",
815
+ "n04154565": "screwdriver",
816
+ "n04162706": "seat belt, seatbelt",
817
+ "n04179913": "sewing machine",
818
+ "n04192698": "shield, buckler",
819
+ "n04200800": "shoe shop, shoe-shop, shoe store",
820
+ "n04201297": "shoji",
821
+ "n04204238": "shopping basket",
822
+ "n04204347": "shopping cart",
823
+ "n04208210": "shovel",
824
+ "n04209133": "shower cap",
825
+ "n04209239": "shower curtain",
826
+ "n04228054": "ski",
827
+ "n04229816": "ski mask",
828
+ "n04235860": "sleeping bag",
829
+ "n04238763": "slide rule, slipstick",
830
+ "n04239074": "sliding door",
831
+ "n04243546": "slot, one-armed bandit",
832
+ "n04251144": "snorkel",
833
+ "n04252077": "snowmobile",
834
+ "n04252225": "snowplow, snowplough",
835
+ "n04254120": "soap dispenser",
836
+ "n04254680": "soccer ball",
837
+ "n04254777": "sock",
838
+ "n04258138": "solar dish, solar collector, solar furnace",
839
+ "n04259630": "sombrero",
840
+ "n04263257": "soup bowl",
841
+ "n04264628": "space bar",
842
+ "n04265275": "space heater",
843
+ "n04266014": "space shuttle",
844
+ "n04270147": "spatula",
845
+ "n04273569": "speedboat",
846
+ "n04275548": "spider web, spider's web",
847
+ "n04277352": "spindle",
848
+ "n04285008": "sports car, sport car",
849
+ "n04286575": "spotlight, spot",
850
+ "n04296562": "stage",
851
+ "n04310018": "steam locomotive",
852
+ "n04311004": "steel arch bridge",
853
+ "n04311174": "steel drum",
854
+ "n04317175": "stethoscope",
855
+ "n04325704": "stole",
856
+ "n04326547": "stone wall",
857
+ "n04328186": "stopwatch, stop watch",
858
+ "n04330267": "stove",
859
+ "n04332243": "strainer",
860
+ "n04335435": "streetcar, tram, tramcar, trolley, trolley car",
861
+ "n04336792": "stretcher",
862
+ "n04344873": "studio couch, day bed",
863
+ "n04346328": "stupa, tope",
864
+ "n04347754": "submarine, pigboat, sub, U-boat",
865
+ "n04350905": "suit, suit of clothes",
866
+ "n04355338": "sundial",
867
+ "n04355933": "sunglass",
868
+ "n04356056": "sunglasses, dark glasses, shades",
869
+ "n04357314": "sunscreen, sunblock, sun blocker",
870
+ "n04366367": "suspension bridge",
871
+ "n04367480": "swab, swob, mop",
872
+ "n04370456": "sweatshirt",
873
+ "n04371430": "swimming trunks, bathing trunks",
874
+ "n04371774": "swing",
875
+ "n04372370": "switch, electric switch, electrical switch",
876
+ "n04376876": "syringe",
877
+ "n04380533": "table lamp",
878
+ "n04389033": "tank, army tank, armored combat vehicle, armoured combat vehicle",
879
+ "n04392985": "tape player",
880
+ "n04398044": "teapot",
881
+ "n04399382": "teddy, teddy bear",
882
+ "n04404412": "television, television system",
883
+ "n04409515": "tennis ball",
884
+ "n04417672": "thatch, thatched roof",
885
+ "n04418357": "theater curtain, theatre curtain",
886
+ "n04423845": "thimble",
887
+ "n04428191": "thresher, thrasher, threshing machine",
888
+ "n04429376": "throne",
889
+ "n04435653": "tile roof",
890
+ "n04442312": "toaster",
891
+ "n04443257": "tobacco shop, tobacconist shop, tobacconist",
892
+ "n04447861": "toilet seat",
893
+ "n04456115": "torch",
894
+ "n04458633": "totem pole",
895
+ "n04461696": "tow truck, tow car, wrecker",
896
+ "n04462240": "toyshop",
897
+ "n04465501": "tractor",
898
+ "n04467665": "trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi",
899
+ "n04476259": "tray",
900
+ "n04479046": "trench coat",
901
+ "n04482393": "tricycle, trike, velocipede",
902
+ "n04483307": "trimaran",
903
+ "n04485082": "tripod",
904
+ "n04486054": "triumphal arch",
905
+ "n04487081": "trolleybus, trolley coach, trackless trolley",
906
+ "n04487394": "trombone",
907
+ "n04493381": "tub, vat",
908
+ "n04501370": "turnstile",
909
+ "n04505470": "typewriter keyboard",
910
+ "n04507155": "umbrella",
911
+ "n04509417": "unicycle, monocycle",
912
+ "n04515003": "upright, upright piano",
913
+ "n04517823": "vacuum, vacuum cleaner",
914
+ "n04522168": "vase",
915
+ "n04523525": "vault",
916
+ "n04525038": "velvet",
917
+ "n04525305": "vending machine",
918
+ "n04532106": "vestment",
919
+ "n04532670": "viaduct",
920
+ "n04536866": "violin, fiddle",
921
+ "n04540053": "volleyball",
922
+ "n04542943": "waffle iron",
923
+ "n04548280": "wall clock",
924
+ "n04548362": "wallet, billfold, notecase, pocketbook",
925
+ "n04550184": "wardrobe, closet, press",
926
+ "n04552348": "warplane, military plane",
927
+ "n04553703": "washbasin, handbasin, washbowl, lavabo, wash-hand basin",
928
+ "n04554684": "washer, automatic washer, washing machine",
929
+ "n04557648": "water bottle",
930
+ "n04560804": "water jug",
931
+ "n04562935": "water tower",
932
+ "n04579145": "whiskey jug",
933
+ "n04579432": "whistle",
934
+ "n04584207": "wig",
935
+ "n04589890": "window screen",
936
+ "n04590129": "window shade",
937
+ "n04591157": "Windsor tie",
938
+ "n04591713": "wine bottle",
939
+ "n04592741": "wing",
940
+ "n04596742": "wok",
941
+ "n04597913": "wooden spoon",
942
+ "n04599235": "wool, woolen, woollen",
943
+ "n04604644": "worm fence, snake fence, snake-rail fence, Virginia fence",
944
+ "n04606251": "wreck",
945
+ "n04612504": "yawl",
946
+ "n04613696": "yurt",
947
+ "n06359193": "web site, website, internet site, site",
948
+ "n06596364": "comic book",
949
+ "n06785654": "crossword puzzle, crossword",
950
+ "n06794110": "street sign",
951
+ "n06874185": "traffic light, traffic signal, stoplight",
952
+ "n07248320": "book jacket, dust cover, dust jacket, dust wrapper",
953
+ "n07565083": "menu",
954
+ "n07579787": "plate",
955
+ "n07583066": "guacamole",
956
+ "n07584110": "consomme",
957
+ "n07590611": "hot pot, hotpot",
958
+ "n07613480": "trifle",
959
+ "n07614500": "ice cream, icecream",
960
+ "n07615774": "ice lolly, lolly, lollipop, popsicle",
961
+ "n07684084": "French loaf",
962
+ "n07693725": "bagel, beigel",
963
+ "n07695742": "pretzel",
964
+ "n07697313": "cheeseburger",
965
+ "n07697537": "hotdog, hot dog, red hot",
966
+ "n07711569": "mashed potato",
967
+ "n07714571": "head cabbage",
968
+ "n07714990": "broccoli",
969
+ "n07715103": "cauliflower",
970
+ "n07716358": "zucchini, courgette",
971
+ "n07716906": "spaghetti squash",
972
+ "n07717410": "acorn squash",
973
+ "n07717556": "butternut squash",
974
+ "n07718472": "cucumber, cuke",
975
+ "n07718747": "artichoke, globe artichoke",
976
+ "n07720875": "bell pepper",
977
+ "n07730033": "cardoon",
978
+ "n07734744": "mushroom",
979
+ "n07742313": "Granny Smith",
980
+ "n07745940": "strawberry",
981
+ "n07747607": "orange",
982
+ "n07749582": "lemon",
983
+ "n07753113": "fig",
984
+ "n07753275": "pineapple, ananas",
985
+ "n07753592": "banana",
986
+ "n07754684": "jackfruit, jak, jack",
987
+ "n07760859": "custard apple",
988
+ "n07768694": "pomegranate",
989
+ "n07802026": "hay",
990
+ "n07831146": "carbonara",
991
+ "n07836838": "chocolate sauce, chocolate syrup",
992
+ "n07860988": "dough",
993
+ "n07871810": "meat loaf, meatloaf",
994
+ "n07873807": "pizza, pizza pie",
995
+ "n07875152": "potpie",
996
+ "n07880968": "burrito",
997
+ "n07892512": "red wine",
998
+ "n07920052": "espresso",
999
+ "n07930864": "cup",
1000
+ "n07932039": "eggnog",
1001
+ "n09193705": "alp",
1002
+ "n09229709": "bubble",
1003
+ "n09246464": "cliff, drop, drop-off",
1004
+ "n09256479": "coral reef",
1005
+ "n09288635": "geyser",
1006
+ "n09332890": "lakeside, lakeshore",
1007
+ "n09399592": "promontory, headland, head, foreland",
1008
+ "n09421951": "sandbar, sand bar",
1009
+ "n09428293": "seashore, coast, seacoast, sea-coast",
1010
+ "n09468604": "valley, vale",
1011
+ "n09472597": "volcano",
1012
+ "n09835506": "ballplayer, baseball player",
1013
+ "n10148035": "groom, bridegroom",
1014
+ "n10565667": "scuba diver",
1015
+ "n11879895": "rapeseed",
1016
+ "n11939491": "daisy",
1017
+ "n12057211": "yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum",
1018
+ "n12144580": "corn",
1019
+ "n12267677": "acorn",
1020
+ "n12620546": "hip, rose hip, rosehip",
1021
+ "n12768682": "buckeye, horse chestnut, conker",
1022
+ "n12985857": "coral fungus",
1023
+ "n12998815": "agaric",
1024
+ "n13037406": "gyromitra",
1025
+ "n13040303": "stinkhorn, carrion fungus",
1026
+ "n13044778": "earthstar",
1027
+ "n13052670": "hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa",
1028
+ "n13054560": "bolete",
1029
+ "n13133613": "ear, spike, capitulum",
1030
+ "n15075141": "toilet tissue, toilet paper, bathroom tissue",
1031
+ }
1032
+ )
1033
+
1034
+ _CITATION = """\
1035
+ @misc{nauen2025foraug,
1036
+ title={ForAug: Recombining Foregrounds and Backgrounds to Improve Vision Transformer Training with Bias Mitigation},
1037
+ author={Tobias Christian Nauen and Brian Moser and Federico Raue and Stanislav Frolov and Andreas Dengel},
1038
+ year={2025},
1039
+ eprint={2503.09399},
1040
+ archivePrefix={arXiv},
1041
+ primaryClass={cs.CV},
1042
+ }
1043
+ """
1044
+
1045
+ _DESCRIPTION = """\
1046
+ ForNet is a dataset of foreground objects and backgrounds extracted (and infilled) from ImageNet. \
1047
+ It's the output of the segmentation phase of the ForAug data augmentation. \
1048
+ ForNet recombines these foregrounds and backgrounds on the fly to create new samples for training vision transformers.
1049
+ """
1050
+
1051
+ _GIT = "https://github.com/tobna/ForAug"
1052
+ _HOMEPAGE = "Coming Soon"
1053
+ _DATASET_URL = "https://huggingface.co/datasets/TNauen/ForNet/resolve/main/"
1054
+ _CONST_URLS = (
1055
+ [_DATASET_URL + "settings.txt"]
1056
+ + [_DATASET_URL + f"fg_bg_ratios_{part}.json" for part in ["train", "val"]]
1057
+ + [_DATASET_URL + f"hf_{part}_indices.json" for part in ["train", "val"]]
1058
+ )
1059
+ _PATCH_URLS = [_DATASET_URL + f"train_{i}.zip" for i in range(20)] + [_DATASET_URL + "val.zip"]
1060
+
1061
+
1062
+ class RecombineDataset(Dataset):
1063
+ """Wrapper for ForNet dataset that recombines foregrounds and backgrounds on the fly."""
1064
+
1065
+ def __init__(
1066
+ self,
1067
+ *args,
1068
+ background_combination,
1069
+ fg_scale_jitter,
1070
+ pruning_ratio,
1071
+ fg_size_mode,
1072
+ fg_bates_n,
1073
+ mask_smoothing_sigma,
1074
+ rel_jut_out,
1075
+ orig_img_prob,
1076
+ **kwargs,
1077
+ ):
1078
+ """Create the ForNet recombination dataset.
1079
+
1080
+ Args:
1081
+ background_combination (str): Which backgrounds to combine with foregrounds. Options: "orig", "same", "all".
1082
+ fg_scale_jitter (tuple[float]): How much should the size of the foreground be changed (random ratio). Example: (0.1, 0.8).
1083
+ pruning_ratio (float): For pruning backgrounds, with (foreground size/background size) >= <pruning_ratio>. Backgrounds from images that contain very large foreground objects are mostly computer generated and therefore relatively unnatural. Full dataset: 1.1 .
1084
+ fg_size_mode (str): How to determine the size of the foreground, based on the foreground sizes of the foreground and background images. Options: "range", "min", "max", "mean".
1085
+ fg_bates_n (int): Bates parameter for the distribution of the object position in the foreground. Uniform Distribution: 1. The higher the value, the more likely the object is in the center. For fg_bates_n = 0, the object is always in the center.
1086
+ mask_smoothing_sigma (float): Sigma for the Gaussian blur of the mask edge.
1087
+ rel_jut_out (float): How much is the foreground allowed to stand/jut out of the background (and then cut off).
1088
+ orig_img_prob (float | str): Probability to use the original image, instead of the fg-bg recombinations. Options: 0.0-1.0, "linear", "revlinear", "cos".
1089
+ """
1090
+ super().__init__(*args, **kwargs)
1091
+ assert (isinstance(orig_img_prob, float) and 0.0 <= orig_img_prob <= 1.0) or orig_img_prob in [
1092
+ "linear",
1093
+ "revlinear",
1094
+ "cos",
1095
+ ], f"Invalid orig_img_prob {orig_img_prob}"
1096
+ assert background_combination in [
1097
+ "all",
1098
+ "same",
1099
+ "orig",
1100
+ ], f"Invalid background_combination {background_combination}"
1101
+ assert fg_size_mode in ["range", "min", "max", "mean"], f"Invalid fg_size_mode {fg_size_mode}"
1102
+ self.background_combination = background_combination
1103
+ self.fg_scale_jitter = fg_scale_jitter
1104
+ self.pruning_ratio = pruning_ratio
1105
+ self.fg_size_mode = fg_size_mode
1106
+ self.fg_bates_n = fg_bates_n
1107
+ self.mask_smoothing_sigma = mask_smoothing_sigma
1108
+ self.rel_jut_out = rel_jut_out
1109
+ self.orig_img_prob = orig_img_prob
1110
+ self.epochs = 0
1111
+ self._epoch = 0
1112
+ self.cls_to_idx = {}
1113
+
1114
+ bg_rat_indices = super()._getitem(0)["bg_rat_idx_file"]
1115
+ self.train = "train" in bg_rat_indices.split("/")[-1]
1116
+
1117
+ with open(bg_rat_indices, "r") as f:
1118
+ bg_rat_indices = json.load(f)
1119
+ for in_cls in bg_rat_indices:
1120
+ if in_cls not in self.cls_to_idx:
1121
+ self.cls_to_idx[in_cls] = []
1122
+ for idx, rat in bg_rat_indices[in_cls]:
1123
+ if rat < self.pruning_ratio:
1124
+ self.cls_to_idx[in_cls].append(idx)
1125
+ if self.background_combination == "all":
1126
+ self.cls_to_idx["all"] = list(itertools.chain(*self.cls_to_idx.values()))
1127
+
1128
+ @property
1129
+ def total_epochs(self):
1130
+ return self.epochs
1131
+
1132
+ @total_epochs.setter
1133
+ def total_epochs(self, value):
1134
+ self.epochs = value
1135
+
1136
+ @property
1137
+ def epoch(self):
1138
+ return self._epoch
1139
+
1140
+ @epoch.setter
1141
+ def epoch(self, value):
1142
+ assert 0 <= value < self.epochs, f"Epoch {value} is out of bounds for range [0, {self.epochs})"
1143
+ self._epoch = value
1144
+
1145
+ def _getitem(self, key):
1146
+ fg_item = super()._getitem(key)
1147
+ out_dict = {"label": fg_item["label"]}
1148
+ in_cls = fg_item["path"].split("/")[0]
1149
+
1150
+ if (
1151
+ (self.orig_img_prob == "linear" and np.random.rand() < self._epoch / self.epochs)
1152
+ or (self.orig_img_prob == "revlinear" and np.random.rand() < (self._epoch - self.epochs) / self.epochs)
1153
+ or (self.orig_img_prob == "cos" and np.random.rand() > np.cos(np.pi * self._epoch / (2 * self.epochs)))
1154
+ or (
1155
+ isinstance(self.orig_img_prob, float)
1156
+ and self.orig_img_prob > 0.0
1157
+ and np.random.rand() < self.orig_img_prob
1158
+ )
1159
+ ):
1160
+ # return original image
1161
+ out_dict["image"] = fg_item["in"]
1162
+ return out_dict
1163
+
1164
+ if self.background_combination == "orig":
1165
+ bg_item = fg_item
1166
+ elif self.background_combination == "same":
1167
+ rand_idx = np.random.randint(len(self.cls_to_idx[in_cls]))
1168
+ rand_idx = self.cls_to_idx[in_cls][rand_idx]
1169
+ bg_item = super()._getitem(rand_idx)
1170
+ else:
1171
+ # all
1172
+ rand_idx = np.random.randint(len(self.cls_to_idx["all"]))
1173
+ rand_idx = self.cls_to_idx["all"][rand_idx]
1174
+ bg_item = super()._getitem(rand_idx)
1175
+
1176
+ fg_img = fg_item["fg"].convert("RGBA")
1177
+ bg_img = bg_item["bg"].convert("RGB")
1178
+ bg_size = bg_img.size
1179
+ bg_area = bg_size[0] * bg_size[1]
1180
+ orig_fg_ratio = fg_item["fg/bg_area"]
1181
+ bg_fg_ratio = bg_item["fg/bg_area"]
1182
+
1183
+ if self.fg_size_mode == "max":
1184
+ goal_fg_ratio_lower = goal_fg_ratio_upper = max(orig_fg_ratio, bg_fg_ratio)
1185
+ elif self.fg_size_mode == "min":
1186
+ goal_fg_ratio_lower = goal_fg_ratio_upper = min(orig_fg_ratio, bg_fg_ratio)
1187
+ elif self.fg_size_mode == "mean":
1188
+ goal_fg_ratio_lower = goal_fg_ratio_upper = (orig_fg_ratio + bg_fg_ratio) / 2
1189
+ else:
1190
+ # range
1191
+ goal_fg_ratio_lower = min(orig_fg_ratio, bg_fg_ratio)
1192
+ goal_fg_ratio_upper = max(orig_fg_ratio, bg_fg_ratio)
1193
+
1194
+ fg_size_factor = T.ToTensor()(fg_img.split()[-1]).mean().item()
1195
+
1196
+ fg_scale = (
1197
+ np.random.uniform(
1198
+ goal_fg_ratio_lower * (1 - self.fg_scale_jitter), goal_fg_ratio_upper * (1 + self.fg_scale_jitter)
1199
+ )
1200
+ / fg_size_factor
1201
+ )
1202
+
1203
+ goal_shape_y = round(np.sqrt(bg_area * fg_scale * fg_img.size[1] / fg_img.size[0]))
1204
+ goal_shape_x = round(np.sqrt(bg_area * fg_scale * fg_img.size[0] / fg_img.size[1]))
1205
+
1206
+ fg_img = fg_img.resize((goal_shape_x, goal_shape_y))
1207
+
1208
+ if fg_img.size[0] > bg_size[0] or fg_img.size[1] > bg_size[1]:
1209
+ # random crop to fit
1210
+ goal_w, goal_h = (min(fg_img.size[0], bg_size[0]), min(fg_img.size[1], bg_size[1]))
1211
+ fg_img = T.RandomCrop((goal_h, goal_w))(fg_img) if self.train else T.CenterCrop((goal_h, goal_w))(fg_img)
1212
+
1213
+ # paste fg on bg
1214
+ z1, z2 = (
1215
+ (
1216
+ np.random.uniform(0, 1, abs(self.fg_bates_n)).mean(), # bates distribution n=1 => uniform
1217
+ np.random.uniform(0, 1, abs(self.fg_bates_n)).mean(),
1218
+ )
1219
+ if self.fg_bates_n != 0
1220
+ else (0.5, 0.5)
1221
+ )
1222
+ if self.fg_bates_n < 0:
1223
+ z1 = z1 + 0.5 - floor(z1 + 0.5)
1224
+ z2 = z2 + 0.5 - floor(z2 + 0.5)
1225
+
1226
+ x_min = -self.rel_jut_out * fg_img.size[0]
1227
+ x_max = bg_size[0] - fg_img.size[0] * (1 - self.rel_jut_out)
1228
+ y_min = -self.rel_jut_out * fg_img.size[1]
1229
+ y_max = bg_size[1] - fg_img.size[1] * (1 - self.rel_jut_out)
1230
+
1231
+ if x_min > x_max:
1232
+ x_min = x_max = (x_min + x_max) / 2
1233
+ if y_min > y_max:
1234
+ y_min = y_max = (y_min + y_max) / 2
1235
+
1236
+ offs_x = round(z1 * (x_max - x_min) + x_min)
1237
+ offs_y = round(z2 * (y_max - y_min) + y_min)
1238
+
1239
+ paste_mask = fg_img.split()[-1]
1240
+ if self.mask_smoothing_sigma > 0.0:
1241
+ sigma = (np.random.rand() * 0.9 + 0.1) * self.mask_smoothing_sigma
1242
+ paste_mask = paste_mask.filter(ImageFilter.GaussianBlur(radius=sigma))
1243
+ paste_mask = paste_mask.point(lambda p: 2 * p - 255 if p > 128 else 0)
1244
+
1245
+ bg_img.paste(fg_img.convert("RGB"), (offs_x, offs_y), paste_mask)
1246
+ bg_img = bg_img.convert("RGB")
1247
+
1248
+ out_dict["image"] = bg_img
1249
+
1250
+ return out_dict
1251
+
1252
+ def __str__(self):
1253
+ return f"{self.__class__}(\n\t features: ['image', 'label'],\n\t num_rows: {len(self)},\n\tbackground_combination: {self.background_combination},\n\t pruning_ratio: {self.pruning_ratio},\n\t fg_size_mode: {self.fg_size_mode},\n\t mask_smoothing_sigma: {self.mask_smoothing_sigma},\n\t orig_img_prob: {self.orig_img_prob}\n)"
1254
+
1255
+
1256
+ _CONFIG_HASH_IGNORE_KWARGS = [
1257
+ "background_combination",
1258
+ "fg_scale_jitter",
1259
+ "pruning_ratio",
1260
+ "fg_size_mode",
1261
+ "fg_bates_n",
1262
+ "mask_smoothing_sigma",
1263
+ "rel_jut_out",
1264
+ "orig_img_prob",
1265
+ ]
1266
+
1267
+
1268
+ class ForNetConfig(datasets.BuilderConfig):
1269
+ """BuilderConfig for ForNet."""
1270
+
1271
+ def __init__(
1272
+ self,
1273
+ background_combination,
1274
+ fg_scale_jitter,
1275
+ pruning_ratio,
1276
+ fg_size_mode,
1277
+ fg_bates_n,
1278
+ mask_smoothing_sigma,
1279
+ rel_jut_out,
1280
+ orig_img_prob,
1281
+ **kwargs,
1282
+ ):
1283
+ """BuilderConfig for ForNet.
1284
+
1285
+ Args:
1286
+ **kwargs: keyword arguments forwarded to super.
1287
+ """
1288
+ super(ForNetConfig, self).__init__(**kwargs)
1289
+ self.background_combination = background_combination
1290
+ self.fg_scale_jitter = fg_scale_jitter
1291
+ self.pruning_ratio = pruning_ratio
1292
+ self.fg_size_mode = fg_size_mode
1293
+ self.fg_bates_n = fg_bates_n
1294
+ self.mask_smoothing_sigma = mask_smoothing_sigma
1295
+ self.rel_jut_out = rel_jut_out
1296
+ self.orig_img_prob = orig_img_prob
1297
+
1298
+ def __str__(self):
1299
+ return f"ForNetConfig(name={self.name}, version={self.version}, data_dir={self.data_dir}, data_files={self.data_files}, description={self.description}, background_combination={self.background_combination}, fg_scale_jitter={self.fg_scale_jitter}, pruning_ratio={self.pruning_ratio}, fg_size_mode={self.fg_size_mode}, fg_bates_n={self.fg_bates_n}, mask_smoothing_sigma={self.mask_smoothing_sigma}, rel_jut_out={self.rel_jut_out}, orig_img_prob={self.orig_img_prob})"
1300
+
1301
+ def create_config_id(
1302
+ self,
1303
+ config_kwargs: dict,
1304
+ custom_features=None,
1305
+ ) -> str:
1306
+ """The config id is used to build the cache directory.
1307
+
1308
+ By default it is equal to the config name.
1309
+ However the name of a config is not sufficient to have a unique identifier for the dataset being generated
1310
+ since it doesn't take into account:
1311
+ - the config kwargs that can be used to overwrite attributes
1312
+ - the custom features used to write the dataset
1313
+ - the data_files for json/text/csv/pandas datasets.
1314
+
1315
+ Therefore the config id is just the config name with an optional suffix based on these.
1316
+ """
1317
+ # Possibly add a suffix to the name to handle custom features/data_files/config_kwargs
1318
+ suffix: Optional[str] = None
1319
+ config_kwargs_to_add_to_suffix = config_kwargs.copy()
1320
+ # name and version are already used to build the cache directory
1321
+ config_kwargs_to_add_to_suffix.pop("name", None)
1322
+ config_kwargs_to_add_to_suffix.pop("version", None)
1323
+
1324
+ # remove only recombination-relevant values
1325
+ for k in _CONFIG_HASH_IGNORE_KWARGS:
1326
+ config_kwargs_to_add_to_suffix.pop(k, None)
1327
+
1328
+ # data dir handling (when specified it points to the manually downloaded data):
1329
+ # it was previously ignored before the introduction of config id because we didn't want
1330
+ # to change the config name. Now it's fine to take it into account for the config id.
1331
+ # config_kwargs_to_add_to_suffix.pop("data_dir", None)
1332
+ if "data_dir" in config_kwargs_to_add_to_suffix:
1333
+ if config_kwargs_to_add_to_suffix["data_dir"] is None:
1334
+ config_kwargs_to_add_to_suffix.pop("data_dir", None)
1335
+ else:
1336
+ # canonicalize the data dir to avoid two paths to the same location having different
1337
+ # hashes
1338
+ data_dir = config_kwargs_to_add_to_suffix["data_dir"]
1339
+ data_dir = os.path.normpath(data_dir)
1340
+ config_kwargs_to_add_to_suffix["data_dir"] = data_dir
1341
+ if config_kwargs_to_add_to_suffix:
1342
+ # we don't care about the order of the kwargs
1343
+ config_kwargs_to_add_to_suffix = {
1344
+ k: config_kwargs_to_add_to_suffix[k] for k in sorted(config_kwargs_to_add_to_suffix)
1345
+ }
1346
+ if all(isinstance(v, (str, bool, int, float)) for v in config_kwargs_to_add_to_suffix.values()):
1347
+ suffix = ",".join(
1348
+ str(k) + "=" + urllib.parse.quote_plus(str(v)) for k, v in config_kwargs_to_add_to_suffix.items()
1349
+ )
1350
+ if len(suffix) > 32: # hash if too long
1351
+ suffix = Hasher.hash(config_kwargs_to_add_to_suffix)
1352
+ else:
1353
+ suffix = Hasher.hash(config_kwargs_to_add_to_suffix)
1354
+
1355
+ if custom_features is not None:
1356
+ m = Hasher()
1357
+ if suffix:
1358
+ m.update(suffix)
1359
+ m.update(custom_features)
1360
+ suffix = m.hexdigest()
1361
+
1362
+ if suffix:
1363
+ config_id = self.name + "-" + suffix
1364
+ if len(config_id) > config.MAX_DATASET_CONFIG_ID_READABLE_LENGTH:
1365
+ config_id = self.name + "-" + Hasher.hash(suffix)
1366
+ return config_id
1367
+ return self.name
1368
+
1369
+
1370
+ class ForNet(datasets.GeneratorBasedBuilder):
1371
+ """ForNet dataset."""
1372
+
1373
+ def __init__(self, *args, **kwargs):
1374
+ """Initialize the ForNet Builder."""
1375
+ super().__init__(*args, **kwargs)
1376
+ self.cls_to_idx_locs = {}
1377
+
1378
+ BUILDER_CONFIGS = [
1379
+ ForNetConfig(
1380
+ name="fornet",
1381
+ version=datasets.Version("1.0.0", ""),
1382
+ description="ForNet dataset",
1383
+ background_combination="all",
1384
+ fg_scale_jitter=0.3,
1385
+ pruning_ratio=0.8,
1386
+ fg_size_mode="range",
1387
+ fg_bates_n=1,
1388
+ mask_smoothing_sigma=4.0,
1389
+ rel_jut_out=0.0,
1390
+ orig_img_prob=0.0,
1391
+ )
1392
+ ]
1393
+
1394
+ DEFAULT_WRITER_BATCH_SIZE = 1000
1395
+
1396
+ def _info(self):
1397
+ return datasets.DatasetInfo(
1398
+ description=_DESCRIPTION,
1399
+ features=datasets.Features(
1400
+ {
1401
+ "path": datasets.Value("string"),
1402
+ "bg": datasets.features.Image(),
1403
+ "fg": datasets.features.Image(),
1404
+ "in": datasets.features.Image(),
1405
+ "label": datasets.features.ClassLabel(names=list(IMAGENET2012_CLASSES.values())),
1406
+ "fg/bg_area": datasets.Value("float"),
1407
+ "bg_rat_idx_file": datasets.Value("string"),
1408
+ }
1409
+ ),
1410
+ supervised_keys=("image", "label"),
1411
+ homepage=_HOMEPAGE,
1412
+ citation=_CITATION,
1413
+ )
1414
+
1415
+ def _split_generators(self, dl_manager: datasets.DownloadManager):
1416
+ urls_to_download = _CONST_URLS + _PATCH_URLS
1417
+ dl_paths = dl_manager.download(urls_to_download)
1418
+
1419
+ train_re = re.compile(r".*/train_(\d+)\.zip$")
1420
+ val_re = re.compile(r".*/val\.zip$")
1421
+
1422
+ train_patches = [f for f in dl_paths if train_re.match(f)]
1423
+ val_patches = [f for f in dl_paths if val_re.match(f)]
1424
+
1425
+ hf_train_indices = [f for f in dl_paths if f.endswith("hf_train_indices.json")][0]
1426
+ hf_val_indices = [f for f in dl_paths if f.endswith("hf_val_indices.json")][0]
1427
+
1428
+ cls_to_idx_locs = {
1429
+ "train": hf_train_indices.replace("hf_train_indices", "train_cls_to_idx"),
1430
+ "val": hf_val_indices.replace("hf_val_indices", "val_cls_to_idx"),
1431
+ }
1432
+
1433
+ fg_bg_ratios = [
1434
+ [f for f in dl_paths if f.endswith(f"fg_bg_ratios_{part}.json")][0] for part in ["train", "val"]
1435
+ ]
1436
+
1437
+ return [
1438
+ datasets.SplitGenerator(
1439
+ name=datasets.Split.TRAIN,
1440
+ gen_kwargs={
1441
+ "patch_files": train_patches,
1442
+ "split": "train",
1443
+ "hf_indices": hf_train_indices,
1444
+ "cls_to_idx_loc": cls_to_idx_locs["train"],
1445
+ "fg_bg_ratios": fg_bg_ratios[0],
1446
+ },
1447
+ ),
1448
+ datasets.SplitGenerator(
1449
+ name=datasets.Split.VALIDATION,
1450
+ gen_kwargs={
1451
+ "patch_files": val_patches,
1452
+ "split": "val",
1453
+ "hf_indices": hf_val_indices,
1454
+ "cls_to_idx_loc": cls_to_idx_locs["val"],
1455
+ "fg_bg_ratios": fg_bg_ratios[1],
1456
+ },
1457
+ ),
1458
+ ]
1459
+
1460
+ def _generate_examples(
1461
+ self, patch_files, split, hf_indices, cls_to_idx_loc, fg_bg_ratios
1462
+ ): # TODO: Parallelize this with multiple tar extractor processes and also multiple recombiner processes. Iterate through imagenet in main thread only, I guess...
1463
+ logger.info(f"Generating examples from {len(patch_files)} patch files")
1464
+ logger.info("Opening files")
1465
+ class_to_zipfile = {}
1466
+ for f in patch_files:
1467
+ with zipfile.ZipFile(f, "r") as zf:
1468
+ for name in zf.namelist():
1469
+ if name.endswith(".pkl") or name.endswith(".pkl.gz"):
1470
+ class_to_zipfile[name.split("/")[-2]] = f
1471
+ file_ending = "pkl" if name.endswith(".pkl") else "pkl.gz"
1472
+ name_start = "/".join(name.split("/")[:-2])
1473
+ if len(name_start) > 0:
1474
+ name_start += "/"
1475
+ logger.info(f"Loading extra information: {hf_indices}, {fg_bg_ratios}")
1476
+ with open(hf_indices, "r") as f:
1477
+ path_to_in_idx = json.load(f)
1478
+ idx_to_path = {v: k for k, v in path_to_in_idx.items()}
1479
+ # print("idx_to_path", list(idx_to_path.items())[:5])
1480
+ with open(fg_bg_ratios, "r") as f:
1481
+ fg_bg_ratios = json.load(f)
1482
+ fg_bg_ratios = {"/".join(k.split("/")[-2:]).split(".")[0]: v for k, v in fg_bg_ratios.items()}
1483
+ # print("fg_bg_ratios", list(fg_bg_ratios.items())[:5])
1484
+
1485
+ logger.info("Starting extraction with ImageNet")
1486
+ foraug_idx = 0
1487
+
1488
+ manager = multiprocessing.Manager()
1489
+ num_workers = multiprocessing.cpu_count()
1490
+ if os.environ.get("MAX_WORKERS", None):
1491
+ num_workers = int(os.environ["MAX_WORKERS"])
1492
+ in_queue = manager.Queue(maxsize=4 * num_workers)
1493
+ ret_queue = manager.Queue(maxsize=4 * num_workers)
1494
+ comm_dict = manager.dict()
1495
+ comm_dict["running"] = True
1496
+ comm_dict["n_errors"] = 0
1497
+
1498
+ in_proc = multiprocessing.Process(target=_in_iterator, args=(in_queue, split))
1499
+ in_proc.start()
1500
+ zip_procs = [
1501
+ multiprocessing.Process(
1502
+ target=_zip_loader,
1503
+ args=(
1504
+ in_queue,
1505
+ ret_queue,
1506
+ comm_dict,
1507
+ patch_files,
1508
+ class_to_zipfile,
1509
+ name_start,
1510
+ file_ending,
1511
+ idx_to_path,
1512
+ fg_bg_ratios,
1513
+ ),
1514
+ )
1515
+ for _ in range(num_workers)
1516
+ ]
1517
+ for proc in zip_procs:
1518
+ proc.start()
1519
+
1520
+ last_errors = 0
1521
+ cls_to_idx = {}
1522
+ while comm_dict["running"]:
1523
+ if not ret_queue.empty():
1524
+ data = ret_queue.get()
1525
+ in_cls = data["path"].split("/")[0]
1526
+ if in_cls not in cls_to_idx:
1527
+ cls_to_idx[in_cls] = []
1528
+ cls_to_idx[in_cls].append((foraug_idx, data["fg/bg_area"]))
1529
+ if foraug_idx == 0:
1530
+ data["bg_rat_idx_file"] = cls_to_idx_loc
1531
+ yield foraug_idx, data
1532
+ foraug_idx += 1
1533
+
1534
+ if comm_dict["n_errors"] > last_errors:
1535
+ last_errors = comm_dict["n_errors"]
1536
+ tqdm.write(
1537
+ f"@step {foraug_idx}: errors {last_errors}; error rate {last_errors / foraug_idx:.2%} (expected {6_610 / 1_274_227:.2%})"
1538
+ )
1539
+
1540
+ if ret_queue.empty() and in_queue.empty() and not in_proc.is_alive():
1541
+ comm_dict["running"] = False
1542
+ tqdm.write("Finished imagenet iteration; waiting for zip loaders to finish")
1543
+
1544
+ in_proc.join()
1545
+ for proc in zip_procs:
1546
+ proc.join()
1547
+
1548
+ # tqdm.write("Finished all processes")
1549
+ while not ret_queue.empty():
1550
+ data = ret_queue.get()
1551
+ in_cls = data["path"].split("/")[0]
1552
+ if in_cls not in cls_to_idx:
1553
+ cls_to_idx[in_cls] = []
1554
+ cls_to_idx[in_cls].append(foraug_idx)
1555
+ yield foraug_idx, data
1556
+ foraug_idx += 1
1557
+ # tqdm.write("Done")
1558
+ with open(cls_to_idx_loc, "w") as f:
1559
+ json.dump(cls_to_idx, f)
1560
+
1561
+ def _as_streaming_dataset_single(self, *args, **kwargs):
1562
+ raise NotImplementedError("ForNet does not support streaming datasets")
1563
+
1564
+ def _as_dataset(self, split=datasets.Split.TRAIN, in_memory=False):
1565
+ """Constructs a `Dataset`.
1566
+
1567
+ This is the internal implementation to overwrite called when user calls
1568
+ `as_dataset`. It should read the pre-processed datasets files and generate
1569
+ the `Dataset` object.
1570
+
1571
+ Args:
1572
+ split (`datasets.Split`):
1573
+ which subset of the data to read.
1574
+ in_memory (`bool`, defaults to `False`):
1575
+ Whether to copy the data in-memory.
1576
+
1577
+ Returns:
1578
+ `Dataset`
1579
+ """
1580
+ cache_dir = self._fs._strip_protocol(self._output_dir)
1581
+ dataset_name = self.dataset_name
1582
+ if self._check_legacy_cache():
1583
+ dataset_name = self.name
1584
+ dataset_kwargs = ArrowReader(cache_dir, self.info).read(
1585
+ name=dataset_name,
1586
+ instructions=split,
1587
+ split_infos=self.info.splits.values(),
1588
+ in_memory=in_memory,
1589
+ )
1590
+
1591
+ fingerprint = self._get_dataset_fingerprint(split)
1592
+ # print("config", self.config)
1593
+ # print("rel data dir", self._relative_data_dir())
1594
+ # print("split", str(split))
1595
+ # print("fingerprint", fingerprint)
1596
+
1597
+ splitname = str(split)
1598
+ if splitname == "validation":
1599
+ splitname = "val"
1600
+
1601
+ return RecombineDataset(
1602
+ fingerprint=fingerprint,
1603
+ background_combination=self.config.background_combination,
1604
+ fg_scale_jitter=self.config.fg_scale_jitter,
1605
+ pruning_ratio=self.config.pruning_ratio,
1606
+ fg_size_mode=self.config.fg_size_mode,
1607
+ fg_bates_n=self.config.fg_bates_n,
1608
+ mask_smoothing_sigma=self.config.mask_smoothing_sigma,
1609
+ rel_jut_out=self.config.rel_jut_out,
1610
+ orig_img_prob=self.config.orig_img_prob,
1611
+ **dataset_kwargs,
1612
+ )
1613
+
1614
+ def _create_builder_config(self, config_name=None, custom_features=None, **config_kwargs):
1615
+ config_hash_kwargs = {k: v for k, v in config_kwargs.items() if k not in _CONFIG_HASH_IGNORE_KWARGS}
1616
+ builder_config, config_id = super()._create_builder_config(config_name, custom_features, **config_hash_kwargs)
1617
+ for k in _CONFIG_HASH_IGNORE_KWARGS:
1618
+ if k in config_kwargs:
1619
+ setattr(builder_config, k, config_kwargs[k])
1620
+ return builder_config, config_id
1621
+
1622
+
1623
+ def _in_iterator(in_queue, split):
1624
+ if split == "val":
1625
+ split = "validation"
1626
+ imagenet = datasets.load_dataset("ILSVRC/imagenet-1k", split=split)
1627
+ for idx, ex in enumerate(imagenet):
1628
+ in_queue.put((idx, ex["image"]))
1629
+
1630
+
1631
+ def _zip_loader(
1632
+ in_queue, ret_queue, comm_dict, patch_files, class_to_zipfile, name_start, file_ending, idx_to_path, fg_bg_ratios
1633
+ ):
1634
+ while comm_dict["running"]:
1635
+ if not in_queue.empty():
1636
+ try:
1637
+ in_idx, in_img = in_queue.get(block=False)
1638
+ except queue.Empty:
1639
+ continue
1640
+ patch_name = idx_to_path[in_idx]
1641
+ in_class, in_file_name = patch_name.split("/")
1642
+
1643
+ try:
1644
+ with zipfile.ZipFile(class_to_zipfile[in_class], "r") as zf, (
1645
+ zf.open(f"{name_start}{patch_name}.{file_ending}", "r")
1646
+ if file_ending == "pkl"
1647
+ else gzip.GzipFile(fileobj=zf.open(f"{name_start}{patch_name}.{file_ending}", "r"), mode="r")
1648
+ ) as pklf:
1649
+ patch_data = pickle.load(pklf)
1650
+ except KeyError:
1651
+ comm_dict["n_errors"] += 1
1652
+ continue
1653
+
1654
+ in_img = in_img.convert("RGB")
1655
+
1656
+ if "bg_diff" in patch_data:
1657
+ if in_img.size != (patch_data["bg_diff"].shape[1], patch_data["bg_diff"].shape[0]):
1658
+ in_img = in_img.resize((patch_data["bg_diff"].shape[1], patch_data["bg_diff"].shape[0]))
1659
+ else:
1660
+ max_size = max(in_img.size)
1661
+ if max_size > 512:
1662
+ goal_size = (round(in_img.size[0] * 512 / max_size), round(in_img.size[1] * 512 / max_size))
1663
+ in_img = in_img.resize(goal_size)
1664
+
1665
+ in_img = np.array(in_img)
1666
+
1667
+ if "bg_diff" in patch_data:
1668
+ bg_diff = patch_data["bg_diff"]
1669
+ bg_img = in_img.astype(np.int64) + bg_diff
1670
+ else:
1671
+ bg_img = None
1672
+
1673
+ if "fg_mask" in patch_data:
1674
+ x_offs, y_offs = patch_data["fg_off"]
1675
+ fg_mask = patch_data["fg_mask"]
1676
+
1677
+ fg_crop = in_img[y_offs : y_offs + fg_mask.shape[0], x_offs : x_offs + fg_mask.shape[1]]
1678
+ fg_img = np.concatenate([fg_crop, fg_mask * 255], axis=-1).clip(0, 255).astype(np.uint8)
1679
+ else:
1680
+ fg_img = None
1681
+ ret_queue.put(
1682
+ {
1683
+ "path": patch_name,
1684
+ "bg": bg_img,
1685
+ "fg": fg_img,
1686
+ "label": IMAGENET2012_CLASSES[in_class],
1687
+ "in": in_img,
1688
+ "fg/bg_area": fg_bg_ratios[patch_name],
1689
+ }
1690
+ )