repo
stringlengths 2
99
| file
stringlengths 13
225
| code
stringlengths 0
18.3M
| file_length
int64 0
18.3M
| avg_line_length
float64 0
1.36M
| max_line_length
int64 0
4.26M
| extension_type
stringclasses 1
value |
---|---|---|---|---|---|---|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/builder.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import platform
import random
from distutils.version import LooseVersion
from functools import partial
import numpy as np
import torch
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from torch.utils.data import DataLoader
from .samplers import DistributedSampler
if platform.system() != 'Windows':
# https://github.com/pytorch/pytorch/issues/973
import resource
rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)
hard_limit = rlimit[1]
soft_limit = min(4096, hard_limit)
resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))
DATASETS = Registry('dataset')
PIPELINES = Registry('pipeline')
def build_dataset(cfg, default_args=None):
from .dataset_wrappers import (ConcatDataset, RepeatDataset,
ClassBalancedDataset)
if isinstance(cfg, (list, tuple)):
dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])
elif cfg['type'] == 'RepeatDataset':
dataset = RepeatDataset(
build_dataset(cfg['dataset'], default_args), cfg['times'])
elif cfg['type'] == 'ClassBalancedDataset':
dataset = ClassBalancedDataset(
build_dataset(cfg['dataset'], default_args), cfg['oversample_thr'])
else:
dataset = build_from_cfg(cfg, DATASETS, default_args)
return dataset
def build_dataloader(dataset,
samples_per_gpu,
workers_per_gpu,
num_gpus=1,
dist=True,
shuffle=True,
round_up=True,
seed=None,
pin_memory=True,
persistent_workers=True,
**kwargs):
"""Build PyTorch DataLoader.
In distributed training, each GPU/process has a dataloader.
In non-distributed training, there is only one dataloader for all GPUs.
Args:
dataset (Dataset): A PyTorch dataset.
samples_per_gpu (int): Number of training samples on each GPU, i.e.,
batch size of each GPU.
workers_per_gpu (int): How many subprocesses to use for data loading
for each GPU.
num_gpus (int): Number of GPUs. Only used in non-distributed training.
dist (bool): Distributed training/test or not. Default: True.
shuffle (bool): Whether to shuffle the data at every epoch.
Default: True.
round_up (bool): Whether to round up the length of dataset by adding
extra samples to make it evenly divisible. Default: True.
pin_memory (bool): Whether to use pin_memory in DataLoader.
Default: True
persistent_workers (bool): If True, the data loader will not shutdown
the worker processes after a dataset has been consumed once.
This allows to maintain the workers Dataset instances alive.
The argument also has effect in PyTorch>=1.7.0.
Default: True
kwargs: any keyword argument to be used to initialize DataLoader
Returns:
DataLoader: A PyTorch dataloader.
"""
rank, world_size = get_dist_info()
if dist:
sampler = DistributedSampler(
dataset, world_size, rank, shuffle=shuffle, round_up=round_up)
shuffle = False
batch_size = samples_per_gpu
num_workers = workers_per_gpu
else:
sampler = None
batch_size = num_gpus * samples_per_gpu
num_workers = num_gpus * workers_per_gpu
init_fn = partial(
worker_init_fn, num_workers=num_workers, rank=rank,
seed=seed) if seed is not None else None
if LooseVersion(torch.__version__) >= LooseVersion('1.7.0'):
kwargs['persistent_workers'] = persistent_workers
data_loader = DataLoader(
dataset,
batch_size=batch_size,
sampler=sampler,
num_workers=num_workers,
collate_fn=partial(collate, samples_per_gpu=samples_per_gpu),
pin_memory=pin_memory,
shuffle=shuffle,
worker_init_fn=init_fn,
**kwargs)
return data_loader
def worker_init_fn(worker_id, num_workers, rank, seed):
# The seed of each worker equals to
# num_worker * rank + worker_id + user_seed
worker_seed = num_workers * rank + worker_id + seed
np.random.seed(worker_seed)
random.seed(worker_seed)
| 4,471 | 34.776 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/cifar.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path
import pickle
import numpy as np
import torch.distributed as dist
from mmcv.runner import get_dist_info
from mmcls.datasets.disentangle_data.multi_task import MultiTask
from mmcls.datasets.pipelines.compose import Compose
from .base_dataset import BaseDataset
from .builder import DATASETS
from .utils import check_integrity, download_and_extract_archive
@DATASETS.register_module()
class CIFAR10(BaseDataset):
"""`CIFAR10 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset.
This implementation is modified from
https://github.com/pytorch/vision/blob/master/torchvision/datasets/cifar.py
""" # noqa: E501
base_folder = 'cifar-10-batches-py'
url = 'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz'
filename = 'cifar-10-python.tar.gz'
tgz_md5 = 'c58f30108f718f92721af3b95e74349a'
train_list = [
['data_batch_1', 'c99cafc152244af753f735de768cd75f'],
['data_batch_2', 'd4bba439e000b95fd0a9bffe97cbabec'],
['data_batch_3', '54ebc095f3ab1f0389bbae665268c751'],
['data_batch_4', '634d18415352ddfa80567beed471001a'],
['data_batch_5', '482c414d41f54cd18b22e5b47cb7c3cb'],
]
test_list = [
['test_batch', '40351d587109b95175f43aff81a1287e'],
]
meta = {
'filename': 'batches.meta',
'key': 'label_names',
'md5': '5ff9c542aee3614f3951f8cda6e48888',
}
def load_annotations(self):
rank, world_size = get_dist_info()
if rank == 0 and not self._check_integrity():
download_and_extract_archive(
self.url,
self.data_prefix,
filename=self.filename,
md5=self.tgz_md5)
if world_size > 1:
dist.barrier()
assert self._check_integrity(), \
'Shared storage seems unavailable. ' \
f'Please download the dataset manually through {self.url}.'
if not self.test_mode:
downloaded_list = self.train_list
else:
downloaded_list = self.test_list
self.imgs = []
self.gt_labels = []
# load the picked numpy arrays
for file_name, checksum in downloaded_list:
file_path = os.path.join(self.data_prefix, self.base_folder,
file_name)
with open(file_path, 'rb') as f:
entry = pickle.load(f, encoding='latin1')
self.imgs.append(entry['data'])
if 'labels' in entry:
self.gt_labels.extend(entry['labels'])
else:
self.gt_labels.extend(entry['fine_labels'])
self.imgs = np.vstack(self.imgs).reshape(-1, 3, 32, 32)
self.imgs = self.imgs.transpose((0, 2, 3, 1)) # convert to HWC
self._load_meta()
data_infos = []
for img, gt_label in zip(self.imgs, self.gt_labels):
gt_label = np.array(gt_label, dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
def _load_meta(self):
path = os.path.join(self.data_prefix, self.base_folder,
self.meta['filename'])
if not check_integrity(path, self.meta['md5']):
raise RuntimeError(
'Dataset metadata file not found or corrupted.' +
' You can use download=True to download it')
with open(path, 'rb') as infile:
data = pickle.load(infile, encoding='latin1')
self.CLASSES = data[self.meta['key']]
def _check_integrity(self):
root = self.data_prefix
for fentry in (self.train_list + self.test_list):
filename, md5 = fentry[0], fentry[1]
fpath = os.path.join(root, self.base_folder, filename)
if not check_integrity(fpath, md5):
return False
return True
@DATASETS.register_module()
class CIFAR100(CIFAR10):
"""`CIFAR100 <https://www.cs.toronto.edu/~kriz/cifar.html>`_ Dataset."""
base_folder = 'cifar-100-python'
url = 'https://www.cs.toronto.edu/~kriz/cifar-100-python.tar.gz'
filename = 'cifar-100-python.tar.gz'
tgz_md5 = 'eb9058c3a382ffc7106e4002c42a8d85'
train_list = [
['train', '16019d7e3df5f24257cddd939b257f8d'],
]
test_list = [
['test', 'f0ef6b0ae62326f3e7ffdfab6717acfc'],
]
meta = {
'filename': 'meta',
'key': 'fine_label_names',
'md5': '7973b15100ade9c7d40fb424638fde48',
}
@DATASETS.register_module()
class CIFAR10_2Task(CIFAR10):
gt2newgt = {0: 0, 1: 1, 2: 4, 3: 5, 4: 6, 5: 7, 6: 8, 7: 9, 8: 2, 9: 3}
def load_annotations(self):
rank, world_size = get_dist_info()
if rank == 0 and not self._check_integrity():
download_and_extract_archive(
self.url,
self.data_prefix,
filename=self.filename,
md5=self.tgz_md5)
if world_size > 1:
dist.barrier()
assert self._check_integrity(), \
'Shared storage seems unavailable. ' \
f'Please download the dataset manually through {self.url}.'
if not self.test_mode:
downloaded_list = self.train_list
else:
downloaded_list = self.test_list
self.imgs = []
self.gt_labels = []
# load the picked numpy arrays
for file_name, checksum in downloaded_list:
file_path = os.path.join(self.data_prefix, self.base_folder,
file_name)
with open(file_path, 'rb') as f:
entry = pickle.load(f, encoding='latin1')
self.imgs.append(entry['data'])
if 'labels' in entry:
self.gt_labels.extend(entry['labels'])
else:
self.gt_labels.extend(entry['fine_labels'])
self.imgs = np.vstack(self.imgs).reshape(-1, 3, 32, 32)
self.imgs = self.imgs.transpose((0, 2, 3, 1)) # convert to HWC
self._load_meta()
data_infos = []
for img, gt_label in zip(self.imgs, self.gt_labels):
gt_label = np.array(self.gt2newgt[gt_label], dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
@DATASETS.register_module()
class CIFAR10_Select(CIFAR10):
def __init__(self,
data_prefix,
pipeline,
select_class=(0, 1, 2, 3, 4, 5, 6, 7, 8, 9),
classes=None,
ann_file=None,
test_mode=False):
assert isinstance(select_class, list) or isinstance(
select_class, tuple)
self.select_class = select_class
self.select2gt = {
self.select_class[i]: i for i in range(len(self.select_class))}
super(CIFAR10_Select, self).__init__(data_prefix,
pipeline,
classes=classes,
ann_file=ann_file,
test_mode=test_mode)
def load_annotations(self):
rank, world_size = get_dist_info()
if rank == 0 and not self._check_integrity():
download_and_extract_archive(
self.url,
self.data_prefix,
filename=self.filename,
md5=self.tgz_md5)
if world_size > 1:
dist.barrier()
assert self._check_integrity(), \
'Shared storage seems unavailable. ' \
f'Please download the dataset manually through {self.url}.'
if not self.test_mode:
downloaded_list = self.train_list
else:
downloaded_list = self.test_list
self.imgs = []
self.gt_labels = []
# load the picked numpy arrays
for file_name, checksum in downloaded_list:
file_path = os.path.join(self.data_prefix, self.base_folder,
file_name)
with open(file_path, 'rb') as f:
entry = pickle.load(f, encoding='latin1')
self.imgs.append(entry['data'])
if 'labels' in entry:
self.gt_labels.extend(entry['labels'])
else:
self.gt_labels.extend(entry['fine_labels'])
self.imgs = np.vstack(self.imgs).reshape(-1, 3, 32, 32)
self.imgs = self.imgs.transpose((0, 2, 3, 1)) # convert to HWC
self._load_meta()
data_infos = []
for img, gt_label in zip(self.imgs, self.gt_labels):
if gt_label in self.select_class:
gt_label = np.array(self.select2gt[gt_label], dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
@DATASETS.register_module()
class CIFAR10_MultiTask(CIFAR10, MultiTask):
num_tasks = 10
def load_annotations(self):
rank, world_size = get_dist_info()
if rank == 0 and not self._check_integrity():
download_and_extract_archive(
self.url,
self.data_prefix,
filename=self.filename,
md5=self.tgz_md5)
if world_size > 1:
dist.barrier()
assert self._check_integrity(), \
'Shared storage seems unavailable. ' \
f'Please download the dataset manually through {self.url}.'
if not self.test_mode:
downloaded_list = self.train_list
else:
downloaded_list = self.test_list
self.imgs = []
self.gt_labels = []
# load the picked numpy arrays
for file_name, checksum in downloaded_list:
file_path = os.path.join(self.data_prefix, self.base_folder,
file_name)
with open(file_path, 'rb') as f:
entry = pickle.load(f, encoding='latin1')
self.imgs.append(entry['data'])
if 'labels' in entry:
self.gt_labels.extend(entry['labels'])
else:
self.gt_labels.extend(entry['fine_labels'])
self.gt_labels = np.eye(10)[self.gt_labels]
self.imgs = np.vstack(self.imgs).reshape(-1, 3, 32, 32)
self.imgs = self.imgs.transpose((0, 2, 3, 1)) # convert to HWC
self._load_meta()
data_infos = []
for img, gt_label in zip(self.imgs, self.gt_labels):
gt_label = np.array(gt_label, dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
| 10,938 | 33.507886 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/imagenet.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import os
import numpy as np
from .base_dataset import BaseDataset
from mmcls.datasets.disentangle_data.multi_task import MultiTask
from .builder import DATASETS
def has_file_allowed_extension(filename, extensions):
"""Checks if a file is an allowed extension.
Args:
filename (string): path to a file
Returns:
bool: True if the filename ends with a known image extension
"""
filename_lower = filename.lower()
return any(filename_lower.endswith(ext) for ext in extensions)
def find_folders(root):
"""Find classes by folders under a root.
Args:
root (string): root directory of folders
Returns:
folder_to_idx (dict): the map from folder name to class idx
"""
folders = [
d for d in os.listdir(root) if os.path.isdir(os.path.join(root, d))
]
folders.sort()
folder_to_idx = {folders[i]: i for i in range(len(folders))}
return folder_to_idx
def get_samples(root, folder_to_idx, extensions):
"""Make dataset by walking all images under a root.
Args:
root (string): root directory of folders
folder_to_idx (dict): the map from class name to class idx
extensions (tuple): allowed extensions
Returns:
samples (list): a list of tuple where each element is (image, label)
"""
samples = []
root = os.path.expanduser(root)
for folder_name in sorted(list(folder_to_idx.keys())):
_dir = os.path.join(root, folder_name)
for _, _, fns in sorted(os.walk(_dir)):
for fn in sorted(fns):
if has_file_allowed_extension(fn, extensions):
path = os.path.join(folder_name, fn)
item = (path, folder_to_idx[folder_name])
samples.append(item)
return samples
@DATASETS.register_module()
class ImageNet(BaseDataset):
"""`ImageNet <http://www.image-net.org>`_ Dataset.
This implementation is modified from
https://github.com/pytorch/vision/blob/master/torchvision/datasets/imagenet.py
""" # noqa: E501
IMG_EXTENSIONS = ('.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm', '.tif')
CLASSES = [
'tench, Tinca tinca',
'goldfish, Carassius auratus',
'great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias', # noqa: E501
'tiger shark, Galeocerdo cuvieri',
'hammerhead, hammerhead shark',
'electric ray, crampfish, numbfish, torpedo',
'stingray',
'cock',
'hen',
'ostrich, Struthio camelus',
'brambling, Fringilla montifringilla',
'goldfinch, Carduelis carduelis',
'house finch, linnet, Carpodacus mexicanus',
'junco, snowbird',
'indigo bunting, indigo finch, indigo bird, Passerina cyanea',
'robin, American robin, Turdus migratorius',
'bulbul',
'jay',
'magpie',
'chickadee',
'water ouzel, dipper',
'kite',
'bald eagle, American eagle, Haliaeetus leucocephalus',
'vulture',
'great grey owl, great gray owl, Strix nebulosa',
'European fire salamander, Salamandra salamandra',
'common newt, Triturus vulgaris',
'eft',
'spotted salamander, Ambystoma maculatum',
'axolotl, mud puppy, Ambystoma mexicanum',
'bullfrog, Rana catesbeiana',
'tree frog, tree-frog',
'tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui',
'loggerhead, loggerhead turtle, Caretta caretta',
'leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea', # noqa: E501
'mud turtle',
'terrapin',
'box turtle, box tortoise',
'banded gecko',
'common iguana, iguana, Iguana iguana',
'American chameleon, anole, Anolis carolinensis',
'whiptail, whiptail lizard',
'agama',
'frilled lizard, Chlamydosaurus kingi',
'alligator lizard',
'Gila monster, Heloderma suspectum',
'green lizard, Lacerta viridis',
'African chameleon, Chamaeleo chamaeleon',
'Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis', # noqa: E501
'African crocodile, Nile crocodile, Crocodylus niloticus',
'American alligator, Alligator mississipiensis',
'triceratops',
'thunder snake, worm snake, Carphophis amoenus',
'ringneck snake, ring-necked snake, ring snake',
'hognose snake, puff adder, sand viper',
'green snake, grass snake',
'king snake, kingsnake',
'garter snake, grass snake',
'water snake',
'vine snake',
'night snake, Hypsiglena torquata',
'boa constrictor, Constrictor constrictor',
'rock python, rock snake, Python sebae',
'Indian cobra, Naja naja',
'green mamba',
'sea snake',
'horned viper, cerastes, sand viper, horned asp, Cerastes cornutus',
'diamondback, diamondback rattlesnake, Crotalus adamanteus',
'sidewinder, horned rattlesnake, Crotalus cerastes',
'trilobite',
'harvestman, daddy longlegs, Phalangium opilio',
'scorpion',
'black and gold garden spider, Argiope aurantia',
'barn spider, Araneus cavaticus',
'garden spider, Aranea diademata',
'black widow, Latrodectus mactans',
'tarantula',
'wolf spider, hunting spider',
'tick',
'centipede',
'black grouse',
'ptarmigan',
'ruffed grouse, partridge, Bonasa umbellus',
'prairie chicken, prairie grouse, prairie fowl',
'peacock',
'quail',
'partridge',
'African grey, African gray, Psittacus erithacus',
'macaw',
'sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita',
'lorikeet',
'coucal',
'bee eater',
'hornbill',
'hummingbird',
'jacamar',
'toucan',
'drake',
'red-breasted merganser, Mergus serrator',
'goose',
'black swan, Cygnus atratus',
'tusker',
'echidna, spiny anteater, anteater',
'platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus', # noqa: E501
'wallaby, brush kangaroo',
'koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus', # noqa: E501
'wombat',
'jellyfish',
'sea anemone, anemone',
'brain coral',
'flatworm, platyhelminth',
'nematode, nematode worm, roundworm',
'conch',
'snail',
'slug',
'sea slug, nudibranch',
'chiton, coat-of-mail shell, sea cradle, polyplacophore',
'chambered nautilus, pearly nautilus, nautilus',
'Dungeness crab, Cancer magister',
'rock crab, Cancer irroratus',
'fiddler crab',
'king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica', # noqa: E501
'American lobster, Northern lobster, Maine lobster, Homarus americanus', # noqa: E501
'spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish', # noqa: E501
'crayfish, crawfish, crawdad, crawdaddy',
'hermit crab',
'isopod',
'white stork, Ciconia ciconia',
'black stork, Ciconia nigra',
'spoonbill',
'flamingo',
'little blue heron, Egretta caerulea',
'American egret, great white heron, Egretta albus',
'bittern',
'crane',
'limpkin, Aramus pictus',
'European gallinule, Porphyrio porphyrio',
'American coot, marsh hen, mud hen, water hen, Fulica americana',
'bustard',
'ruddy turnstone, Arenaria interpres',
'red-backed sandpiper, dunlin, Erolia alpina',
'redshank, Tringa totanus',
'dowitcher',
'oystercatcher, oyster catcher',
'pelican',
'king penguin, Aptenodytes patagonica',
'albatross, mollymawk',
'grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus', # noqa: E501
'killer whale, killer, orca, grampus, sea wolf, Orcinus orca',
'dugong, Dugong dugon',
'sea lion',
'Chihuahua',
'Japanese spaniel',
'Maltese dog, Maltese terrier, Maltese',
'Pekinese, Pekingese, Peke',
'Shih-Tzu',
'Blenheim spaniel',
'papillon',
'toy terrier',
'Rhodesian ridgeback',
'Afghan hound, Afghan',
'basset, basset hound',
'beagle',
'bloodhound, sleuthhound',
'bluetick',
'black-and-tan coonhound',
'Walker hound, Walker foxhound',
'English foxhound',
'redbone',
'borzoi, Russian wolfhound',
'Irish wolfhound',
'Italian greyhound',
'whippet',
'Ibizan hound, Ibizan Podenco',
'Norwegian elkhound, elkhound',
'otterhound, otter hound',
'Saluki, gazelle hound',
'Scottish deerhound, deerhound',
'Weimaraner',
'Staffordshire bullterrier, Staffordshire bull terrier',
'American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier', # noqa: E501
'Bedlington terrier',
'Border terrier',
'Kerry blue terrier',
'Irish terrier',
'Norfolk terrier',
'Norwich terrier',
'Yorkshire terrier',
'wire-haired fox terrier',
'Lakeland terrier',
'Sealyham terrier, Sealyham',
'Airedale, Airedale terrier',
'cairn, cairn terrier',
'Australian terrier',
'Dandie Dinmont, Dandie Dinmont terrier',
'Boston bull, Boston terrier',
'miniature schnauzer',
'giant schnauzer',
'standard schnauzer',
'Scotch terrier, Scottish terrier, Scottie',
'Tibetan terrier, chrysanthemum dog',
'silky terrier, Sydney silky',
'soft-coated wheaten terrier',
'West Highland white terrier',
'Lhasa, Lhasa apso',
'flat-coated retriever',
'curly-coated retriever',
'golden retriever',
'Labrador retriever',
'Chesapeake Bay retriever',
'German short-haired pointer',
'vizsla, Hungarian pointer',
'English setter',
'Irish setter, red setter',
'Gordon setter',
'Brittany spaniel',
'clumber, clumber spaniel',
'English springer, English springer spaniel',
'Welsh springer spaniel',
'cocker spaniel, English cocker spaniel, cocker',
'Sussex spaniel',
'Irish water spaniel',
'kuvasz',
'schipperke',
'groenendael',
'malinois',
'briard',
'kelpie',
'komondor',
'Old English sheepdog, bobtail',
'Shetland sheepdog, Shetland sheep dog, Shetland',
'collie',
'Border collie',
'Bouvier des Flandres, Bouviers des Flandres',
'Rottweiler',
'German shepherd, German shepherd dog, German police dog, alsatian',
'Doberman, Doberman pinscher',
'miniature pinscher',
'Greater Swiss Mountain dog',
'Bernese mountain dog',
'Appenzeller',
'EntleBucher',
'boxer',
'bull mastiff',
'Tibetan mastiff',
'French bulldog',
'Great Dane',
'Saint Bernard, St Bernard',
'Eskimo dog, husky',
'malamute, malemute, Alaskan malamute',
'Siberian husky',
'dalmatian, coach dog, carriage dog',
'affenpinscher, monkey pinscher, monkey dog',
'basenji',
'pug, pug-dog',
'Leonberg',
'Newfoundland, Newfoundland dog',
'Great Pyrenees',
'Samoyed, Samoyede',
'Pomeranian',
'chow, chow chow',
'keeshond',
'Brabancon griffon',
'Pembroke, Pembroke Welsh corgi',
'Cardigan, Cardigan Welsh corgi',
'toy poodle',
'miniature poodle',
'standard poodle',
'Mexican hairless',
'timber wolf, grey wolf, gray wolf, Canis lupus',
'white wolf, Arctic wolf, Canis lupus tundrarum',
'red wolf, maned wolf, Canis rufus, Canis niger',
'coyote, prairie wolf, brush wolf, Canis latrans',
'dingo, warrigal, warragal, Canis dingo',
'dhole, Cuon alpinus',
'African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus',
'hyena, hyaena',
'red fox, Vulpes vulpes',
'kit fox, Vulpes macrotis',
'Arctic fox, white fox, Alopex lagopus',
'grey fox, gray fox, Urocyon cinereoargenteus',
'tabby, tabby cat',
'tiger cat',
'Persian cat',
'Siamese cat, Siamese',
'Egyptian cat',
'cougar, puma, catamount, mountain lion, painter, panther, Felis concolor', # noqa: E501
'lynx, catamount',
'leopard, Panthera pardus',
'snow leopard, ounce, Panthera uncia',
'jaguar, panther, Panthera onca, Felis onca',
'lion, king of beasts, Panthera leo',
'tiger, Panthera tigris',
'cheetah, chetah, Acinonyx jubatus',
'brown bear, bruin, Ursus arctos',
'American black bear, black bear, Ursus americanus, Euarctos americanus', # noqa: E501
'ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus',
'sloth bear, Melursus ursinus, Ursus ursinus',
'mongoose',
'meerkat, mierkat',
'tiger beetle',
'ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle',
'ground beetle, carabid beetle',
'long-horned beetle, longicorn, longicorn beetle',
'leaf beetle, chrysomelid',
'dung beetle',
'rhinoceros beetle',
'weevil',
'fly',
'bee',
'ant, emmet, pismire',
'grasshopper, hopper',
'cricket',
'walking stick, walkingstick, stick insect',
'cockroach, roach',
'mantis, mantid',
'cicada, cicala',
'leafhopper',
'lacewing, lacewing fly',
"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk", # noqa: E501
'damselfly',
'admiral',
'ringlet, ringlet butterfly',
'monarch, monarch butterfly, milkweed butterfly, Danaus plexippus',
'cabbage butterfly',
'sulphur butterfly, sulfur butterfly',
'lycaenid, lycaenid butterfly',
'starfish, sea star',
'sea urchin',
'sea cucumber, holothurian',
'wood rabbit, cottontail, cottontail rabbit',
'hare',
'Angora, Angora rabbit',
'hamster',
'porcupine, hedgehog',
'fox squirrel, eastern fox squirrel, Sciurus niger',
'marmot',
'beaver',
'guinea pig, Cavia cobaya',
'sorrel',
'zebra',
'hog, pig, grunter, squealer, Sus scrofa',
'wild boar, boar, Sus scrofa',
'warthog',
'hippopotamus, hippo, river horse, Hippopotamus amphibius',
'ox',
'water buffalo, water ox, Asiatic buffalo, Bubalus bubalis',
'bison',
'ram, tup',
'bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis', # noqa: E501
'ibex, Capra ibex',
'hartebeest',
'impala, Aepyceros melampus',
'gazelle',
'Arabian camel, dromedary, Camelus dromedarius',
'llama',
'weasel',
'mink',
'polecat, fitch, foulmart, foumart, Mustela putorius',
'black-footed ferret, ferret, Mustela nigripes',
'otter',
'skunk, polecat, wood pussy',
'badger',
'armadillo',
'three-toed sloth, ai, Bradypus tridactylus',
'orangutan, orang, orangutang, Pongo pygmaeus',
'gorilla, Gorilla gorilla',
'chimpanzee, chimp, Pan troglodytes',
'gibbon, Hylobates lar',
'siamang, Hylobates syndactylus, Symphalangus syndactylus',
'guenon, guenon monkey',
'patas, hussar monkey, Erythrocebus patas',
'baboon',
'macaque',
'langur',
'colobus, colobus monkey',
'proboscis monkey, Nasalis larvatus',
'marmoset',
'capuchin, ringtail, Cebus capucinus',
'howler monkey, howler',
'titi, titi monkey',
'spider monkey, Ateles geoffroyi',
'squirrel monkey, Saimiri sciureus',
'Madagascar cat, ring-tailed lemur, Lemur catta',
'indri, indris, Indri indri, Indri brevicaudatus',
'Indian elephant, Elephas maximus',
'African elephant, Loxodonta africana',
'lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens',
'giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca',
'barracouta, snoek',
'eel',
'coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch', # noqa: E501
'rock beauty, Holocanthus tricolor',
'anemone fish',
'sturgeon',
'gar, garfish, garpike, billfish, Lepisosteus osseus',
'lionfish',
'puffer, pufferfish, blowfish, globefish',
'abacus',
'abaya',
"academic gown, academic robe, judge's robe",
'accordion, piano accordion, squeeze box',
'acoustic guitar',
'aircraft carrier, carrier, flattop, attack aircraft carrier',
'airliner',
'airship, dirigible',
'altar',
'ambulance',
'amphibian, amphibious vehicle',
'analog clock',
'apiary, bee house',
'apron',
'ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin', # noqa: E501
'assault rifle, assault gun',
'backpack, back pack, knapsack, packsack, rucksack, haversack',
'bakery, bakeshop, bakehouse',
'balance beam, beam',
'balloon',
'ballpoint, ballpoint pen, ballpen, Biro',
'Band Aid',
'banjo',
'bannister, banister, balustrade, balusters, handrail',
'barbell',
'barber chair',
'barbershop',
'barn',
'barometer',
'barrel, cask',
'barrow, garden cart, lawn cart, wheelbarrow',
'baseball',
'basketball',
'bassinet',
'bassoon',
'bathing cap, swimming cap',
'bath towel',
'bathtub, bathing tub, bath, tub',
'beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon', # noqa: E501
'beacon, lighthouse, beacon light, pharos',
'beaker',
'bearskin, busby, shako',
'beer bottle',
'beer glass',
'bell cote, bell cot',
'bib',
'bicycle-built-for-two, tandem bicycle, tandem',
'bikini, two-piece',
'binder, ring-binder',
'binoculars, field glasses, opera glasses',
'birdhouse',
'boathouse',
'bobsled, bobsleigh, bob',
'bolo tie, bolo, bola tie, bola',
'bonnet, poke bonnet',
'bookcase',
'bookshop, bookstore, bookstall',
'bottlecap',
'bow',
'bow tie, bow-tie, bowtie',
'brass, memorial tablet, plaque',
'brassiere, bra, bandeau',
'breakwater, groin, groyne, mole, bulwark, seawall, jetty',
'breastplate, aegis, egis',
'broom',
'bucket, pail',
'buckle',
'bulletproof vest',
'bullet train, bullet',
'butcher shop, meat market',
'cab, hack, taxi, taxicab',
'caldron, cauldron',
'candle, taper, wax light',
'cannon',
'canoe',
'can opener, tin opener',
'cardigan',
'car mirror',
'carousel, carrousel, merry-go-round, roundabout, whirligig',
"carpenter's kit, tool kit",
'carton',
'car wheel',
'cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM', # noqa: E501
'cassette',
'cassette player',
'castle',
'catamaran',
'CD player',
'cello, violoncello',
'cellular telephone, cellular phone, cellphone, cell, mobile phone',
'chain',
'chainlink fence',
'chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour', # noqa: E501
'chain saw, chainsaw',
'chest',
'chiffonier, commode',
'chime, bell, gong',
'china cabinet, china closet',
'Christmas stocking',
'church, church building',
'cinema, movie theater, movie theatre, movie house, picture palace',
'cleaver, meat cleaver, chopper',
'cliff dwelling',
'cloak',
'clog, geta, patten, sabot',
'cocktail shaker',
'coffee mug',
'coffeepot',
'coil, spiral, volute, whorl, helix',
'combination lock',
'computer keyboard, keypad',
'confectionery, confectionary, candy store',
'container ship, containership, container vessel',
'convertible',
'corkscrew, bottle screw',
'cornet, horn, trumpet, trump',
'cowboy boot',
'cowboy hat, ten-gallon hat',
'cradle',
'crane',
'crash helmet',
'crate',
'crib, cot',
'Crock Pot',
'croquet ball',
'crutch',
'cuirass',
'dam, dike, dyke',
'desk',
'desktop computer',
'dial telephone, dial phone',
'diaper, nappy, napkin',
'digital clock',
'digital watch',
'dining table, board',
'dishrag, dishcloth',
'dishwasher, dish washer, dishwashing machine',
'disk brake, disc brake',
'dock, dockage, docking facility',
'dogsled, dog sled, dog sleigh',
'dome',
'doormat, welcome mat',
'drilling platform, offshore rig',
'drum, membranophone, tympan',
'drumstick',
'dumbbell',
'Dutch oven',
'electric fan, blower',
'electric guitar',
'electric locomotive',
'entertainment center',
'envelope',
'espresso maker',
'face powder',
'feather boa, boa',
'file, file cabinet, filing cabinet',
'fireboat',
'fire engine, fire truck',
'fire screen, fireguard',
'flagpole, flagstaff',
'flute, transverse flute',
'folding chair',
'football helmet',
'forklift',
'fountain',
'fountain pen',
'four-poster',
'freight car',
'French horn, horn',
'frying pan, frypan, skillet',
'fur coat',
'garbage truck, dustcart',
'gasmask, respirator, gas helmet',
'gas pump, gasoline pump, petrol pump, island dispenser',
'goblet',
'go-kart',
'golf ball',
'golfcart, golf cart',
'gondola',
'gong, tam-tam',
'gown',
'grand piano, grand',
'greenhouse, nursery, glasshouse',
'grille, radiator grille',
'grocery store, grocery, food market, market',
'guillotine',
'hair slide',
'hair spray',
'half track',
'hammer',
'hamper',
'hand blower, blow dryer, blow drier, hair dryer, hair drier',
'hand-held computer, hand-held microcomputer',
'handkerchief, hankie, hanky, hankey',
'hard disc, hard disk, fixed disk',
'harmonica, mouth organ, harp, mouth harp',
'harp',
'harvester, reaper',
'hatchet',
'holster',
'home theater, home theatre',
'honeycomb',
'hook, claw',
'hoopskirt, crinoline',
'horizontal bar, high bar',
'horse cart, horse-cart',
'hourglass',
'iPod',
'iron, smoothing iron',
"jack-o'-lantern",
'jean, blue jean, denim',
'jeep, landrover',
'jersey, T-shirt, tee shirt',
'jigsaw puzzle',
'jinrikisha, ricksha, rickshaw',
'joystick',
'kimono',
'knee pad',
'knot',
'lab coat, laboratory coat',
'ladle',
'lampshade, lamp shade',
'laptop, laptop computer',
'lawn mower, mower',
'lens cap, lens cover',
'letter opener, paper knife, paperknife',
'library',
'lifeboat',
'lighter, light, igniter, ignitor',
'limousine, limo',
'liner, ocean liner',
'lipstick, lip rouge',
'Loafer',
'lotion',
'loudspeaker, speaker, speaker unit, loudspeaker system, speaker system', # noqa: E501
"loupe, jeweler's loupe",
'lumbermill, sawmill',
'magnetic compass',
'mailbag, postbag',
'mailbox, letter box',
'maillot',
'maillot, tank suit',
'manhole cover',
'maraca',
'marimba, xylophone',
'mask',
'matchstick',
'maypole',
'maze, labyrinth',
'measuring cup',
'medicine chest, medicine cabinet',
'megalith, megalithic structure',
'microphone, mike',
'microwave, microwave oven',
'military uniform',
'milk can',
'minibus',
'miniskirt, mini',
'minivan',
'missile',
'mitten',
'mixing bowl',
'mobile home, manufactured home',
'Model T',
'modem',
'monastery',
'monitor',
'moped',
'mortar',
'mortarboard',
'mosque',
'mosquito net',
'motor scooter, scooter',
'mountain bike, all-terrain bike, off-roader',
'mountain tent',
'mouse, computer mouse',
'mousetrap',
'moving van',
'muzzle',
'nail',
'neck brace',
'necklace',
'nipple',
'notebook, notebook computer',
'obelisk',
'oboe, hautboy, hautbois',
'ocarina, sweet potato',
'odometer, hodometer, mileometer, milometer',
'oil filter',
'organ, pipe organ',
'oscilloscope, scope, cathode-ray oscilloscope, CRO',
'overskirt',
'oxcart',
'oxygen mask',
'packet',
'paddle, boat paddle',
'paddlewheel, paddle wheel',
'padlock',
'paintbrush',
"pajama, pyjama, pj's, jammies",
'palace',
'panpipe, pandean pipe, syrinx',
'paper towel',
'parachute, chute',
'parallel bars, bars',
'park bench',
'parking meter',
'passenger car, coach, carriage',
'patio, terrace',
'pay-phone, pay-station',
'pedestal, plinth, footstall',
'pencil box, pencil case',
'pencil sharpener',
'perfume, essence',
'Petri dish',
'photocopier',
'pick, plectrum, plectron',
'pickelhaube',
'picket fence, paling',
'pickup, pickup truck',
'pier',
'piggy bank, penny bank',
'pill bottle',
'pillow',
'ping-pong ball',
'pinwheel',
'pirate, pirate ship',
'pitcher, ewer',
"plane, carpenter's plane, woodworking plane",
'planetarium',
'plastic bag',
'plate rack',
'plow, plough',
"plunger, plumber's helper",
'Polaroid camera, Polaroid Land camera',
'pole',
'police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria', # noqa: E501
'poncho',
'pool table, billiard table, snooker table',
'pop bottle, soda bottle',
'pot, flowerpot',
"potter's wheel",
'power drill',
'prayer rug, prayer mat',
'printer',
'prison, prison house',
'projectile, missile',
'projector',
'puck, hockey puck',
'punching bag, punch bag, punching ball, punchball',
'purse',
'quill, quill pen',
'quilt, comforter, comfort, puff',
'racer, race car, racing car',
'racket, racquet',
'radiator',
'radio, wireless',
'radio telescope, radio reflector',
'rain barrel',
'recreational vehicle, RV, R.V.',
'reel',
'reflex camera',
'refrigerator, icebox',
'remote control, remote',
'restaurant, eating house, eating place, eatery',
'revolver, six-gun, six-shooter',
'rifle',
'rocking chair, rocker',
'rotisserie',
'rubber eraser, rubber, pencil eraser',
'rugby ball',
'rule, ruler',
'running shoe',
'safe',
'safety pin',
'saltshaker, salt shaker',
'sandal',
'sarong',
'sax, saxophone',
'scabbard',
'scale, weighing machine',
'school bus',
'schooner',
'scoreboard',
'screen, CRT screen',
'screw',
'screwdriver',
'seat belt, seatbelt',
'sewing machine',
'shield, buckler',
'shoe shop, shoe-shop, shoe store',
'shoji',
'shopping basket',
'shopping cart',
'shovel',
'shower cap',
'shower curtain',
'ski',
'ski mask',
'sleeping bag',
'slide rule, slipstick',
'sliding door',
'slot, one-armed bandit',
'snorkel',
'snowmobile',
'snowplow, snowplough',
'soap dispenser',
'soccer ball',
'sock',
'solar dish, solar collector, solar furnace',
'sombrero',
'soup bowl',
'space bar',
'space heater',
'space shuttle',
'spatula',
'speedboat',
"spider web, spider's web",
'spindle',
'sports car, sport car',
'spotlight, spot',
'stage',
'steam locomotive',
'steel arch bridge',
'steel drum',
'stethoscope',
'stole',
'stone wall',
'stopwatch, stop watch',
'stove',
'strainer',
'streetcar, tram, tramcar, trolley, trolley car',
'stretcher',
'studio couch, day bed',
'stupa, tope',
'submarine, pigboat, sub, U-boat',
'suit, suit of clothes',
'sundial',
'sunglass',
'sunglasses, dark glasses, shades',
'sunscreen, sunblock, sun blocker',
'suspension bridge',
'swab, swob, mop',
'sweatshirt',
'swimming trunks, bathing trunks',
'swing',
'switch, electric switch, electrical switch',
'syringe',
'table lamp',
'tank, army tank, armored combat vehicle, armoured combat vehicle',
'tape player',
'teapot',
'teddy, teddy bear',
'television, television system',
'tennis ball',
'thatch, thatched roof',
'theater curtain, theatre curtain',
'thimble',
'thresher, thrasher, threshing machine',
'throne',
'tile roof',
'toaster',
'tobacco shop, tobacconist shop, tobacconist',
'toilet seat',
'torch',
'totem pole',
'tow truck, tow car, wrecker',
'toyshop',
'tractor',
'trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi', # noqa: E501
'tray',
'trench coat',
'tricycle, trike, velocipede',
'trimaran',
'tripod',
'triumphal arch',
'trolleybus, trolley coach, trackless trolley',
'trombone',
'tub, vat',
'turnstile',
'typewriter keyboard',
'umbrella',
'unicycle, monocycle',
'upright, upright piano',
'vacuum, vacuum cleaner',
'vase',
'vault',
'velvet',
'vending machine',
'vestment',
'viaduct',
'violin, fiddle',
'volleyball',
'waffle iron',
'wall clock',
'wallet, billfold, notecase, pocketbook',
'wardrobe, closet, press',
'warplane, military plane',
'washbasin, handbasin, washbowl, lavabo, wash-hand basin',
'washer, automatic washer, washing machine',
'water bottle',
'water jug',
'water tower',
'whiskey jug',
'whistle',
'wig',
'window screen',
'window shade',
'Windsor tie',
'wine bottle',
'wing',
'wok',
'wooden spoon',
'wool, woolen, woollen',
'worm fence, snake fence, snake-rail fence, Virginia fence',
'wreck',
'yawl',
'yurt',
'web site, website, internet site, site',
'comic book',
'crossword puzzle, crossword',
'street sign',
'traffic light, traffic signal, stoplight',
'book jacket, dust cover, dust jacket, dust wrapper',
'menu',
'plate',
'guacamole',
'consomme',
'hot pot, hotpot',
'trifle',
'ice cream, icecream',
'ice lolly, lolly, lollipop, popsicle',
'French loaf',
'bagel, beigel',
'pretzel',
'cheeseburger',
'hotdog, hot dog, red hot',
'mashed potato',
'head cabbage',
'broccoli',
'cauliflower',
'zucchini, courgette',
'spaghetti squash',
'acorn squash',
'butternut squash',
'cucumber, cuke',
'artichoke, globe artichoke',
'bell pepper',
'cardoon',
'mushroom',
'Granny Smith',
'strawberry',
'orange',
'lemon',
'fig',
'pineapple, ananas',
'banana',
'jackfruit, jak, jack',
'custard apple',
'pomegranate',
'hay',
'carbonara',
'chocolate sauce, chocolate syrup',
'dough',
'meat loaf, meatloaf',
'pizza, pizza pie',
'potpie',
'burrito',
'red wine',
'espresso',
'cup',
'eggnog',
'alp',
'bubble',
'cliff, drop, drop-off',
'coral reef',
'geyser',
'lakeside, lakeshore',
'promontory, headland, head, foreland',
'sandbar, sand bar',
'seashore, coast, seacoast, sea-coast',
'valley, vale',
'volcano',
'ballplayer, baseball player',
'groom, bridegroom',
'scuba diver',
'rapeseed',
'daisy',
"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum", # noqa: E501
'corn',
'acorn',
'hip, rose hip, rosehip',
'buckeye, horse chestnut, conker',
'coral fungus',
'agaric',
'gyromitra',
'stinkhorn, carrion fungus',
'earthstar',
'hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa', # noqa: E501
'bolete',
'ear, spike, capitulum',
'toilet tissue, toilet paper, bathroom tissue'
]
def load_annotations(self):
if self.ann_file is None:
folder_to_idx = find_folders(self.data_prefix)
samples = get_samples(
self.data_prefix,
folder_to_idx,
extensions=self.IMG_EXTENSIONS)
if len(samples) == 0:
raise (RuntimeError('Found 0 files in subfolders of: '
f'{self.data_prefix}. '
'Supported extensions are: '
f'{",".join(self.IMG_EXTENSIONS)}'))
self.folder_to_idx = folder_to_idx
elif isinstance(self.ann_file, str):
with open(self.ann_file) as f:
samples = [x.strip().rsplit(' ', 1) for x in f.readlines()]
else:
raise TypeError('ann_file must be a str or None')
self.samples = samples
data_infos = []
for filename, gt_label in self.samples:
info = {'img_prefix': self.data_prefix}
info['img_info'] = {'filename': filename}
info['gt_label'] = np.array(gt_label, dtype=np.int64)
data_infos.append(info)
return data_infos
@DATASETS.register_module()
class ImageNet_MultiTask(ImageNet, MultiTask):
num_tasks = 1000
def load_annotations(self):
if self.ann_file is None:
folder_to_idx = find_folders(self.data_prefix)
samples = get_samples(
self.data_prefix,
folder_to_idx,
extensions=self.IMG_EXTENSIONS)
if len(samples) == 0:
raise (RuntimeError('Found 0 files in subfolders of: '
f'{self.data_prefix}. '
'Supported extensions are: '
f'{",".join(self.IMG_EXTENSIONS)}'))
self.folder_to_idx = folder_to_idx
elif isinstance(self.ann_file, str):
with open(self.ann_file) as f:
samples = [x.strip().rsplit(' ', 1) for x in f.readlines()]
else:
raise TypeError('ann_file must be a str or None')
self.samples = samples
data_infos = []
for filename, gt_label in self.samples:
info = {'img_prefix': self.data_prefix}
info['img_info'] = {'filename': filename}
gt_label = np.eye(1000)[int(gt_label)]
info['gt_label'] = np.array(gt_label, dtype=np.int64)
data_infos.append(info)
return data_infos
| 37,785 | 32.203866 | 146 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/disentangle_data/dsprites.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import codecs
import numpy as np
import os
import os.path as osp
import torch
import torch.distributed as dist
from mmcv.runner import get_dist_info, master_only
from numpy import random
from mmcls.datasets.builder import DATASETS
from mmcls.datasets.utils import (download_and_extract_archive, download_url,
rm_suffix)
from .multi_task import MultiTask
@DATASETS.register_module()
class dSprites(MultiTask):
"""Latent factor values
Color: white
Shape: square, ellipse, heart
Scale: 6 values linearly spaced in [0.5, 1]
Orientation: 40 values in [0, 2 pi]
Position X: 32 values in [0, 1]
Position Y: 32 values in [0, 1]
""" # noqa: E501
resources = 'https://github.com/deepmind/dsprites-dataset/blob/master/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz'
split_ratio = 0.7
num_tasks = 5
CLASSES = [
]
def load_annotations(self):
filename = self.resources.rpartition('/')[2]
data_file = osp.join(
self.data_prefix, filename)
if not osp.exists(data_file):
self.download()
_, world_size = get_dist_info()
if world_size > 1:
dist.barrier()
assert osp.exists(data_file), \
'Shared storage seems unavailable. Please download dataset ' \
f'manually through {self.resource}.'
data = np.load(data_file)
num_data = len(data['imgs'])
data_index = np.arange(num_data)
np.random.seed(42)
np.random.shuffle(data_index)
train_index = data_index[:int(num_data*self.split_ratio)]
test_index = data_index[int(num_data*self.split_ratio):]
train_set = (data['imgs'][train_index],
data['latents_classes'][train_index][:, 1:])
test_set = (data['imgs'][test_index],
data['latents_classes'][test_index][:, 1:])
if not self.test_mode:
imgs, gt_labels = train_set
else:
imgs, gt_labels = test_set
data_infos = []
for img, gt_label in zip(imgs, gt_labels):
gt_label = np.array(gt_label, dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
@master_only
def download(self):
os.makedirs(self.data_prefix, exist_ok=True)
# download files
url = self.resources
filename = url.rpartition('/')[2]
download_url(url,
root=self.data_prefix,
filename=filename)
| 2,668 | 31.156627 | 121 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/disentangle_data/multi_task.py
|
import numpy as np
from mmcls.core.evaluation import precision_recall_f1, support
from mmcls.datasets.base_dataset import BaseDataset
from mmcls.datasets.builder import DATASETS
from mmcls.models.losses import accuracy
from tqdm import tqdm
@DATASETS.register_module()
class MultiTask(BaseDataset):
def evaluate(self,
multitask_results,
metric='accuracy',
metric_options=None,
logger=None):
"""Evaluate the dataset.
Args:
results (list): Testing results of the dataset.
metric (str | list[str]): Metrics to be evaluated.
Default value is `accuracy`.
metric_options (dict, optional): Options for calculating metrics.
Allowed keys are 'topk', 'thrs' and 'average_mode'.
Defaults to None.
logger (logging.Logger | str, optional): Logger used for printing
related information during evaluation. Defaults to None.
Returns:
dict: evaluation results
"""
if metric_options is None:
metric_options = {'topk': (1, 5)}
if isinstance(metric, str):
metrics = [metric]
else:
metrics = metric
allowed_metrics = [
'accuracy', 'precision', 'recall', 'f1_score', 'support'
]
eval_results = {}
if isinstance(multitask_results, dict):
for i in tqdm(range(self.num_tasks)):
results = np.vstack(multitask_results[f'task_{i}'])
gt_labels = self.get_gt_labels()[:,i]
num_imgs = len(results)
assert len(gt_labels) == num_imgs, 'dataset testing results should '\
'be of the same length as gt_labels.'
invalid_metrics = set(metrics) - set(allowed_metrics)
if len(invalid_metrics) != 0:
raise ValueError(f'metric {invalid_metrics} is not supported.')
topk = metric_options.get('topk', (1, 5))
thrs = metric_options.get('thrs')
average_mode = metric_options.get('average_mode', 'macro')
if 'accuracy' in metrics:
if thrs is not None:
acc = accuracy(results, gt_labels, topk=topk, thrs=thrs)
else:
acc = accuracy(results, gt_labels, topk=topk)
if isinstance(topk, tuple):
eval_results_ = {
f'task_{i}_accuracy_top-{k}': a
for k, a in zip(topk, acc)
}
else:
eval_results_ = {'task_{i}_accuracy': acc}
if isinstance(thrs, tuple):
for key, values in eval_results_.items():
eval_results.update({
f'{key}_thr_{thr:.2f}': value.item()
for thr, value in zip(thrs, values)
})
else:
eval_results.update(
{k: v.item()
for k, v in eval_results_.items()})
if 'support' in metrics:
support_value = support(
results, gt_labels, average_mode=average_mode)
eval_results[f'task_{i}_support'] = support_value
precision_recall_f1_keys = ['precision', 'recall', 'f1_score']
if len(set(metrics) & set(precision_recall_f1_keys)) != 0:
if thrs is not None:
precision_recall_f1_values = precision_recall_f1(
results, gt_labels, average_mode=average_mode, thrs=thrs)
else:
precision_recall_f1_values = precision_recall_f1(
results, gt_labels, average_mode=average_mode)
for key, values in zip(precision_recall_f1_keys,
precision_recall_f1_values):
if key in metrics:
if isinstance(thrs, tuple):
eval_results.update({
f'task_{i}_{key}_thr_{thr:.2f}': value
for thr, value in zip(thrs, values)
})
else:
eval_results[key] = values
return eval_results
| 4,638 | 43.605769 | 85 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/disentangle_data/shape3d.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import codecs
import os
import os.path as osp
import numpy as np
import torch
import torch.distributed as dist
from mmcv.runner import get_dist_info, master_only
from .multi_task import MultiTask
from mmcls.datasets.builder import DATASETS
from mmcls.datasets.utils import download_and_extract_archive, download_url, rm_suffix
import h5py
@DATASETS.register_module()
class Shape3D(MultiTask):
"""Latent factor values
Color: white
Shape: square, ellipse, heart
Scale: 6 values linearly spaced in [0.5, 1]
Orientation: 40 values in [0, 2 pi]
Position X: 32 values in [0, 1]
Position Y: 32 values in [0, 1]
""" # noqa: E501
resources = '3dshapes.h5'
split_ratio = 0.7
num_tasks = 6
CLASSES = ['floor_hue', 'wall_hue', 'object_hue', 'scale', 'shape',
'orientation']
def load_annotations(self):
filename = self.resources.rpartition('/')[2]
data_file = osp.join(
self.data_prefix, filename)
if not osp.exists(data_file):
self.download()
_, world_size = get_dist_info()
if world_size > 1:
dist.barrier()
assert osp.exists(data_file), \
'Shared storage seems unavailable. Please download dataset ' \
f'manually through {self.resource}.'
data = h5py.File(data_file, 'r')
num_data = len(data['images'])
labels = self.convert_value_to_label(data)
train_set = (data['images'][:int(num_data*self.split_ratio)],
labels[:int(num_data*self.split_ratio)])
test_set = (data['images'][int(num_data*self.split_ratio):],
labels[int(num_data*self.split_ratio):])
if not self.test_mode:
imgs, gt_labels = train_set
else:
imgs, gt_labels = test_set
data_infos = []
for img, gt_label in zip(imgs, gt_labels):
gt_label = np.array(gt_label, dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
def convert_value_to_label(self, data):
labels = []
for i in range(self.num_tasks):
values = np.unique(data['labels'][:, i])
values = np.sort(values)
num_class = len(values)
print(f'Task {i}, with {num_class} classes')
value2cls = {values[c]:c for c in range(num_class)}
label_converted = np.vectorize(value2cls.get)(data['labels'][:, i])
labels.append(label_converted)
labels = np.stack(labels, axis=-1)
return labels
@master_only
def download(self):
assert f'Shape3D dataset can only be downloaded manually'
| 2,826 | 32.258824 | 86 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/disentangle_data/__init__.py
|
from .dsprites import dSprites
from .shape3d import Shape3D
| 59 | 29 | 30 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/disentangle_data/mpi3d.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import codecs
import numpy as np
import os
import os.path as osp
import torch
import torch.distributed as dist
from mmcv.runner import get_dist_info, master_only
from numpy import random
from mmcls.datasets.builder import DATASETS
from mmcls.datasets.utils import (download_and_extract_archive, download_url,
rm_suffix)
from .multi_task import MultiTask
@DATASETS.register_module()
class MPI3d(MultiTask):
"""Factors Possible Values
object_color white=0, green=1, red=2, blue=3, brown=4, olive=5
object_shape cone=0, cube=1, cylinder=2, hexagonal=3, pyramid=4, sphere=5
object_size small=0, large=1
camera_height top=0, center=1, bottom=2
background_color purple=0, sea green=1, salmon=2
horizontal_axis 0,...,39
vertical_axis 0,...,39
""" # noqa: E501
resources = 'https://github.com/deepmind/dsprites-dataset/blob/master/dsprites_ndarray_co1sh3sc6or40x32y32_64x64.npz'
split_ratio = 0.7
num_tasks = 7
num_classes = [6,6,2,3,3,40,40]
CLASSES = [
]
def load_annotations(self):
filename = self.resources.rpartition('/')[2]
data_file = osp.join(
self.data_prefix, filename)
if not osp.exists(data_file):
self.download()
_, world_size = get_dist_info()
if world_size > 1:
dist.barrier()
assert osp.exists(data_file), \
'Shared storage seems unavailable. Please download dataset ' \
f'manually through {self.resource}.'
data = np.load(data_file)
num_data = len(data['images'])
label = self.create_label(num_data)
data_index = np.arange(num_data)
np.random.seed(42)
np.random.shuffle(data_index)
train_index = data_index[:int(num_data*self.split_ratio)]
test_index = data_index[int(num_data*self.split_ratio):]
train_set = (data['images'][train_index],
label[train_index])
test_set = (data['images'][test_index],
label[test_index])
if not self.test_mode:
imgs, gt_labels = train_set
else:
imgs, gt_labels = test_set
data_infos = []
for img, gt_label in zip(imgs, gt_labels):
gt_label = np.array(gt_label, dtype=np.int64)
info = {'img': img, 'gt_label': gt_label}
data_infos.append(info)
return data_infos
def create_label(self, num_data):
label = np.zeros((num_data, self.num_tasks))
for i in range(self.num_tasks):
num_per_cls = np.prod([num_factor for f, num_factor in enumerate(self.num_classes) if f != i])
for j in range(self.num_classes[i]):
label[:, j*num_per_cls:(j+1)*num_per_cls] = j
return label
@master_only
def download(self):
os.makedirs(self.data_prefix, exist_ok=True)
# download files
url = self.resources
filename = url.rpartition('/')[2]
download_url(url,
root=self.data_prefix,
filename=filename)
| 3,167 | 32 | 121 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/samplers/distributed_sampler.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
class DistributedSampler(_DistributedSampler):
def __init__(self,
dataset,
num_replicas=None,
rank=None,
shuffle=True,
round_up=True):
super().__init__(dataset, num_replicas=num_replicas, rank=rank)
self.shuffle = shuffle
self.round_up = round_up
if self.round_up:
self.total_size = self.num_samples * self.num_replicas
else:
self.total_size = len(self.dataset)
def __iter__(self):
# deterministically shuffle based on epoch
if self.shuffle:
g = torch.Generator()
g.manual_seed(self.epoch)
indices = torch.randperm(len(self.dataset), generator=g).tolist()
else:
indices = torch.arange(len(self.dataset)).tolist()
# add extra samples to make it evenly divisible
if self.round_up:
indices = (
indices *
int(self.total_size / len(indices) + 1))[:self.total_size]
assert len(indices) == self.total_size
# subsample
indices = indices[self.rank:self.total_size:self.num_replicas]
if self.round_up:
assert len(indices) == self.num_samples
return iter(indices)
| 1,433 | 31.590909 | 77 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/samplers/__init__.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from .distributed_sampler import DistributedSampler
__all__ = ['DistributedSampler']
| 134 | 26 | 51 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/pipelines/loading.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
import mmcv
import numpy as np
from ..builder import PIPELINES
@PIPELINES.register_module()
class LoadImageFromFile(object):
"""Load an image from file.
Required keys are "img_prefix" and "img_info" (a dict that must contain the
key "filename"). Added or updated keys are "filename", "img", "img_shape",
"ori_shape" (same as `img_shape`) and "img_norm_cfg" (means=0 and stds=1).
Args:
to_float32 (bool): Whether to convert the loaded image to a float32
numpy array. If set to False, the loaded image is an uint8 array.
Defaults to False.
color_type (str): The flag argument for :func:`mmcv.imfrombytes()`.
Defaults to 'color'.
file_client_args (dict): Arguments to instantiate a FileClient.
See :class:`mmcv.fileio.FileClient` for details.
Defaults to ``dict(backend='disk')``.
"""
def __init__(self,
to_float32=False,
color_type='color',
file_client_args=dict(backend='disk')):
self.to_float32 = to_float32
self.color_type = color_type
self.file_client_args = file_client_args.copy()
self.file_client = None
def __call__(self, results):
if self.file_client is None:
self.file_client = mmcv.FileClient(**self.file_client_args)
if results['img_prefix'] is not None:
filename = osp.join(results['img_prefix'],
results['img_info']['filename'])
else:
filename = results['img_info']['filename']
img_bytes = self.file_client.get(filename)
img = mmcv.imfrombytes(img_bytes, flag=self.color_type)
if self.to_float32:
img = img.astype(np.float32)
results['filename'] = filename
results['ori_filename'] = results['img_info']['filename']
results['img'] = img
results['img_shape'] = img.shape
results['ori_shape'] = img.shape
num_channels = 1 if len(img.shape) < 3 else img.shape[2]
results['img_norm_cfg'] = dict(
mean=np.zeros(num_channels, dtype=np.float32),
std=np.ones(num_channels, dtype=np.float32),
to_rgb=False)
return results
def __repr__(self):
repr_str = (f'{self.__class__.__name__}('
f'to_float32={self.to_float32}, '
f"color_type='{self.color_type}', "
f'file_client_args={self.file_client_args})')
return repr_str
| 2,607 | 35.732394 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/pipelines/compose.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from collections.abc import Sequence
from mmcv.utils import build_from_cfg
from ..builder import PIPELINES
@PIPELINES.register_module()
class Compose(object):
"""Compose a data pipeline with a sequence of transforms.
Args:
transforms (list[dict | callable]):
Either config dicts of transforms or transform objects.
"""
def __init__(self, transforms):
assert isinstance(transforms, Sequence)
self.transforms = []
for transform in transforms:
if isinstance(transform, dict):
transform = build_from_cfg(transform, PIPELINES)
self.transforms.append(transform)
elif callable(transform):
self.transforms.append(transform)
else:
raise TypeError('transform must be callable or a dict, but got'
f' {type(transform)}')
def __call__(self, data):
for t in self.transforms:
data = t(data)
if data is None:
return None
return data
def __repr__(self):
format_string = self.__class__.__name__ + '('
for t in self.transforms:
format_string += f'\n {t}'
format_string += '\n)'
return format_string
| 1,339 | 29.454545 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/pipelines/auto_augment.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import inspect
import random
from numbers import Number
from typing import Sequence
import mmcv
import numpy as np
from ..builder import PIPELINES
from .compose import Compose
# Default hyperparameters for all Ops
_HPARAMS_DEFAULT = dict(pad_val=128)
def random_negative(value, random_negative_prob):
"""Randomly negate value based on random_negative_prob."""
return -value if np.random.rand() < random_negative_prob else value
def merge_hparams(policy: dict, hparams: dict):
"""Merge hyperparameters into policy config.
Only merge partial hyperparameters required of the policy.
Args:
policy (dict): Original policy config dict.
hparams (dict): Hyperparameters need to be merged.
Returns:
dict: Policy config dict after adding ``hparams``.
"""
op = PIPELINES.get(policy['type'])
assert op is not None, f'Invalid policy type "{policy["type"]}".'
for key, value in hparams.items():
if policy.get(key, None) is not None:
continue
if key in inspect.getfullargspec(op.__init__).args:
policy[key] = value
return policy
@PIPELINES.register_module()
class AutoAugment(object):
"""Auto augmentation.
This data augmentation is proposed in `AutoAugment: Learning Augmentation
Policies from Data <https://arxiv.org/abs/1805.09501>`_.
Args:
policies (list[list[dict]]): The policies of auto augmentation. Each
policy in ``policies`` is a specific augmentation policy, and is
composed by several augmentations (dict). When AutoAugment is
called, a random policy in ``policies`` will be selected to
augment images.
hparams (dict): Configs of hyperparameters. Hyperparameters will be
used in policies that require these arguments if these arguments
are not set in policy dicts. Defaults to use _HPARAMS_DEFAULT.
"""
def __init__(self, policies, hparams=_HPARAMS_DEFAULT):
assert isinstance(policies, list) and len(policies) > 0, \
'Policies must be a non-empty list.'
for policy in policies:
assert isinstance(policy, list) and len(policy) > 0, \
'Each policy in policies must be a non-empty list.'
for augment in policy:
assert isinstance(augment, dict) and 'type' in augment, \
'Each specific augmentation must be a dict with key' \
' "type".'
self.hparams = hparams
policies = copy.deepcopy(policies)
self.policies = []
for sub in policies:
merged_sub = [merge_hparams(policy, hparams) for policy in sub]
self.policies.append(merged_sub)
self.sub_policy = [Compose(policy) for policy in self.policies]
def __call__(self, results):
sub_policy = random.choice(self.sub_policy)
return sub_policy(results)
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(policies={self.policies})'
return repr_str
@PIPELINES.register_module()
class RandAugment(object):
r"""Random augmentation.
This data augmentation is proposed in `RandAugment: Practical automated
data augmentation with a reduced search space
<https://arxiv.org/abs/1909.13719>`_.
Args:
policies (list[dict]): The policies of random augmentation. Each
policy in ``policies`` is one specific augmentation policy (dict).
The policy shall at least have key `type`, indicating the type of
augmentation. For those which have magnitude, (given to the fact
they are named differently in different augmentation, )
`magnitude_key` and `magnitude_range` shall be the magnitude
argument (str) and the range of magnitude (tuple in the format of
(val1, val2)), respectively. Note that val1 is not necessarily
less than val2.
num_policies (int): Number of policies to select from policies each
time.
magnitude_level (int | float): Magnitude level for all the augmentation
selected.
total_level (int | float): Total level for the magnitude. Defaults to
30.
magnitude_std (Number | str): Deviation of magnitude noise applied.
- If positive number, magnitude is sampled from normal distribution
(mean=magnitude, std=magnitude_std).
- If 0 or negative number, magnitude remains unchanged.
- If str "inf", magnitude is sampled from uniform distribution
(range=[min, magnitude]).
hparams (dict): Configs of hyperparameters. Hyperparameters will be
used in policies that require these arguments if these arguments
are not set in policy dicts. Defaults to use _HPARAMS_DEFAULT.
Note:
`magnitude_std` will introduce some randomness to policy, modified by
https://github.com/rwightman/pytorch-image-models.
When magnitude_std=0, we calculate the magnitude as follows:
.. math::
\text{magnitude} = \frac{\text{magnitude\_level}}
{\text{total\_level}} \times (\text{val2} - \text{val1})
+ \text{val1}
"""
def __init__(self,
policies,
num_policies,
magnitude_level,
magnitude_std=0.,
total_level=30,
hparams=_HPARAMS_DEFAULT):
assert isinstance(num_policies, int), 'Number of policies must be ' \
f'of int type, got {type(num_policies)} instead.'
assert isinstance(magnitude_level, (int, float)), \
'Magnitude level must be of int or float type, ' \
f'got {type(magnitude_level)} instead.'
assert isinstance(total_level, (int, float)), 'Total level must be ' \
f'of int or float type, got {type(total_level)} instead.'
assert isinstance(policies, list) and len(policies) > 0, \
'Policies must be a non-empty list.'
assert isinstance(magnitude_std, (Number, str)), \
'Magnitude std must be of number or str type, ' \
f'got {type(magnitude_std)} instead.'
if isinstance(magnitude_std, str):
assert magnitude_std == 'inf', \
'Magnitude std must be of number or "inf", ' \
f'got "{magnitude_std}" instead.'
assert num_policies > 0, 'num_policies must be greater than 0.'
assert magnitude_level >= 0, 'magnitude_level must be no less than 0.'
assert total_level > 0, 'total_level must be greater than 0.'
self.num_policies = num_policies
self.magnitude_level = magnitude_level
self.magnitude_std = magnitude_std
self.total_level = total_level
self.hparams = hparams
policies = copy.deepcopy(policies)
self._check_policies(policies)
self.policies = [merge_hparams(policy, hparams) for policy in policies]
def _check_policies(self, policies):
for policy in policies:
assert isinstance(policy, dict) and 'type' in policy, \
'Each policy must be a dict with key "type".'
type_name = policy['type']
magnitude_key = policy.get('magnitude_key', None)
if magnitude_key is not None:
assert 'magnitude_range' in policy, \
f'RandAugment policy {type_name} needs `magnitude_range`.'
magnitude_range = policy['magnitude_range']
assert (isinstance(magnitude_range, Sequence)
and len(magnitude_range) == 2), \
f'`magnitude_range` of RandAugment policy {type_name} ' \
f'should be a Sequence with two numbers.'
def _process_policies(self, policies):
processed_policies = []
for policy in policies:
processed_policy = copy.deepcopy(policy)
magnitude_key = processed_policy.pop('magnitude_key', None)
if magnitude_key is not None:
magnitude = self.magnitude_level
# if magnitude_std is positive number or 'inf', move
# magnitude_value randomly.
if self.magnitude_std == 'inf':
magnitude = random.uniform(0, magnitude)
elif self.magnitude_std > 0:
magnitude = random.gauss(magnitude, self.magnitude_std)
magnitude = min(self.total_level, max(0, magnitude))
val1, val2 = processed_policy.pop('magnitude_range')
magnitude = (magnitude / self.total_level) * (val2 -
val1) + val1
processed_policy.update({magnitude_key: magnitude})
processed_policies.append(processed_policy)
return processed_policies
def __call__(self, results):
if self.num_policies == 0:
return results
sub_policy = random.choices(self.policies, k=self.num_policies)
sub_policy = self._process_policies(sub_policy)
sub_policy = Compose(sub_policy)
return sub_policy(results)
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(policies={self.policies}, '
repr_str += f'num_policies={self.num_policies}, '
repr_str += f'magnitude_level={self.magnitude_level}, '
repr_str += f'total_level={self.total_level})'
return repr_str
@PIPELINES.register_module()
class Shear(object):
"""Shear images.
Args:
magnitude (int | float): The magnitude used for shear.
pad_val (int, Sequence[int]): Pixel pad_val value for constant fill.
If a sequence of length 3, it is used to pad_val R, G, B channels
respectively. Defaults to 128.
prob (float): The probability for performing Shear therefore should be
in range [0, 1]. Defaults to 0.5.
direction (str): The shearing direction. Options are 'horizontal' and
'vertical'. Defaults to 'horizontal'.
random_negative_prob (float): The probability that turns the magnitude
negative, which should be in range [0,1]. Defaults to 0.5.
interpolation (str): Interpolation method. Options are 'nearest',
'bilinear', 'bicubic', 'area', 'lanczos'. Defaults to 'bicubic'.
"""
def __init__(self,
magnitude,
pad_val=128,
prob=0.5,
direction='horizontal',
random_negative_prob=0.5,
interpolation='bicubic'):
assert isinstance(magnitude, (int, float)), 'The magnitude type must '\
f'be int or float, but got {type(magnitude)} instead.'
if isinstance(pad_val, int):
pad_val = tuple([pad_val] * 3)
elif isinstance(pad_val, Sequence):
assert len(pad_val) == 3, 'pad_val as a tuple must have 3 ' \
f'elements, got {len(pad_val)} instead.'
assert all(isinstance(i, int) for i in pad_val), 'pad_val as a '\
'tuple must got elements of int type.'
else:
raise TypeError('pad_val must be int or tuple with 3 elements.')
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert direction in ('horizontal', 'vertical'), 'direction must be ' \
f'either "horizontal" or "vertical", got {direction} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.magnitude = magnitude
self.pad_val = tuple(pad_val)
self.prob = prob
self.direction = direction
self.random_negative_prob = random_negative_prob
self.interpolation = interpolation
def __call__(self, results):
if np.random.rand() > self.prob:
return results
magnitude = random_negative(self.magnitude, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
img_sheared = mmcv.imshear(
img,
magnitude,
direction=self.direction,
border_value=self.pad_val,
interpolation=self.interpolation)
results[key] = img_sheared.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'pad_val={self.pad_val}, '
repr_str += f'prob={self.prob}, '
repr_str += f'direction={self.direction}, '
repr_str += f'random_negative_prob={self.random_negative_prob}, '
repr_str += f'interpolation={self.interpolation})'
return repr_str
@PIPELINES.register_module()
class Translate(object):
"""Translate images.
Args:
magnitude (int | float): The magnitude used for translate. Note that
the offset is calculated by magnitude * size in the corresponding
direction. With a magnitude of 1, the whole image will be moved out
of the range.
pad_val (int, Sequence[int]): Pixel pad_val value for constant fill.
If a sequence of length 3, it is used to pad_val R, G, B channels
respectively. Defaults to 128.
prob (float): The probability for performing translate therefore should
be in range [0, 1]. Defaults to 0.5.
direction (str): The translating direction. Options are 'horizontal'
and 'vertical'. Defaults to 'horizontal'.
random_negative_prob (float): The probability that turns the magnitude
negative, which should be in range [0,1]. Defaults to 0.5.
interpolation (str): Interpolation method. Options are 'nearest',
'bilinear', 'bicubic', 'area', 'lanczos'. Defaults to 'nearest'.
"""
def __init__(self,
magnitude,
pad_val=128,
prob=0.5,
direction='horizontal',
random_negative_prob=0.5,
interpolation='nearest'):
assert isinstance(magnitude, (int, float)), 'The magnitude type must '\
f'be int or float, but got {type(magnitude)} instead.'
if isinstance(pad_val, int):
pad_val = tuple([pad_val] * 3)
elif isinstance(pad_val, Sequence):
assert len(pad_val) == 3, 'pad_val as a tuple must have 3 ' \
f'elements, got {len(pad_val)} instead.'
assert all(isinstance(i, int) for i in pad_val), 'pad_val as a '\
'tuple must got elements of int type.'
else:
raise TypeError('pad_val must be int or tuple with 3 elements.')
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert direction in ('horizontal', 'vertical'), 'direction must be ' \
f'either "horizontal" or "vertical", got {direction} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.magnitude = magnitude
self.pad_val = tuple(pad_val)
self.prob = prob
self.direction = direction
self.random_negative_prob = random_negative_prob
self.interpolation = interpolation
def __call__(self, results):
if np.random.rand() > self.prob:
return results
magnitude = random_negative(self.magnitude, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
height, width = img.shape[:2]
if self.direction == 'horizontal':
offset = magnitude * width
else:
offset = magnitude * height
img_translated = mmcv.imtranslate(
img,
offset,
direction=self.direction,
border_value=self.pad_val,
interpolation=self.interpolation)
results[key] = img_translated.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'pad_val={self.pad_val}, '
repr_str += f'prob={self.prob}, '
repr_str += f'direction={self.direction}, '
repr_str += f'random_negative_prob={self.random_negative_prob}, '
repr_str += f'interpolation={self.interpolation})'
return repr_str
@PIPELINES.register_module()
class Rotate(object):
"""Rotate images.
Args:
angle (float): The angle used for rotate. Positive values stand for
clockwise rotation.
center (tuple[float], optional): Center point (w, h) of the rotation in
the source image. If None, the center of the image will be used.
Defaults to None.
scale (float): Isotropic scale factor. Defaults to 1.0.
pad_val (int, Sequence[int]): Pixel pad_val value for constant fill.
If a sequence of length 3, it is used to pad_val R, G, B channels
respectively. Defaults to 128.
prob (float): The probability for performing Rotate therefore should be
in range [0, 1]. Defaults to 0.5.
random_negative_prob (float): The probability that turns the angle
negative, which should be in range [0,1]. Defaults to 0.5.
interpolation (str): Interpolation method. Options are 'nearest',
'bilinear', 'bicubic', 'area', 'lanczos'. Defaults to 'nearest'.
"""
def __init__(self,
angle,
center=None,
scale=1.0,
pad_val=128,
prob=0.5,
random_negative_prob=0.5,
interpolation='nearest'):
assert isinstance(angle, float), 'The angle type must be float, but ' \
f'got {type(angle)} instead.'
if isinstance(center, tuple):
assert len(center) == 2, 'center as a tuple must have 2 ' \
f'elements, got {len(center)} elements instead.'
else:
assert center is None, 'The center type' \
f'must be tuple or None, got {type(center)} instead.'
assert isinstance(scale, float), 'the scale type must be float, but ' \
f'got {type(scale)} instead.'
if isinstance(pad_val, int):
pad_val = tuple([pad_val] * 3)
elif isinstance(pad_val, Sequence):
assert len(pad_val) == 3, 'pad_val as a tuple must have 3 ' \
f'elements, got {len(pad_val)} instead.'
assert all(isinstance(i, int) for i in pad_val), 'pad_val as a '\
'tuple must got elements of int type.'
else:
raise TypeError('pad_val must be int or tuple with 3 elements.')
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.angle = angle
self.center = center
self.scale = scale
self.pad_val = tuple(pad_val)
self.prob = prob
self.random_negative_prob = random_negative_prob
self.interpolation = interpolation
def __call__(self, results):
if np.random.rand() > self.prob:
return results
angle = random_negative(self.angle, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
img_rotated = mmcv.imrotate(
img,
angle,
center=self.center,
scale=self.scale,
border_value=self.pad_val,
interpolation=self.interpolation)
results[key] = img_rotated.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(angle={self.angle}, '
repr_str += f'center={self.center}, '
repr_str += f'scale={self.scale}, '
repr_str += f'pad_val={self.pad_val}, '
repr_str += f'prob={self.prob}, '
repr_str += f'random_negative_prob={self.random_negative_prob}, '
repr_str += f'interpolation={self.interpolation})'
return repr_str
@PIPELINES.register_module()
class AutoContrast(object):
"""Auto adjust image contrast.
Args:
prob (float): The probability for performing invert therefore should
be in range [0, 1]. Defaults to 0.5.
"""
def __init__(self, prob=0.5):
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_contrasted = mmcv.auto_contrast(img)
results[key] = img_contrasted.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(prob={self.prob})'
return repr_str
@PIPELINES.register_module()
class Invert(object):
"""Invert images.
Args:
prob (float): The probability for performing invert therefore should
be in range [0, 1]. Defaults to 0.5.
"""
def __init__(self, prob=0.5):
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_inverted = mmcv.iminvert(img)
results[key] = img_inverted.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(prob={self.prob})'
return repr_str
@PIPELINES.register_module()
class Equalize(object):
"""Equalize the image histogram.
Args:
prob (float): The probability for performing invert therefore should
be in range [0, 1]. Defaults to 0.5.
"""
def __init__(self, prob=0.5):
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_equalized = mmcv.imequalize(img)
results[key] = img_equalized.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(prob={self.prob})'
return repr_str
@PIPELINES.register_module()
class Solarize(object):
"""Solarize images (invert all pixel values above a threshold).
Args:
thr (int | float): The threshold above which the pixels value will be
inverted.
prob (float): The probability for solarizing therefore should be in
range [0, 1]. Defaults to 0.5.
"""
def __init__(self, thr, prob=0.5):
assert isinstance(thr, (int, float)), 'The thr type must '\
f'be int or float, but got {type(thr)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.thr = thr
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_solarized = mmcv.solarize(img, thr=self.thr)
results[key] = img_solarized.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(thr={self.thr}, '
repr_str += f'prob={self.prob})'
return repr_str
@PIPELINES.register_module()
class SolarizeAdd(object):
"""SolarizeAdd images (add a certain value to pixels below a threshold).
Args:
magnitude (int | float): The value to be added to pixels below the thr.
thr (int | float): The threshold below which the pixels value will be
adjusted.
prob (float): The probability for solarizing therefore should be in
range [0, 1]. Defaults to 0.5.
"""
def __init__(self, magnitude, thr=128, prob=0.5):
assert isinstance(magnitude, (int, float)), 'The thr magnitude must '\
f'be int or float, but got {type(magnitude)} instead.'
assert isinstance(thr, (int, float)), 'The thr type must '\
f'be int or float, but got {type(thr)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.magnitude = magnitude
self.thr = thr
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_solarized = np.where(img < self.thr,
np.minimum(img + self.magnitude, 255),
img)
results[key] = img_solarized.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'thr={self.thr}, '
repr_str += f'prob={self.prob})'
return repr_str
@PIPELINES.register_module()
class Posterize(object):
"""Posterize images (reduce the number of bits for each color channel).
Args:
bits (int | float): Number of bits for each pixel in the output img,
which should be less or equal to 8.
prob (float): The probability for posterizing therefore should be in
range [0, 1]. Defaults to 0.5.
"""
def __init__(self, bits, prob=0.5):
assert bits <= 8, f'The bits must be less than 8, got {bits} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.bits = int(bits)
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_posterized = mmcv.posterize(img, bits=self.bits)
results[key] = img_posterized.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(bits={self.bits}, '
repr_str += f'prob={self.prob})'
return repr_str
@PIPELINES.register_module()
class Contrast(object):
"""Adjust images contrast.
Args:
magnitude (int | float): The magnitude used for adjusting contrast. A
positive magnitude would enhance the contrast and a negative
magnitude would make the image grayer. A magnitude=0 gives the
origin img.
prob (float): The probability for performing contrast adjusting
therefore should be in range [0, 1]. Defaults to 0.5.
random_negative_prob (float): The probability that turns the magnitude
negative, which should be in range [0,1]. Defaults to 0.5.
"""
def __init__(self, magnitude, prob=0.5, random_negative_prob=0.5):
assert isinstance(magnitude, (int, float)), 'The magnitude type must '\
f'be int or float, but got {type(magnitude)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.magnitude = magnitude
self.prob = prob
self.random_negative_prob = random_negative_prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
magnitude = random_negative(self.magnitude, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
img_contrasted = mmcv.adjust_contrast(img, factor=1 + magnitude)
results[key] = img_contrasted.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'prob={self.prob}, '
repr_str += f'random_negative_prob={self.random_negative_prob})'
return repr_str
@PIPELINES.register_module()
class ColorTransform(object):
"""Adjust images color balance.
Args:
magnitude (int | float): The magnitude used for color transform. A
positive magnitude would enhance the color and a negative magnitude
would make the image grayer. A magnitude=0 gives the origin img.
prob (float): The probability for performing ColorTransform therefore
should be in range [0, 1]. Defaults to 0.5.
random_negative_prob (float): The probability that turns the magnitude
negative, which should be in range [0,1]. Defaults to 0.5.
"""
def __init__(self, magnitude, prob=0.5, random_negative_prob=0.5):
assert isinstance(magnitude, (int, float)), 'The magnitude type must '\
f'be int or float, but got {type(magnitude)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.magnitude = magnitude
self.prob = prob
self.random_negative_prob = random_negative_prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
magnitude = random_negative(self.magnitude, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
img_color_adjusted = mmcv.adjust_color(img, alpha=1 + magnitude)
results[key] = img_color_adjusted.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'prob={self.prob}, '
repr_str += f'random_negative_prob={self.random_negative_prob})'
return repr_str
@PIPELINES.register_module()
class Brightness(object):
"""Adjust images brightness.
Args:
magnitude (int | float): The magnitude used for adjusting brightness. A
positive magnitude would enhance the brightness and a negative
magnitude would make the image darker. A magnitude=0 gives the
origin img.
prob (float): The probability for performing contrast adjusting
therefore should be in range [0, 1]. Defaults to 0.5.
random_negative_prob (float): The probability that turns the magnitude
negative, which should be in range [0,1]. Defaults to 0.5.
"""
def __init__(self, magnitude, prob=0.5, random_negative_prob=0.5):
assert isinstance(magnitude, (int, float)), 'The magnitude type must '\
f'be int or float, but got {type(magnitude)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.magnitude = magnitude
self.prob = prob
self.random_negative_prob = random_negative_prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
magnitude = random_negative(self.magnitude, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
img_brightened = mmcv.adjust_brightness(img, factor=1 + magnitude)
results[key] = img_brightened.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'prob={self.prob}, '
repr_str += f'random_negative_prob={self.random_negative_prob})'
return repr_str
@PIPELINES.register_module()
class Sharpness(object):
"""Adjust images sharpness.
Args:
magnitude (int | float): The magnitude used for adjusting sharpness. A
positive magnitude would enhance the sharpness and a negative
magnitude would make the image bulr. A magnitude=0 gives the
origin img.
prob (float): The probability for performing contrast adjusting
therefore should be in range [0, 1]. Defaults to 0.5.
random_negative_prob (float): The probability that turns the magnitude
negative, which should be in range [0,1]. Defaults to 0.5.
"""
def __init__(self, magnitude, prob=0.5, random_negative_prob=0.5):
assert isinstance(magnitude, (int, float)), 'The magnitude type must '\
f'be int or float, but got {type(magnitude)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
assert 0 <= random_negative_prob <= 1.0, 'The random_negative_prob ' \
f'should be in range [0,1], got {random_negative_prob} instead.'
self.magnitude = magnitude
self.prob = prob
self.random_negative_prob = random_negative_prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
magnitude = random_negative(self.magnitude, self.random_negative_prob)
for key in results.get('img_fields', ['img']):
img = results[key]
img_sharpened = mmcv.adjust_sharpness(img, factor=1 + magnitude)
results[key] = img_sharpened.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(magnitude={self.magnitude}, '
repr_str += f'prob={self.prob}, '
repr_str += f'random_negative_prob={self.random_negative_prob})'
return repr_str
@PIPELINES.register_module()
class Cutout(object):
"""Cutout images.
Args:
shape (int | float | tuple(int | float)): Expected cutout shape (h, w).
If given as a single value, the value will be used for
both h and w.
pad_val (int, Sequence[int]): Pixel pad_val value for constant fill.
If it is a sequence, it must have the same length with the image
channels. Defaults to 128.
prob (float): The probability for performing cutout therefore should
be in range [0, 1]. Defaults to 0.5.
"""
def __init__(self, shape, pad_val=128, prob=0.5):
if isinstance(shape, float):
shape = int(shape)
elif isinstance(shape, tuple):
shape = tuple(int(i) for i in shape)
elif not isinstance(shape, int):
raise TypeError(
'shape must be of '
f'type int, float or tuple, got {type(shape)} instead')
if isinstance(pad_val, int):
pad_val = tuple([pad_val] * 3)
elif isinstance(pad_val, Sequence):
assert len(pad_val) == 3, 'pad_val as a tuple must have 3 ' \
f'elements, got {len(pad_val)} instead.'
assert 0 <= prob <= 1.0, 'The prob should be in range [0,1], ' \
f'got {prob} instead.'
self.shape = shape
self.pad_val = tuple(pad_val)
self.prob = prob
def __call__(self, results):
if np.random.rand() > self.prob:
return results
for key in results.get('img_fields', ['img']):
img = results[key]
img_cutout = mmcv.cutout(img, self.shape, pad_val=self.pad_val)
results[key] = img_cutout.astype(img.dtype)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(shape={self.shape}, '
repr_str += f'pad_val={self.pad_val}, '
repr_str += f'prob={self.prob})'
return repr_str
| 37,110 | 39.338043 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/pipelines/formating.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from PIL import Image
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
:class:`Sequence`, :class:`int` and :class:`float`.
"""
if isinstance(data, torch.Tensor):
return data
elif isinstance(data, np.ndarray):
return torch.from_numpy(data)
elif isinstance(data, Sequence) and not mmcv.is_str(data):
return torch.tensor(data)
elif isinstance(data, int):
return torch.LongTensor([data])
elif isinstance(data, float):
return torch.FloatTensor([data])
else:
raise TypeError(
f'Type {type(data)} cannot be converted to tensor.'
'Supported types are: `numpy.ndarray`, `torch.Tensor`, '
'`Sequence`, `int` and `float`')
@PIPELINES.register_module()
class ToTensor(object):
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
for key in self.keys:
results[key] = to_tensor(results[key])
return results
def __repr__(self):
return self.__class__.__name__ + f'(keys={self.keys})'
@PIPELINES.register_module()
class ImageToTensor(object):
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
for key in self.keys:
img = results[key]
if len(img.shape) < 3:
img = np.expand_dims(img, -1)
results[key] = to_tensor(img.transpose(2, 0, 1))
return results
def __repr__(self):
return self.__class__.__name__ + f'(keys={self.keys})'
@PIPELINES.register_module()
class Transpose(object):
def __init__(self, keys, order):
self.keys = keys
self.order = order
def __call__(self, results):
for key in self.keys:
results[key] = results[key].transpose(self.order)
return results
def __repr__(self):
return self.__class__.__name__ + \
f'(keys={self.keys}, order={self.order})'
@PIPELINES.register_module()
class ToPIL(object):
def __init__(self):
pass
def __call__(self, results):
results['img'] = Image.fromarray(results['img'])
return results
@PIPELINES.register_module()
class ToNumpy(object):
def __init__(self):
pass
def __call__(self, results):
results['img'] = np.array(results['img'], dtype=np.float32)
return results
@PIPELINES.register_module()
class Collect(object):
"""Collect data from the loader relevant to the specific task.
This is usually the last stage of the data loader pipeline. Typically keys
is set to some subset of "img" and "gt_label".
Args:
keys (Sequence[str]): Keys of results to be collected in ``data``.
meta_keys (Sequence[str], optional): Meta keys to be converted to
``mmcv.DataContainer`` and collected in ``data[img_metas]``.
Default: ('filename', 'ori_shape', 'img_shape', 'flip',
'flip_direction', 'img_norm_cfg')
Returns:
dict: The result dict contains the following keys
- keys in ``self.keys``
- ``img_metas`` if avaliable
"""
def __init__(self,
keys,
meta_keys=('filename', 'ori_filename', 'ori_shape',
'img_shape', 'flip', 'flip_direction',
'img_norm_cfg')):
self.keys = keys
self.meta_keys = meta_keys
def __call__(self, results):
data = {}
img_meta = {}
for key in self.meta_keys:
if key in results:
img_meta[key] = results[key]
data['img_metas'] = DC(img_meta, cpu_only=True)
for key in self.keys:
data[key] = results[key]
return data
def __repr__(self):
return self.__class__.__name__ + \
f'(keys={self.keys}, meta_keys={self.meta_keys})'
@PIPELINES.register_module()
class WrapFieldsToLists(object):
"""Wrap fields of the data dictionary into lists for evaluation.
This class can be used as a last step of a test or validation
pipeline for single image evaluation or inference.
Example:
>>> test_pipeline = [
>>> dict(type='LoadImageFromFile'),
>>> dict(type='Normalize',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True),
>>> dict(type='ImageToTensor', keys=['img']),
>>> dict(type='Collect', keys=['img']),
>>> dict(type='WrapIntoLists')
>>> ]
"""
def __call__(self, results):
# Wrap dict fields into lists
for key, val in results.items():
results[key] = [val]
return results
def __repr__(self):
return f'{self.__class__.__name__}()'
| 5,129 | 27.342541 | 78 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/pipelines/__init__.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from .auto_augment import (AutoAugment, AutoContrast, Brightness,
ColorTransform, Contrast, Cutout, Equalize, Invert,
Posterize, RandAugment, Rotate, Sharpness, Shear,
Solarize, SolarizeAdd, Translate)
from .compose import Compose
from .formating import (Collect, ImageToTensor, ToNumpy, ToPIL, ToTensor,
Transpose, to_tensor)
from .loading import LoadImageFromFile
from .transforms import (CenterCrop, ColorJitter, Lighting, RandomCrop,
RandomErasing, RandomFlip, RandomGrayscale,
RandomResizedCrop, Resize)
__all__ = [
'Compose', 'to_tensor', 'ToTensor', 'ImageToTensor', 'ToPIL', 'ToNumpy',
'Transpose', 'Collect', 'LoadImageFromFile', 'Resize', 'CenterCrop',
'RandomFlip', 'Normalize', 'RandomCrop', 'RandomResizedCrop',
'RandomGrayscale', 'Shear', 'Translate', 'Rotate', 'Invert',
'ColorTransform', 'Solarize', 'Posterize', 'AutoContrast', 'Equalize',
'Contrast', 'Brightness', 'Sharpness', 'AutoAugment', 'SolarizeAdd',
'Cutout', 'RandAugment', 'Lighting', 'ColorJitter', 'RandomErasing'
]
| 1,228 | 52.434783 | 78 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/datasets/pipelines/transforms.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import inspect
import math
import random
from numbers import Number
from typing import Sequence
import mmcv
import numpy as np
from ..builder import PIPELINES
from .compose import Compose
try:
import albumentations
except ImportError:
albumentations = None
@PIPELINES.register_module()
class RandomCrop(object):
"""Crop the given Image at a random location.
Args:
size (sequence or int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made.
padding (int or sequence, optional): Optional padding on each border
of the image. If a sequence of length 4 is provided, it is used to
pad left, top, right, bottom borders respectively. If a sequence
of length 2 is provided, it is used to pad left/right, top/bottom
borders, respectively. Default: None, which means no padding.
pad_if_needed (boolean): It will pad the image if smaller than the
desired size to avoid raising an exception. Since cropping is done
after padding, the padding seems to be done at a random offset.
Default: False.
pad_val (Number | Sequence[Number]): Pixel pad_val value for constant
fill. If a tuple of length 3, it is used to pad_val R, G, B
channels respectively. Default: 0.
padding_mode (str): Type of padding. Defaults to "constant". Should
be one of the following:
- constant: Pads with a constant value, this value is specified \
with pad_val.
- edge: pads with the last value at the edge of the image.
- reflect: Pads with reflection of image without repeating the \
last value on the edge. For example, padding [1, 2, 3, 4] \
with 2 elements on both sides in reflect mode will result \
in [3, 2, 1, 2, 3, 4, 3, 2].
- symmetric: Pads with reflection of image repeating the last \
value on the edge. For example, padding [1, 2, 3, 4] with \
2 elements on both sides in symmetric mode will result in \
[2, 1, 1, 2, 3, 4, 4, 3].
"""
def __init__(self,
size,
padding=None,
pad_if_needed=False,
pad_val=0,
padding_mode='constant'):
if isinstance(size, (tuple, list)):
self.size = size
else:
self.size = (size, size)
# check padding mode
assert padding_mode in ['constant', 'edge', 'reflect', 'symmetric']
self.padding = padding
self.pad_if_needed = pad_if_needed
self.pad_val = pad_val
self.padding_mode = padding_mode
@staticmethod
def get_params(img, output_size):
"""Get parameters for ``crop`` for a random crop.
Args:
img (ndarray): Image to be cropped.
output_size (tuple): Expected output size of the crop.
Returns:
tuple: Params (xmin, ymin, target_height, target_width) to be
passed to ``crop`` for random crop.
"""
height = img.shape[0]
width = img.shape[1]
target_height, target_width = output_size
if width == target_width and height == target_height:
return 0, 0, height, width
ymin = random.randint(0, height - target_height)
xmin = random.randint(0, width - target_width)
return ymin, xmin, target_height, target_width
def __call__(self, results):
"""
Args:
img (ndarray): Image to be cropped.
"""
for key in results.get('img_fields', ['img']):
img = results[key]
if self.padding is not None:
img = mmcv.impad(
img, padding=self.padding, pad_val=self.pad_val)
# pad the height if needed
if self.pad_if_needed and img.shape[0] < self.size[0]:
img = mmcv.impad(
img,
padding=(0, self.size[0] - img.shape[0], 0,
self.size[0] - img.shape[0]),
pad_val=self.pad_val,
padding_mode=self.padding_mode)
# pad the width if needed
if self.pad_if_needed and img.shape[1] < self.size[1]:
img = mmcv.impad(
img,
padding=(self.size[1] - img.shape[1], 0,
self.size[1] - img.shape[1], 0),
pad_val=self.pad_val,
padding_mode=self.padding_mode)
ymin, xmin, height, width = self.get_params(img, self.size)
results[key] = mmcv.imcrop(
img,
np.array([
xmin,
ymin,
xmin + width - 1,
ymin + height - 1,
]))
return results
def __repr__(self):
return (self.__class__.__name__ +
f'(size={self.size}, padding={self.padding})')
@PIPELINES.register_module()
class RandomResizedCrop(object):
"""Crop the given image to random size and aspect ratio.
A crop of random size (default: of 0.08 to 1.0) of the original size and a
random aspect ratio (default: of 3/4 to 4/3) of the original aspect ratio
is made. This crop is finally resized to given size.
Args:
size (sequence | int): Desired output size of the crop. If size is an
int instead of sequence like (h, w), a square crop (size, size) is
made.
scale (tuple): Range of the random size of the cropped image compared
to the original image. Defaults to (0.08, 1.0).
ratio (tuple): Range of the random aspect ratio of the cropped image
compared to the original image. Defaults to (3. / 4., 4. / 3.).
max_attempts (int): Maxinum number of attempts before falling back to
Central Crop. Defaults to 10.
efficientnet_style (bool): Whether to use efficientnet style Random
ResizedCrop. Defaults to False.
min_covered (Number): Minimum ratio of the cropped area to the original
area. Only valid if efficientnet_style is true. Defaults to 0.1.
crop_padding (int): The crop padding parameter in efficientnet style
center crop. Only valid if efficientnet_style is true.
Defaults to 32.
interpolation (str): Interpolation method, accepted values are
'nearest', 'bilinear', 'bicubic', 'area', 'lanczos'. Defaults to
'bilinear'.
backend (str): The image resize backend type, accpeted values are
`cv2` and `pillow`. Defaults to `cv2`.
"""
def __init__(self,
size,
scale=(0.08, 1.0),
ratio=(3. / 4., 4. / 3.),
max_attempts=10,
efficientnet_style=False,
min_covered=0.1,
crop_padding=32,
interpolation='bilinear',
backend='cv2'):
if efficientnet_style:
assert isinstance(size, int)
self.size = (size, size)
assert crop_padding >= 0
else:
if isinstance(size, (tuple, list)):
self.size = size
else:
self.size = (size, size)
if (scale[0] > scale[1]) or (ratio[0] > ratio[1]):
raise ValueError('range should be of kind (min, max). '
f'But received scale {scale} and rato {ratio}.')
assert min_covered >= 0, 'min_covered should be no less than 0.'
assert isinstance(max_attempts, int) and max_attempts >= 0, \
'max_attempts mush be of typle int and no less than 0.'
assert interpolation in ('nearest', 'bilinear', 'bicubic', 'area',
'lanczos')
if backend not in ['cv2', 'pillow']:
raise ValueError(f'backend: {backend} is not supported for resize.'
'Supported backends are "cv2", "pillow"')
self.scale = scale
self.ratio = ratio
self.max_attempts = max_attempts
self.efficientnet_style = efficientnet_style
self.min_covered = min_covered
self.crop_padding = crop_padding
self.interpolation = interpolation
self.backend = backend
@staticmethod
def get_params(img, scale, ratio, max_attempts=10):
"""Get parameters for ``crop`` for a random sized crop.
Args:
img (ndarray): Image to be cropped.
scale (tuple): Range of the random size of the cropped image
compared to the original image size.
ratio (tuple): Range of the random aspect ratio of the cropped
image compared to the original image area.
max_attempts (int): Maxinum number of attempts before falling back
to central crop. Defaults to 10.
Returns:
tuple: Params (ymin, xmin, ymax, xmax) to be passed to `crop` for
a random sized crop.
"""
height = img.shape[0]
width = img.shape[1]
area = height * width
for _ in range(max_attempts):
target_area = random.uniform(*scale) * area
log_ratio = (math.log(ratio[0]), math.log(ratio[1]))
aspect_ratio = math.exp(random.uniform(*log_ratio))
target_width = int(round(math.sqrt(target_area * aspect_ratio)))
target_height = int(round(math.sqrt(target_area / aspect_ratio)))
if 0 < target_width <= width and 0 < target_height <= height:
ymin = random.randint(0, height - target_height)
xmin = random.randint(0, width - target_width)
ymax = ymin + target_height - 1
xmax = xmin + target_width - 1
return ymin, xmin, ymax, xmax
# Fallback to central crop
in_ratio = float(width) / float(height)
if in_ratio < min(ratio):
target_width = width
target_height = int(round(target_width / min(ratio)))
elif in_ratio > max(ratio):
target_height = height
target_width = int(round(target_height * max(ratio)))
else: # whole image
target_width = width
target_height = height
ymin = (height - target_height) // 2
xmin = (width - target_width) // 2
ymax = ymin + target_height - 1
xmax = xmin + target_width - 1
return ymin, xmin, ymax, xmax
# https://github.com/kakaobrain/fast-autoaugment/blob/master/FastAutoAugment/data.py # noqa
@staticmethod
def get_params_efficientnet_style(img,
size,
scale,
ratio,
max_attempts=10,
min_covered=0.1,
crop_padding=32):
"""Get parameters for ``crop`` for a random sized crop in efficientnet
style.
Args:
img (ndarray): Image to be cropped.
size (sequence): Desired output size of the crop.
scale (tuple): Range of the random size of the cropped image
compared to the original image size.
ratio (tuple): Range of the random aspect ratio of the cropped
image compared to the original image area.
max_attempts (int): Maxinum number of attempts before falling back
to central crop. Defaults to 10.
min_covered (Number): Minimum ratio of the cropped area to the
original area. Only valid if efficientnet_style is true.
Defaults to 0.1.
crop_padding (int): The crop padding parameter in efficientnet
style center crop. Defaults to 32.
Returns:
tuple: Params (ymin, xmin, ymax, xmax) to be passed to `crop` for
a random sized crop.
"""
height, width = img.shape[:2]
area = height * width
min_target_area = scale[0] * area
max_target_area = scale[1] * area
for _ in range(max_attempts):
aspect_ratio = random.uniform(*ratio)
min_target_height = int(
round(math.sqrt(min_target_area / aspect_ratio)))
max_target_height = int(
round(math.sqrt(max_target_area / aspect_ratio)))
if max_target_height * aspect_ratio > width:
max_target_height = int((width + 0.5 - 1e-7) / aspect_ratio)
if max_target_height * aspect_ratio > width:
max_target_height -= 1
max_target_height = min(max_target_height, height)
min_target_height = min(max_target_height, min_target_height)
# slightly differs from tf inplementation
target_height = int(
round(random.uniform(min_target_height, max_target_height)))
target_width = int(round(target_height * aspect_ratio))
target_area = target_height * target_width
# slight differs from tf. In tf, if target_area > max_target_area,
# area will be recalculated
if (target_area < min_target_area or target_area > max_target_area
or target_width > width or target_height > height
or target_area < min_covered * area):
continue
ymin = random.randint(0, height - target_height)
xmin = random.randint(0, width - target_width)
ymax = ymin + target_height - 1
xmax = xmin + target_width - 1
return ymin, xmin, ymax, xmax
# Fallback to central crop
img_short = min(height, width)
crop_size = size[0] / (size[0] + crop_padding) * img_short
ymin = max(0, int(round((height - crop_size) / 2.)))
xmin = max(0, int(round((width - crop_size) / 2.)))
ymax = min(height, ymin + crop_size) - 1
xmax = min(width, xmin + crop_size) - 1
return ymin, xmin, ymax, xmax
def __call__(self, results):
for key in results.get('img_fields', ['img']):
img = results[key]
if self.efficientnet_style:
get_params_func = self.get_params_efficientnet_style
get_params_args = dict(
img=img,
size=self.size,
scale=self.scale,
ratio=self.ratio,
max_attempts=self.max_attempts,
min_covered=self.min_covered,
crop_padding=self.crop_padding)
else:
get_params_func = self.get_params
get_params_args = dict(
img=img,
scale=self.scale,
ratio=self.ratio,
max_attempts=self.max_attempts)
ymin, xmin, ymax, xmax = get_params_func(**get_params_args)
img = mmcv.imcrop(img, bboxes=np.array([xmin, ymin, xmax, ymax]))
results[key] = mmcv.imresize(
img,
tuple(self.size[::-1]),
interpolation=self.interpolation,
backend=self.backend)
return results
def __repr__(self):
repr_str = self.__class__.__name__ + f'(size={self.size}'
repr_str += f', scale={tuple(round(s, 4) for s in self.scale)}'
repr_str += f', ratio={tuple(round(r, 4) for r in self.ratio)}'
repr_str += f', max_attempts={self.max_attempts}'
repr_str += f', efficientnet_style={self.efficientnet_style}'
repr_str += f', min_covered={self.min_covered}'
repr_str += f', crop_padding={self.crop_padding}'
repr_str += f', interpolation={self.interpolation}'
repr_str += f', backend={self.backend})'
return repr_str
@PIPELINES.register_module()
class RandomGrayscale(object):
"""Randomly convert image to grayscale with a probability of gray_prob.
Args:
gray_prob (float): Probability that image should be converted to
grayscale. Default: 0.1.
Returns:
ndarray: Image after randomly grayscale transform.
Notes:
- If input image is 1 channel: grayscale version is 1 channel.
- If input image is 3 channel: grayscale version is 3 channel
with r == g == b.
"""
def __init__(self, gray_prob=0.1):
self.gray_prob = gray_prob
def __call__(self, results):
"""
Args:
img (ndarray): Image to be converted to grayscale.
Returns:
ndarray: Randomly grayscaled image.
"""
for key in results.get('img_fields', ['img']):
img = results[key]
num_output_channels = img.shape[2]
if random.random() < self.gray_prob:
if num_output_channels > 1:
img = mmcv.rgb2gray(img)[:, :, None]
results[key] = np.dstack(
[img for _ in range(num_output_channels)])
return results
results[key] = img
return results
def __repr__(self):
return self.__class__.__name__ + f'(gray_prob={self.gray_prob})'
@PIPELINES.register_module()
class RandomFlip(object):
"""Flip the image randomly.
Flip the image randomly based on flip probaility and flip direction.
Args:
flip_prob (float): probability of the image being flipped. Default: 0.5
direction (str): The flipping direction. Options are
'horizontal' and 'vertical'. Default: 'horizontal'.
"""
def __init__(self, flip_prob=0.5, direction='horizontal'):
assert 0 <= flip_prob <= 1
assert direction in ['horizontal', 'vertical']
self.flip_prob = flip_prob
self.direction = direction
def __call__(self, results):
"""Call function to flip image.
Args:
results (dict): Result dict from loading pipeline.
Returns:
dict: Flipped results, 'flip', 'flip_direction' keys are added into
result dict.
"""
flip = True if np.random.rand() < self.flip_prob else False
results['flip'] = flip
results['flip_direction'] = self.direction
if results['flip']:
# flip image
for key in results.get('img_fields', ['img']):
results[key] = mmcv.imflip(
results[key], direction=results['flip_direction'])
return results
def __repr__(self):
return self.__class__.__name__ + f'(flip_prob={self.flip_prob})'
@PIPELINES.register_module()
class RandomErasing(object):
"""Randomly selects a rectangle region in an image and erase pixels.
Args:
erase_prob (float): Probability that image will be randomly erased.
Default: 0.5
min_area_ratio (float): Minimum erased area / input image area
Default: 0.02
max_area_ratio (float): Maximum erased area / input image area
Default: 0.4
aspect_range (sequence | float): Aspect ratio range of erased area.
if float, it will be converted to (aspect_ratio, 1/aspect_ratio)
Default: (3/10, 10/3)
mode (str): Fill method in erased area, can be:
- const (default): All pixels are assign with the same value.
- rand: each pixel is assigned with a random value in [0, 255]
fill_color (sequence | Number): Base color filled in erased area.
Defaults to (128, 128, 128).
fill_std (sequence | Number, optional): If set and ``mode`` is 'rand',
fill erased area with random color from normal distribution
(mean=fill_color, std=fill_std); If not set, fill erased area with
random color from uniform distribution (0~255). Defaults to None.
Note:
See `Random Erasing Data Augmentation
<https://arxiv.org/pdf/1708.04896.pdf>`_
This paper provided 4 modes: RE-R, RE-M, RE-0, RE-255, and use RE-M as
default. The config of these 4 modes are:
- RE-R: RandomErasing(mode='rand')
- RE-M: RandomErasing(mode='const', fill_color=(123.67, 116.3, 103.5))
- RE-0: RandomErasing(mode='const', fill_color=0)
- RE-255: RandomErasing(mode='const', fill_color=255)
"""
def __init__(self,
erase_prob=0.5,
min_area_ratio=0.02,
max_area_ratio=0.4,
aspect_range=(3 / 10, 10 / 3),
mode='const',
fill_color=(128, 128, 128),
fill_std=None):
assert isinstance(erase_prob, float) and 0. <= erase_prob <= 1.
assert isinstance(min_area_ratio, float) and 0. <= min_area_ratio <= 1.
assert isinstance(max_area_ratio, float) and 0. <= max_area_ratio <= 1.
assert min_area_ratio <= max_area_ratio, \
'min_area_ratio should be smaller than max_area_ratio'
if isinstance(aspect_range, float):
aspect_range = min(aspect_range, 1 / aspect_range)
aspect_range = (aspect_range, 1 / aspect_range)
assert isinstance(aspect_range, Sequence) and len(aspect_range) == 2 \
and all(isinstance(x, float) for x in aspect_range), \
'aspect_range should be a float or Sequence with two float.'
assert all(x > 0 for x in aspect_range), \
'aspect_range should be positive.'
assert aspect_range[0] <= aspect_range[1], \
'In aspect_range (min, max), min should be smaller than max.'
assert mode in ['const', 'rand']
if isinstance(fill_color, Number):
fill_color = [fill_color] * 3
assert isinstance(fill_color, Sequence) and len(fill_color) == 3 \
and all(isinstance(x, Number) for x in fill_color), \
'fill_color should be a float or Sequence with three int.'
if fill_std is not None:
if isinstance(fill_std, Number):
fill_std = [fill_std] * 3
assert isinstance(fill_std, Sequence) and len(fill_std) == 3 \
and all(isinstance(x, Number) for x in fill_std), \
'fill_std should be a float or Sequence with three int.'
self.erase_prob = erase_prob
self.min_area_ratio = min_area_ratio
self.max_area_ratio = max_area_ratio
self.aspect_range = aspect_range
self.mode = mode
self.fill_color = fill_color
self.fill_std = fill_std
def _fill_pixels(self, img, top, left, h, w):
if self.mode == 'const':
patch = np.empty((h, w, 3), dtype=np.uint8)
patch[:, :] = np.array(self.fill_color, dtype=np.uint8)
elif self.fill_std is None:
# Uniform distribution
patch = np.random.uniform(0, 256, (h, w, 3)).astype(np.uint8)
else:
# Normal distribution
patch = np.random.normal(self.fill_color, self.fill_std, (h, w, 3))
patch = np.clip(patch.astype(np.int32), 0, 255).astype(np.uint8)
img[top:top + h, left:left + w] = patch
return img
def __call__(self, results):
"""
Args:
results (dict): Results dict from pipeline
Returns:
dict: Results after the transformation.
"""
for key in results.get('img_fields', ['img']):
if np.random.rand() > self.erase_prob:
continue
img = results[key]
img_h, img_w = img.shape[:2]
# convert to log aspect to ensure equal probability of aspect ratio
log_aspect_range = np.log(
np.array(self.aspect_range, dtype=np.float32))
aspect_ratio = np.exp(np.random.uniform(*log_aspect_range))
area = img_h * img_w
area *= np.random.uniform(self.min_area_ratio, self.max_area_ratio)
h = min(int(round(np.sqrt(area * aspect_ratio))), img_h)
w = min(int(round(np.sqrt(area / aspect_ratio))), img_w)
top = np.random.randint(0, img_h - h) if img_h > h else 0
left = np.random.randint(0, img_w - w) if img_w > w else 0
img = self._fill_pixels(img, top, left, h, w)
results[key] = img
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(erase_prob={self.erase_prob}, '
repr_str += f'min_area_ratio={self.min_area_ratio}, '
repr_str += f'max_area_ratio={self.max_area_ratio}, '
repr_str += f'aspect_range={self.aspect_range}, '
repr_str += f'mode={self.mode}, '
repr_str += f'fill_color={self.fill_color}, '
repr_str += f'fill_std={self.fill_std})'
return repr_str
@PIPELINES.register_module()
class Resize(object):
"""Resize images.
Args:
size (int | tuple): Images scales for resizing (h, w).
When size is int, the default behavior is to resize an image
to (size, size). When size is tuple and the second value is -1,
the short edge of an image is resized to its first value.
For example, when size is 224, the image is resized to 224x224.
When size is (224, -1), the short side is resized to 224 and the
other side is computed based on the short side, maintaining the
aspect ratio.
interpolation (str): Interpolation method, accepted values are
"nearest", "bilinear", "bicubic", "area", "lanczos".
More details can be found in `mmcv.image.geometric`.
backend (str): The image resize backend type, accpeted values are
`cv2` and `pillow`. Default: `cv2`.
"""
def __init__(self, size, interpolation='bilinear', backend='cv2'):
assert isinstance(size, int) or (isinstance(size, tuple)
and len(size) == 2)
self.resize_w_short_side = False
if isinstance(size, int):
assert size > 0
size = (size, size)
else:
assert size[0] > 0 and (size[1] > 0 or size[1] == -1)
if size[1] == -1:
self.resize_w_short_side = True
assert interpolation in ('nearest', 'bilinear', 'bicubic', 'area',
'lanczos')
if backend not in ['cv2', 'pillow']:
raise ValueError(f'backend: {backend} is not supported for resize.'
'Supported backends are "cv2", "pillow"')
self.size = size
self.interpolation = interpolation
self.backend = backend
def _resize_img(self, results):
for key in results.get('img_fields', ['img']):
img = results[key]
ignore_resize = False
if self.resize_w_short_side:
h, w = img.shape[:2]
short_side = self.size[0]
if (w <= h and w == short_side) or (h <= w
and h == short_side):
ignore_resize = True
else:
if w < h:
width = short_side
height = int(short_side * h / w)
else:
height = short_side
width = int(short_side * w / h)
else:
height, width = self.size
if not ignore_resize:
img = mmcv.imresize(
img,
size=(width, height),
interpolation=self.interpolation,
return_scale=False,
backend=self.backend)
results[key] = img
results['img_shape'] = img.shape
def __call__(self, results):
self._resize_img(results)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(size={self.size}, '
repr_str += f'interpolation={self.interpolation})'
return repr_str
@PIPELINES.register_module()
class CenterCrop(object):
r"""Center crop the image.
Args:
crop_size (int | tuple): Expected size after cropping with the format
of (h, w).
efficientnet_style (bool): Whether to use efficientnet style center
crop. Defaults to False.
crop_padding (int): The crop padding parameter in efficientnet style
center crop. Only valid if efficientnet style is True. Defaults to
32.
interpolation (str): Interpolation method, accepted values are
'nearest', 'bilinear', 'bicubic', 'area', 'lanczos'. Only valid if
``efficientnet_style`` is True. Defaults to 'bilinear'.
backend (str): The image resize backend type, accpeted values are
`cv2` and `pillow`. Only valid if efficientnet style is True.
Defaults to `cv2`.
Notes:
- If the image is smaller than the crop size, return the original
image.
- If efficientnet_style is set to False, the pipeline would be a simple
center crop using the crop_size.
- If efficientnet_style is set to True, the pipeline will be to first
to perform the center crop with the ``crop_size_`` as:
.. math::
\text{crop\_size\_} = \frac{\text{crop\_size}}{\text{crop\_size} +
\text{crop\_padding}} \times \text{short\_edge}
And then the pipeline resizes the img to the input crop size.
"""
def __init__(self,
crop_size,
efficientnet_style=False,
crop_padding=32,
interpolation='bilinear',
backend='cv2'):
if efficientnet_style:
assert isinstance(crop_size, int)
assert crop_padding >= 0
assert interpolation in ('nearest', 'bilinear', 'bicubic', 'area',
'lanczos')
if backend not in ['cv2', 'pillow']:
raise ValueError(
f'backend: {backend} is not supported for '
'resize. Supported backends are "cv2", "pillow"')
else:
assert isinstance(crop_size, int) or (isinstance(crop_size, tuple)
and len(crop_size) == 2)
if isinstance(crop_size, int):
crop_size = (crop_size, crop_size)
assert crop_size[0] > 0 and crop_size[1] > 0
self.crop_size = crop_size
self.efficientnet_style = efficientnet_style
self.crop_padding = crop_padding
self.interpolation = interpolation
self.backend = backend
def __call__(self, results):
crop_height, crop_width = self.crop_size[0], self.crop_size[1]
for key in results.get('img_fields', ['img']):
img = results[key]
# img.shape has length 2 for grayscale, length 3 for color
img_height, img_width = img.shape[:2]
# https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/preprocessing.py#L118 # noqa
if self.efficientnet_style:
img_short = min(img_height, img_width)
crop_height = crop_height / (crop_height +
self.crop_padding) * img_short
crop_width = crop_width / (crop_width +
self.crop_padding) * img_short
y1 = max(0, int(round((img_height - crop_height) / 2.)))
x1 = max(0, int(round((img_width - crop_width) / 2.)))
y2 = min(img_height, y1 + crop_height) - 1
x2 = min(img_width, x1 + crop_width) - 1
# crop the image
img = mmcv.imcrop(img, bboxes=np.array([x1, y1, x2, y2]))
if self.efficientnet_style:
img = mmcv.imresize(
img,
tuple(self.crop_size[::-1]),
interpolation=self.interpolation,
backend=self.backend)
img_shape = img.shape
results[key] = img
results['img_shape'] = img_shape
return results
def __repr__(self):
repr_str = self.__class__.__name__ + f'(crop_size={self.crop_size}'
repr_str += f', efficientnet_style={self.efficientnet_style}'
repr_str += f', crop_padding={self.crop_padding}'
repr_str += f', interpolation={self.interpolation}'
repr_str += f', backend={self.backend})'
return repr_str
@PIPELINES.register_module()
class Normalize(object):
"""Normalize the image.
Args:
mean (sequence): Mean values of 3 channels.
std (sequence): Std values of 3 channels.
to_rgb (bool): Whether to convert the image from BGR to RGB,
default is true.
"""
def __init__(self, mean, std, to_rgb=True):
self.mean = np.array(mean, dtype=np.float32)
self.std = np.array(std, dtype=np.float32)
self.to_rgb = to_rgb
def __call__(self, results):
for key in results.get('img_fields', ['img']):
results[key] = mmcv.imnormalize(results[key], self.mean, self.std,
self.to_rgb)
results['img_norm_cfg'] = dict(
mean=self.mean, std=self.std, to_rgb=self.to_rgb)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(mean={list(self.mean)}, '
repr_str += f'std={list(self.std)}, '
repr_str += f'to_rgb={self.to_rgb})'
return repr_str
@PIPELINES.register_module()
class ColorJitter(object):
"""Randomly change the brightness, contrast and saturation of an image.
Args:
brightness (float): How much to jitter brightness.
brightness_factor is chosen uniformly from
[max(0, 1 - brightness), 1 + brightness].
contrast (float): How much to jitter contrast.
contrast_factor is chosen uniformly from
[max(0, 1 - contrast), 1 + contrast].
saturation (float): How much to jitter saturation.
saturation_factor is chosen uniformly from
[max(0, 1 - saturation), 1 + saturation].
"""
def __init__(self, brightness, contrast, saturation):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
def __call__(self, results):
brightness_factor = random.uniform(0, self.brightness)
contrast_factor = random.uniform(0, self.contrast)
saturation_factor = random.uniform(0, self.saturation)
color_jitter_transforms = [
dict(
type='Brightness',
magnitude=brightness_factor,
prob=1.,
random_negative_prob=0.5),
dict(
type='Contrast',
magnitude=contrast_factor,
prob=1.,
random_negative_prob=0.5),
dict(
type='ColorTransform',
magnitude=saturation_factor,
prob=1.,
random_negative_prob=0.5)
]
random.shuffle(color_jitter_transforms)
transform = Compose(color_jitter_transforms)
return transform(results)
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(brightness={self.brightness}, '
repr_str += f'contrast={self.contrast}, '
repr_str += f'saturation={self.saturation})'
return repr_str
@PIPELINES.register_module()
class Lighting(object):
"""Adjust images lighting using AlexNet-style PCA jitter.
Args:
eigval (list): the eigenvalue of the convariance matrix of pixel
values, respectively.
eigvec (list[list]): the eigenvector of the convariance matrix of pixel
values, respectively.
alphastd (float): The standard deviation for distribution of alpha.
Dafaults to 0.1
to_rgb (bool): Whether to convert img to rgb.
"""
def __init__(self, eigval, eigvec, alphastd=0.1, to_rgb=True):
assert isinstance(eigval, list), \
f'eigval must be of type list, got {type(eigval)} instead.'
assert isinstance(eigvec, list), \
f'eigvec must be of type list, got {type(eigvec)} instead.'
for vec in eigvec:
assert isinstance(vec, list) and len(vec) == len(eigvec[0]), \
'eigvec must contains lists with equal length.'
self.eigval = np.array(eigval)
self.eigvec = np.array(eigvec)
self.alphastd = alphastd
self.to_rgb = to_rgb
def __call__(self, results):
for key in results.get('img_fields', ['img']):
img = results[key]
results[key] = mmcv.adjust_lighting(
img,
self.eigval,
self.eigvec,
alphastd=self.alphastd,
to_rgb=self.to_rgb)
return results
def __repr__(self):
repr_str = self.__class__.__name__
repr_str += f'(eigval={self.eigval.tolist()}, '
repr_str += f'eigvec={self.eigvec.tolist()}, '
repr_str += f'alphastd={self.alphastd}, '
repr_str += f'to_rgb={self.to_rgb})'
return repr_str
@PIPELINES.register_module()
class Albu(object):
"""Albumentation augmentation.
Adds custom transformations from Albumentations library.
Please, visit `https://albumentations.readthedocs.io`
to get more information.
An example of ``transforms`` is as followed:
.. code-block::
[
dict(
type='ShiftScaleRotate',
shift_limit=0.0625,
scale_limit=0.0,
rotate_limit=0,
interpolation=1,
p=0.5),
dict(
type='RandomBrightnessContrast',
brightness_limit=[0.1, 0.3],
contrast_limit=[0.1, 0.3],
p=0.2),
dict(type='ChannelShuffle', p=0.1),
dict(
type='OneOf',
transforms=[
dict(type='Blur', blur_limit=3, p=1.0),
dict(type='MedianBlur', blur_limit=3, p=1.0)
],
p=0.1),
]
Args:
transforms (list[dict]): A list of albu transformations
keymap (dict): Contains {'input key':'albumentation-style key'}
"""
def __init__(self, transforms, keymap=None, update_pad_shape=False):
if albumentations is None:
raise RuntimeError('albumentations is not installed')
else:
from albumentations import Compose
self.transforms = transforms
self.filter_lost_elements = False
self.update_pad_shape = update_pad_shape
self.aug = Compose([self.albu_builder(t) for t in self.transforms])
if not keymap:
self.keymap_to_albu = {
'img': 'image',
}
else:
self.keymap_to_albu = keymap
self.keymap_back = {v: k for k, v in self.keymap_to_albu.items()}
def albu_builder(self, cfg):
"""Import a module from albumentations.
It inherits some of :func:`build_from_cfg` logic.
Args:
cfg (dict): Config dict. It should at least contain the key "type".
Returns:
obj: The constructed object.
"""
assert isinstance(cfg, dict) and 'type' in cfg
args = cfg.copy()
obj_type = args.pop('type')
if mmcv.is_str(obj_type):
if albumentations is None:
raise RuntimeError('albumentations is not installed')
obj_cls = getattr(albumentations, obj_type)
elif inspect.isclass(obj_type):
obj_cls = obj_type
else:
raise TypeError(
f'type must be a str or valid type, but got {type(obj_type)}')
if 'transforms' in args:
args['transforms'] = [
self.albu_builder(transform)
for transform in args['transforms']
]
return obj_cls(**args)
@staticmethod
def mapper(d, keymap):
"""Dictionary mapper.
Renames keys according to keymap provided.
Args:
d (dict): old dict
keymap (dict): {'old_key':'new_key'}
Returns:
dict: new dict.
"""
updated_dict = {}
for k, v in zip(d.keys(), d.values()):
new_k = keymap.get(k, k)
updated_dict[new_k] = d[k]
return updated_dict
def __call__(self, results):
# dict to albumentations format
results = self.mapper(results, self.keymap_to_albu)
results = self.aug(**results)
if 'gt_labels' in results:
if isinstance(results['gt_labels'], list):
results['gt_labels'] = np.array(results['gt_labels'])
results['gt_labels'] = results['gt_labels'].astype(np.int64)
# back to the original format
results = self.mapper(results, self.keymap_back)
# update final shape
if self.update_pad_shape:
results['pad_shape'] = results['img'].shape
return results
def __repr__(self):
repr_str = self.__class__.__name__ + f'(transforms={self.transforms})'
return repr_str
| 41,925 | 38.330206 | 117 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/utils/logger.py
|
# Copyright (c) OpenMMLab. All rights reserved.
import logging
from mmcv.utils import get_logger
def get_root_logger(log_file=None, log_level=logging.INFO):
return get_logger('mmcls', log_file, log_level)
| 212 | 22.666667 | 59 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/utils/collect_env.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from mmcv.utils import collect_env as collect_base_env
from mmcv.utils import get_git_hash
import mmcls
def collect_env():
"""Collect the information of the running environments."""
env_info = collect_base_env()
env_info['MMClassification'] = mmcls.__version__ + '+' + get_git_hash()[:7]
return env_info
if __name__ == '__main__':
for name, val in collect_env().items():
print(f'{name}: {val}')
| 476 | 25.5 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/mmcls/utils/__init__.py
|
# Copyright (c) OpenMMLab. All rights reserved.
from .collect_env import collect_env
from .logger import get_root_logger
__all__ = ['collect_env', 'get_root_logger']
| 167 | 27 | 47 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/simplecnn64_1x128_dsprite.py
|
_base_ = [
'../_base_/datasets/dsprite.py',
'../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999), weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[10, 15])
runner = dict(type='EpochBasedRunner', max_epochs=20)
model = dict(
type='ImageClassifier',
backbone=dict(
type='SimpleConv64',
latent_dim=10,
num_channels=1,
image_size=64),
head=dict(
type='MultiTaskLinearClsHead',
num_classes=[3, 6, 40, 32, 32],
in_channels=10,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
))
checkpoint_config = dict(interval=5)
| 722 | 25.777778 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/resnet18_vib_1x128_dsprite.py
|
_base_ = [
'../_base_/models/resnet18_vib_dsprite.py',
'../_base_/datasets/dsprite.py',
'../_base_/schedules/dsprite_bs128.py',
'../_base_/default_runtime.py'
]
checkpoint_config = dict(interval=5)
| 214 | 29.714286 | 47 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/simplecnn64_simplecnn64_1x128_dsprite.py
|
_base_ = [
'../_base_/datasets/dsprite.py',
'../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999), weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[10, 15])
runner = dict(type='EpochBasedRunner', max_epochs=20)
# model settings
model = dict(
type='KFTaskParallelImageClassifier',
kd_loss=dict(type='Logits'),
train_cfg=dict(lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=1.0,
teacher_checkpoint='/home/yangxingyi/NeuralFactor/NeuralFactor/work_dirs/resnet18_b128x1_cifar10/latest.pth',
feat_channels=dict(student=[64, 128, 256, 512],
teacher=[64, 128, 256, 512]),
infor_loss='l2'
),
backbone=dict(
num_task=5,
student=dict(
CKN=dict(type='SimpleConv64',
latent_dim=10,
num_channels=1,
image_size=64),
TSN=dict(type='SimpleGaussianConv64',
atent_dim=10,
num_channels=1,
image_size=64)
),
teacher=dict(type='SimpleConv64',
latent_dim=10,
num_channels=1,
image_size=64)
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='MultiTaskLinearClsHead',
num_classes=[3, 6, 40, 32, 32],
in_channels=10,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
),
task=dict(
type='MutiTaskClsIMBLinearClsHead',
num_classes=[3, 6, 40, 32, 32],
in_channels=10,
loss=dict(type='CrossEntropyLoss',
use_sigmoid=True,
loss_weight=1.0),
),
teacher=dict(
type='MultiTaskLinearClsHead',
num_classes=[3, 6, 40, 32, 32],
in_channels=10,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
)
)
)
checkpoint_config = dict(interval=5)
| 2,356 | 31.736111 | 128 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/resnet18_1x128_shape3d.py
|
_base_ = [
'../_base_/models/resnet18_shape3d.py',
'../_base_/datasets/shape3d.py',
'../_base_/schedules/shape3d_bs128.py',
'../_base_/default_runtime.py'
]
checkpoint_config = dict(interval=5)
| 210 | 29.142857 | 44 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/resnet18_vib_1x128_shape3d.py
|
_base_ = [
'../_base_/models/resnet18_vib_shape3d.py',
'../_base_/datasets/shape3d.py',
'../_base_/schedules/shape3d_bs128.py',
'../_base_/default_runtime.py'
]
checkpoint_config = dict(interval=5)
| 214 | 29.714286 | 47 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/resnet18_1x128_dsprite.py
|
_base_ = [
'../_base_/models/resnet18_dsprite.py',
'../_base_/datasets/dsprite.py',
'../_base_/schedules/dsprite_bs128.py',
'../_base_/default_runtime.py'
]
checkpoint_config = dict(interval=5)
| 210 | 29.142857 | 44 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/multi_task/simplecnn64_1x128_shape3d.py
|
_base_ = [
'../_base_/datasets/shape3d.py',
'../_base_/default_runtime.py'
]
# optimizer
optimizer = dict(type='Adam', lr=1e-4, betas=(0.9, 0.999), weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[3])
runner = dict(type='EpochBasedRunner', max_epochs=5)
model = dict(
type='ImageClassifier',
backbone=dict(
type='SimpleConv64',
latent_dim=10,
num_channels=3,
image_size=64),
head=dict(
type='MultiTaskLinearClsHead',
num_classes=[10, 10, 10, 8, 4, 15],
in_channels=10,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
)
)
checkpoint_config = dict(interval=5)
| 721 | 24.785714 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/default_runtime.py
|
# checkpoint saving
checkpoint_config = dict(interval=20)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
# dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
| 342 | 19.176471 | 44 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/mobilenet_v2_1x.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(type='MobileNetV2', widen_factor=1.0),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1280,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
| 346 | 25.692308 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/resnet18_shape3d.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet_CIFAR',
depth=18,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='MultiTaskLinearClsHead',
num_classes=[10,10,10,8,4,15],
in_channels=512,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
))
| 430 | 24.352941 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/wide-resnet28-10.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 10,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=640,
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=10,
in_channels=640,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
| 568 | 24.863636 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/resnet18_cifar.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet_CIFAR',
depth=18,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=10,
in_channels=512,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
))
| 406 | 22.941176 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/resnet18.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet',
depth=18,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
| 423 | 22.555556 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/wide-resnet28-2.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=128,
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
| 567 | 24.818182 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/resnet50.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=2048,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
| 424 | 22.611111 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/resnet18_dsprite.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet_CIFAR',
in_channels=1,
depth=18,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='MultiTaskLinearClsHead',
num_classes=[3,6,40,32,32],
in_channels=512,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
))
| 450 | 24.055556 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/models/shufflenet_v2_1x.py
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(type='ShuffleNetV2', widen_factor=1.0),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1024,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
))
| 347 | 25.769231 | 60 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/dsprite_bs128.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[10,15])
runner = dict(type='EpochBasedRunner', max_epochs=20)
| 242 | 33.714286 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/shape3d_bs128.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[3])
runner = dict(type='EpochBasedRunner', max_epochs=5)
| 237 | 33 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs256_coslr_300e.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='CosineAnnealing', min_lr=0)
runner = dict(type='EpochBasedRunner', max_epochs=300)
| 250 | 34.857143 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs1024_adamw_swin.py
|
paramwise_cfg = dict(
norm_decay_mult=0.0,
bias_decay_mult=0.0,
custom_keys={
'.absolute_pos_embed': dict(decay_mult=0.0),
'.relative_position_bias_table': dict(decay_mult=0.0)
})
# for batch in each gpu is 128, 8 gpu
# lr = 5e-4 * 128 * 8 / 512 = 0.001
optimizer = dict(
type='AdamW',
lr=5e-4 * 128 * 8 / 512,
weight_decay=0.05,
eps=1e-8,
betas=(0.9, 0.999),
paramwise_cfg=paramwise_cfg)
optimizer_config = dict(grad_clip=dict(max_norm=5.0))
# learning policy
lr_config = dict(
policy='CosineAnnealing',
by_epoch=False,
min_lr_ratio=1e-2,
warmup='linear',
warmup_ratio=1e-3,
warmup_iters=20 * 1252,
warmup_by_epoch=False)
runner = dict(type='EpochBasedRunner', max_epochs=300)
| 765 | 23.709677 | 61 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs2048_coslr.py
|
# optimizer
optimizer = dict(
type='SGD', lr=0.8, momentum=0.9, weight_decay=0.0001, nesterov=True)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_iters=2500,
warmup_ratio=0.25)
runner = dict(type='EpochBasedRunner', max_epochs=100)
| 346 | 25.692308 | 73 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs1024_coslr.py
|
# optimizer
optimizer = dict(
type='SGD', lr=0.5, momentum=0.9, weight_decay=0.0001, nesterov=True)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_iters=2500,
warmup_ratio=0.25)
runner = dict(type='EpochBasedRunner', max_epochs=150)
| 346 | 25.692308 | 73 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs256_coslr.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='CosineAnnealing', min_lr=0)
runner = dict(type='EpochBasedRunner', max_epochs=150)
| 250 | 34.857143 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/cifar10_bs128.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
| 246 | 34.285714 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs256_epochstep.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.045, momentum=0.9, weight_decay=0.00004)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', gamma=0.98, step=1)
runner = dict(type='EpochBasedRunner', max_epochs=300)
| 252 | 35.142857 | 74 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs256_coslr_mobilenetv2.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.05, momentum=0.9, weight_decay=0.00004)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='CosineAnnealing', min_lr=0)
runner = dict(type='EpochBasedRunner', max_epochs=200)
| 252 | 35.142857 | 73 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs1024_linearlr_bn_nowd.py
|
# optimizer
optimizer = dict(
type='SGD',
lr=0.5,
momentum=0.9,
weight_decay=0.00004,
paramwise_cfg=dict(norm_decay_mult=0))
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='poly',
min_lr=0,
by_epoch=False,
warmup='constant',
warmup_iters=5000,
)
runner = dict(type='EpochBasedRunner', max_epochs=300)
| 377 | 20 | 54 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs256.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[30, 60, 90])
runner = dict(type='EpochBasedRunner', max_epochs=100)
| 248 | 34.571429 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs2048_AdamW.py
|
# optimizer
# In ClassyVision, the lr is set to 0.003 for bs4096.
# In this implementation(bs2048), lr = 0.003 / 4096 * (32bs * 64gpus) = 0.0015
optimizer = dict(type='AdamW', lr=0.0015, weight_decay=0.3)
optimizer_config = dict(grad_clip=dict(max_norm=1.0))
# specific to vit pretrain
paramwise_cfg = dict(
custom_keys={
'.backbone.cls_token': dict(decay_mult=0.0),
'.backbone.pos_embed': dict(decay_mult=0.0)
})
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_iters=10000,
warmup_ratio=1e-4)
runner = dict(type='EpochBasedRunner', max_epochs=300)
| 642 | 29.619048 | 78 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs256_140e.py
|
# optimizer
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[40, 80, 120])
runner = dict(type='EpochBasedRunner', max_epochs=140)
| 249 | 34.714286 | 71 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs4096_AdamW.py
|
# optimizer
optimizer = dict(type='AdamW', lr=0.003, weight_decay=0.3)
optimizer_config = dict(grad_clip=dict(max_norm=1.0))
# specific to vit pretrain
paramwise_cfg = dict(
custom_keys={
'.backbone.cls_token': dict(decay_mult=0.0),
'.backbone.pos_embed': dict(decay_mult=0.0)
})
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_iters=10000,
warmup_ratio=1e-4)
runner = dict(type='EpochBasedRunner', max_epochs=300)
| 508 | 25.789474 | 58 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/schedules/imagenet_bs2048.py
|
# optimizer
optimizer = dict(
type='SGD', lr=0.8, momentum=0.9, weight_decay=0.0001, nesterov=True)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=2500,
warmup_ratio=0.25,
step=[30, 60, 90])
runner = dict(type='EpochBasedRunner', max_epochs=100)
| 344 | 25.538462 | 73 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/imagenet_bs256_randaug.py
|
# dataset settings
_base_ = ['./pipelines/rand_aug.py']
dataset_type = 'ImageNet'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(
type='RandAugment',
policies={{_base_.rand_increasing_policies}},
num_policies=2,
total_level=10,
magnitude_level=7,
magnitude_std=0.5,
hparams=dict(
pad_val=[round(x) for x in img_norm_cfg['mean'][::-1]],
interpolation='bicubic')),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(256, -1)),
dict(type='CenterCrop', crop_size=224),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=256,
workers_per_gpu=4,
train=dict(
type=dataset_type,
data_prefix='data/imagenet/train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file=None,
pipeline=test_pipeline),
test=dict(
# replace `data/val` with `data/test` for standard test
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file=None,
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='accuracy')
| 1,703 | 31.769231 | 77 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/imagenet_bs64.py
|
# dataset settings
dataset_type = 'ImageNet'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(256, -1)),
dict(type='CenterCrop', crop_size=224),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=64,
workers_per_gpu=4,
train=dict(
type=dataset_type,
data_prefix='data/imagenet/train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file='data/imagenet/meta/val.txt',
pipeline=test_pipeline),
test=dict(
# replace `data/val` with `data/test` for standard test
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file='data/imagenet/meta/val.txt',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='accuracy')
| 1,389 | 33.75 | 77 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/cifar10_bs128_2task.py
|
# dataset settings
dataset_type = 'CIFAR10_2Task'
img_norm_cfg = dict(
mean=[125.307, 122.961, 113.8575],
std=[51.5865, 50.847, 51.255],
to_rgb=False)
train_pipeline = [
dict(type='RandomCrop', size=32, padding=4),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=128,
workers_per_gpu=2,
train=dict(
type=dataset_type, data_prefix='data/cifar10',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/cifar10',
pipeline=test_pipeline,
test_mode=True),
test=dict(
type=dataset_type,
data_prefix='data/cifar10',
pipeline=test_pipeline,
test_mode=True))
| 1,072 | 28.805556 | 67 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/cifar10_bs128.py
|
# dataset settings
_base_ = ['./pipelines/rand_aug_cifar.py']
dataset_type = 'CIFAR10'
img_norm_cfg = dict(
mean=[125.307, 122.961, 113.8575],
std=[51.5865, 50.847, 51.255],
to_rgb=False)
train_pipeline = [
dict(type='RandomCrop', size=32, padding=4),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(type='RandAugment',
policies={{_base_.rand_increasing_policies}},
num_policies=2,
total_level=10,
magnitude_level=9,
magnitude_std=0.5),
dict(type='Albu',
transforms=[
dict(type='Blur', blur_limit=3, p=0.1),
dict(type='GaussNoise', var_limit=10.0, p=0.1)
]),
dict(
type='RandomErasing',
erase_prob=0.2,
mode='rand',
min_area_ratio=0.02,
max_area_ratio=1 / 3,
fill_color=img_norm_cfg['mean'][::-1],
fill_std=img_norm_cfg['std'][::-1]),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=128,
workers_per_gpu=2,
train=dict(
type=dataset_type, data_prefix='data/cifar10',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/cifar10',
pipeline=test_pipeline,
test_mode=True),
test=dict(
type=dataset_type,
data_prefix='data/cifar10',
pipeline=test_pipeline,
test_mode=True))
| 1,710 | 28 | 67 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/imagenet_bs64_randaug.py
|
# dataset settings
_base_ = ['./pipelines/rand_aug.py']
dataset_type = 'ImageNet'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(
type='RandAugment',
policies={{_base_.rand_increasing_policies}},
num_policies=2,
total_level=10,
magnitude_level=7,
magnitude_std=0.5,
hparams=dict(
pad_val=[round(x) for x in img_norm_cfg['mean'][::-1]],
interpolation='bicubic')),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(256, -1)),
dict(type='CenterCrop', crop_size=224),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=64,
workers_per_gpu=4,
train=dict(
type=dataset_type,
data_prefix='data/imagenet/train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file=None,
pipeline=test_pipeline),
test=dict(
# replace `data/val` with `data/test` for standard test
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file=None,
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='accuracy')
| 1,702 | 31.75 | 77 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/dsprite.py
|
# dataset settings
dataset_type = 'dSprites'
multi_task = True
img_norm_cfg = dict(
mean=[0.5],
std=[0.5],
to_rgb=False)
train_pipeline = [
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=128,
workers_per_gpu=4,
train=dict(
type=dataset_type, data_prefix='data/dsprite',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/dsprite',
pipeline=test_pipeline,
test_mode=True),
test=dict(
type=dataset_type,
data_prefix='data/dsprite',
pipeline=test_pipeline,
test_mode=True))
| 925 | 25.457143 | 54 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/imagenet_bs32_randaug.py
|
# dataset settings
_base_ = ['./pipelines/rand_aug.py']
dataset_type = 'ImageNet'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(
type='RandAugment',
policies={{_base_.rand_increasing_policies}},
num_policies=2,
total_level=10,
magnitude_level=7,
magnitude_std=0.5,
hparams=dict(
pad_val=[round(x) for x in img_norm_cfg['mean'][::-1]],
interpolation='bicubic')),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(256, -1)),
dict(type='CenterCrop', crop_size=224),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=32,
workers_per_gpu=4,
train=dict(
type=dataset_type,
data_prefix='data/imagenet/train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file=None,
pipeline=test_pipeline),
test=dict(
# replace `data/val` with `data/test` for standard test
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file=None,
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='accuracy')
| 1,702 | 31.75 | 77 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/imagenet_bs256.py
|
# dataset settings
dataset_type = 'ImageNet'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(256, -1)),
dict(type='CenterCrop', crop_size=224),
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=256,
workers_per_gpu=4,
train=dict(
type=dataset_type,
data_prefix='data/imagenet/train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file='data/imagenet/meta/val.txt',
pipeline=test_pipeline),
test=dict(
# replace `data/val` with `data/test` for standard test
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file='data/imagenet/meta/val.txt',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='accuracy')
| 1,390 | 33.775 | 77 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/shape3d.py
|
# dataset settings
dataset_type = 'Shape3D'
multi_task = True
img_norm_cfg = dict(
mean=[127.0, 127.0, 127.0],
std=[127.0, 127.0, 127.0],
to_rgb=False)
train_pipeline = [
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='Normalize', **img_norm_cfg),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=256,
workers_per_gpu=2,
train=dict(
type=dataset_type, data_prefix='data/shape3d',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/shape3d',
pipeline=test_pipeline,
test_mode=True),
test=dict(
type=dataset_type,
data_prefix='data/shape3d',
pipeline=test_pipeline,
test_mode=True))
| 956 | 26.342857 | 54 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/pipelines/rand_aug.py
|
# Refers to `_RAND_INCREASING_TRANSFORMS` in pytorch-image-models
rand_increasing_policies = [
dict(type='AutoContrast'),
dict(type='Equalize'),
dict(type='Invert'),
dict(type='Rotate', magnitude_key='angle', magnitude_range=(0, 30)),
dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 0)),
dict(type='Solarize', magnitude_key='thr', magnitude_range=(256, 0)),
dict(
type='SolarizeAdd',
magnitude_key='magnitude',
magnitude_range=(0, 110)),
dict(
type='ColorTransform',
magnitude_key='magnitude',
magnitude_range=(0, 0.9)),
dict(type='Contrast', magnitude_key='magnitude', magnitude_range=(0, 0.9)),
dict(
type='Brightness', magnitude_key='magnitude',
magnitude_range=(0, 0.9)),
dict(
type='Sharpness', magnitude_key='magnitude', magnitude_range=(0, 0.9)),
dict(
type='Shear',
magnitude_key='magnitude',
magnitude_range=(0, 0.3),
direction='horizontal'),
dict(
type='Shear',
magnitude_key='magnitude',
magnitude_range=(0, 0.3),
direction='vertical'),
dict(
type='Translate',
magnitude_key='magnitude',
magnitude_range=(0, 0.45),
direction='horizontal'),
dict(
type='Translate',
magnitude_key='magnitude',
magnitude_range=(0, 0.45),
direction='vertical')
]
| 1,429 | 32.255814 | 79 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/_base_/datasets/pipelines/rand_aug_cifar.py
|
img_norm_cfg = dict(
mean=[125.307, 122.961, 113.8575],
std=[51.5865, 50.847, 51.255],
to_rgb=False)
rand_increasing_policies = [
dict(type='AutoContrast'),
dict(type='Brightness', magnitude_key='magnitude',
magnitude_range=(0.05, 0.95)),
dict(type='ColorTransform', magnitude_key='magnitude',
magnitude_range=(0.05, 0.95)),
dict(type='Contrast', magnitude_key='magnitude',
magnitude_range=(0.05, 0.95)),
dict(type='Equalize'),
dict(type='Invert'),
dict(type='Sharpness', magnitude_key='magnitude',
magnitude_range=(0.05, 0.95)),
dict(type='Posterize', magnitude_key='bits', magnitude_range=(4, 8)),
dict(type='Solarize', magnitude_key='thr', magnitude_range=(0, 256)),
dict(type='Rotate', interpolation='bicubic', magnitude_key='angle',
pad_val=tuple([int(x) for x in img_norm_cfg['mean']]),
magnitude_range=(-30, 30)),
dict(
type='Shear',
interpolation='bicubic',
magnitude_key='magnitude',
magnitude_range=(-0.3, 0.3),
pad_val=tuple([int(x) for x in img_norm_cfg['mean']]),
direction='horizontal'),
dict(
type='Shear',
interpolation='bicubic',
magnitude_key='magnitude',
magnitude_range=(-0.3, 0.3),
pad_val=tuple([int(x) for x in img_norm_cfg['mean']]),
direction='vertical'),
dict(
type='Translate',
interpolation='bicubic',
magnitude_key='magnitude',
magnitude_range=(-0.3, 0.3),
pad_val=tuple([int(x) for x in img_norm_cfg['mean']]),
direction='horizontal'),
dict(
type='Translate',
interpolation='bicubic',
magnitude_key='magnitude',
magnitude_range=(-0.3, 0.3),
pad_val=tuple([int(x) for x in img_norm_cfg['mean']]),
direction='vertical')
]
| 1,863 | 36.28 | 73 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kf/wideresnet28-2_mobilenetv2_b128x1_cifar10_softtar_kf.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# 93.61
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=1.0,
teacher_checkpoint=None, # Input your teacher checkpoint
feat_channels=dict(student=[160, 320, 1280],
teacher=[32, 64, 128]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(type='MobileNetV2_CIFAR',
out_indices=(5, 6, 7),
widen_factor=1.0),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2_CIFAR',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=1280)
),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(0, 1, 2),
out_channel=128,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=1280,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=10,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=10,
in_channels=1280,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=10,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
evaluation = dict(interval=5)
checkpoint_config = dict(max_keep_ckpts=1)
| 3,043 | 26.423423 | 65 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kf/wideresnet28-2_wideresnet28-2_b128x1_cifar10_softtar_kf.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# 93.58
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=1.0,
teacher_checkpoint=None, # Input your teacher checkpoint
feat_channels=dict(student=[32, 64, 128],
teacher=[32, 64, 128]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(0, 1, 2),
out_channel=128,
style='pytorch'),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2_CIFAR',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=128)
),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(0, 1, 2),
out_channel=128,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=10,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=10,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
evaluation = dict(interval=5)
checkpoint_config = dict(max_keep_ckpts=1)
| 3,275 | 26.529412 | 65 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kf/wideresnet28-2_resnet18_b128x1_cifar10_softtar_kf.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=1.0,
teacher_checkpoint=None, # Input your teacher checkpoint
feat_channels=dict(student=[128, 256, 512],
teacher=[32, 64, 128]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(type='ResNet_CIFAR',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2_CIFAR',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=512)
),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(0, 1, 2),
out_channel=128,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=512,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=10,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=10,
in_channels=512,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=10,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
evaluation = dict(interval=5)
checkpoint_config = dict(max_keep_ckpts=1)
| 3,091 | 26.607143 | 65 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/imagenet-kd/resnet50_resnet18_b32x8_imagenet_softtar_kd.py
|
_base_ = [
'../_base_/datasets/imagenet_bs32_randaug.py',
'../_base_/schedules/imagenet_bs256_coslr.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
fp16 = dict(loss_scale=512.)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
augments=[
dict(type='BatchMixup', alpha=0.1,
num_classes=1000, prob=0.5)
],
lambda_kd=0.1,
teacher_checkpoint=None, # Input your teacher checkpoint
),
backbone=dict(
student=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
teacher=dict(type='ResNet',
depth=50,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=2048,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
checkpoint_config = dict(max_keep_ckpts=1)
| 1,872 | 25.380282 | 64 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/imagenet-kd/resnet18_resnet18_b32x8_imagenet_softtar_kd.py
|
_base_ = [
'../_base_/datasets/imagenet_bs32_randaug.py',
'../_base_/schedules/imagenet_bs256_coslr.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
fp16 = dict(loss_scale=512.)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
augments=[
dict(type='BatchMixup', alpha=0.1,
num_classes=1000, prob=0.5)
],
lambda_kd=0.1,
teacher_checkpoint=None, # Input your teacher checkpoint
),
backbone=dict(
student=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
teacher=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
checkpoint_config = dict(max_keep_ckpts=1)
| 1,871 | 25.366197 | 64 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kd/wideresnet28-2_resnet18_b128x1_cifar10.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(lambda_kd=0.1,
teacher_checkpoint=None), # Input your teacher checkpoint
backbone=dict(
student=dict(
type='ResNet_CIFAR',
depth=18,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=128,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=512,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
| 1,992 | 24.883117 | 76 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kd/wideresnet28-2_wideresnet28-2_b128x1_cifar10.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(lambda_kd=0.1,
teacher_checkpoint=None), # Input your teacher checkpoint
backbone=dict(
student=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=128,
style='pytorch'),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=128,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
| 2,153 | 25.268293 | 76 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kd/wideresnet28-10_wideresnet28-2_b128x1_cifar10.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(lambda_kd=0.1,
teacher_checkpoint=None), # Input your teacher checkpoint
backbone=dict(
# return_tuple=False,
student=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=128,
style='pytorch'),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 10,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=640,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=640,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
| 2,184 | 25.325301 | 76 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kd/wideresnet28-10_mobilenetv2_b128x1_cifar10.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(lambda_kd=0.1,
teacher_checkpoint=None), # Input your teacher checkpoint
backbone=dict(
# return_tuple=False,
student=dict(type='MobileNetV2_CIFAR',
out_indices=(7, ),
widen_factor=1.0),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 10,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=640,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=1280,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=640,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
| 1,987 | 25.506667 | 76 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kd/wideresnet28-2_mobilenetv2_b128x1_cifar10.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(lambda_kd=0.1,
teacher_checkpoint=None), # Input your teacher checkpoint
backbone=dict(
# return_tuple=False,
student=dict(type='MobileNetV2_CIFAR',
out_indices=(7, ),
widen_factor=1.0),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 2,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=128,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=1280,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=128,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
| 1,986 | 25.493333 | 76 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/cifar10-kd/wideresnet28-10_resnet18_b128x1_cifar10.py
|
_base_ = [
'../_base_/datasets/cifar10_bs128.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
# optimizer
optimizer = dict(type='SGD',
lr=0.1, momentum=0.9, weight_decay=0.0001)
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(policy='step', step=[100, 150])
runner = dict(type='EpochBasedRunner', max_epochs=200)
# model settings
model = dict(
type='KDImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(lambda_kd=0.1,
teacher_checkpoint=None), # Input your teacher checkpoint
backbone=dict(
# return_tuple=False,
student=dict(
type='ResNet_CIFAR',
depth=18,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
teacher=dict(
type='WideResNet_CIFAR',
depth=28,
stem_channels=16,
base_channels=16 * 10,
num_stages=3,
strides=(1, 2, 2),
dilations=(1, 1, 1),
out_indices=(2, ),
out_channel=640,
style='pytorch')
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=10,
in_channels=512,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
),
teacher=dict(
type='LinearClsHead',
num_classes=10,
in_channels=640,
loss=dict(type='CrossEntropyLoss', loss_weight=1.0),
topk=(1, 5),
)
))
| 2,023 | 24.948718 | 76 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/imagenet-kf/resnet18_resnet18_b32x8_imagenet_softtar_kf.py
|
_base_ = [
'../_base_/datasets/imagenet_bs32_randaug.py',
'../_base_/schedules/imagenet_bs256_coslr.py'
]
# checkpoint saving
checkpoint_config = dict(interval=10)
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
fp16 = dict(loss_scale=512.)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
augments=[
dict(type='BatchMixup', alpha=0.1,
num_classes=1000, prob=0.5)
],
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=0.1,
teacher_checkpoint='/home/yangxingyi/.cache/torch/checkpoints/resnet18-5c106cde_converted.pth',
feat_channels=dict(student=[128, 256, 512],
teacher=[128, 256, 512]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=512)
),
teacher=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
checkpoint_config = dict(max_keep_ckpts=1)
| 2,876 | 27.205882 | 103 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/imagenet-kf/resnet18_mbnv2_b32x8_imagenet_softtar_kf.py
|
_base_ = [
'../_base_/datasets/imagenet_bs32_randaug.py',
'../_base_/schedules/imagenet_bs256_coslr_mobilenetv2.py'
]
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
fp16 = dict(loss_scale=512.)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=2.0),
train_cfg=dict(
augments=[
dict(type='BatchMixup', alpha=0.1, num_classes=1000, prob=0.5)
],
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=0.1,
teacher_checkpoint= '/home/yangxingyi/.cache/torch/checkpoints/resnet18-5c106cde_converted.pth', # Input your teacher checkpoint
feat_channels=dict(student=[160, 320, 1280],
teacher=[128, 256, 512]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(type='MobileNetV2',
out_indices=(5, 6, 7),
widen_factor=1.0),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=1280)
),
teacher=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1280,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1280,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
checkpoint_config = dict(interval=10, max_keep_ckpts=1)
| 2,802 | 27.896907 | 136 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/imagenet-kf/resnet18_mbnv2_b32x8_imagenet_softtar_kf_tmp.py
|
_base_ = [
'../_base_/datasets/imagenet_bs32_randaug.py',
'../_base_/schedules/imagenet_bs256_coslr_mobilenetv2.py'
]
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
fp16 = dict(loss_scale=512.)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=2.0),
train_cfg=dict(
augments=[
dict(type='BatchMixup', alpha=0.1, num_classes=1000, prob=0.5)
],
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=0.1,
teacher_checkpoint= '/home/yangxingyi/.cache/torch/checkpoints/resnet18-5c106cde_converted.pth', # Input your teacher checkpoint
feat_channels=dict(student=[160, 320, 1280],
teacher=[128, 256, 512]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(type='MobileNetV2',
out_indices=(5, 6, 7),
widen_factor=1.0),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=1280)
),
teacher=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1280,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=1280,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
checkpoint_config = dict(interval=10, max_keep_ckpts=1)
| 2,802 | 27.896907 | 136 |
py
|
KnowledgeFactor
|
KnowledgeFactor-main/cls/configs/imagenet-kf/resnet50_resnet18_b32x8_imagenet_softtar_kf.py
|
_base_ = [
'../_base_/datasets/imagenet_bs32_randaug.py',
'../_base_/schedules/imagenet_bs256_coslr.py'
]
# yapf:disable
log_config = dict(
interval=100,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
fp16 = dict(loss_scale=512.)
# model settings
model = dict(
type='KFImageClassifier',
kd_loss=dict(type='SoftTarget',
temperature=10.0),
train_cfg=dict(
augments=[
dict(type='BatchMixup', alpha=0.1,
num_classes=1000, prob=0.5)
],
lambda_kd=0.1,
lambda_feat=1.0,
alpha=1.0,
beta=1e-3,
task_weight=1.0,
teacher_checkpoint=None, # Input your teacher checkpoint
feat_channels=dict(student=[128, 256, 512],
teacher=[512, 1024, 2048]),
),
backbone=dict(
num_task=1,
student=dict(
CKN=dict(type='ResNet',
depth=18,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
TSN=dict(type='TSN_backbone',
backbone=dict(type='MobileNetV2',
out_indices=(7, ),
widen_factor=0.5),
in_channels=1280,
out_channels=512)
),
teacher=dict(type='ResNet',
depth=50,
num_stages=4,
out_indices=(1, 2, 3),
style='pytorch'),
),
neck=dict(
student=dict(type='GlobalAveragePooling'),
teacher=dict(type='GlobalAveragePooling')
),
head=dict(
student=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
task=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=512,
loss=dict(
type='LabelSmoothLoss',
label_smooth_val=0.1,
num_classes=1000,
reduction='mean',
loss_weight=1.0),
),
teacher=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=2048,
loss=dict(type='CrossEntropyLoss',
loss_weight=1.0),
)
)
)
checkpoint_config = dict(interval=10, max_keep_ckpts=2)
| 2,796 | 26.693069 | 64 |
py
|
Detecting-Cyberbullying-Across-SMPs
|
Detecting-Cyberbullying-Across-SMPs-master/models.py
|
import tflearn
import numpy as np
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_1d, global_max_pool
from tflearn.layers.merge_ops import merge
from tflearn.layers.estimator import regression
import tensorflow as tf
import os
os.environ['KERAS_BACKEND']='theano'
from keras.layers import Embedding
from keras.layers import Dense, Input, Flatten
from keras.layers import Conv1D, MaxPooling1D, Embedding, Merge, Dropout, LSTM, GRU, Bidirectional
from keras.models import Model,Sequential
from keras import backend as K
from keras.engine.topology import Layer, InputSpec
from keras import initializers, optimizers
def lstm_keras(inp_dim, vocab_size, embed_size, num_classes, learn_rate):
# K.clear_session()
model = Sequential()
model.add(Embedding(vocab_size, embed_size, input_length=inp_dim, trainable=True))
model.add(Dropout(0.25))
model.add(LSTM(embed_size))
model.add(Dropout(0.50))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
print model.summary()
return model
def cnn(inp_dim, vocab_size, embed_size, num_classes, learn_rate):
tf.reset_default_graph()
network = input_data(shape=[None, inp_dim], name='input')
network = tflearn.embedding(network, input_dim=vocab_size, output_dim=embed_size, name="EmbeddingLayer")
network = dropout(network, 0.25)
branch1 = conv_1d(network, embed_size, 3, padding='valid', activation='relu', regularizer="L2", name="layer_1")
branch2 = conv_1d(network, embed_size, 4, padding='valid', activation='relu', regularizer="L2", name="layer_2")
branch3 = conv_1d(network, embed_size, 5, padding='valid', activation='relu', regularizer="L2", name="layer_3")
network = merge([branch1, branch2, branch3], mode='concat', axis=1)
network = tf.expand_dims(network, 2)
network = global_max_pool(network)
network = dropout(network, 0.50)
network = fully_connected(network, num_classes, activation='softmax', name="fc")
network = regression(network, optimizer='adam', learning_rate=learn_rate,
loss='categorical_crossentropy', name='target')
model = tflearn.DNN(network, tensorboard_verbose=0)
return model
def blstm(inp_dim,vocab_size, embed_size, num_classes, learn_rate):
# K.clear_session()
model = Sequential()
model.add(Embedding(vocab_size, embed_size, input_length=inp_dim, trainable=True))
model.add(Dropout(0.25))
model.add(Bidirectional(LSTM(embed_size)))
model.add(Dropout(0.50))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
return model
class AttLayer(Layer):
def __init__(self, **kwargs):
super(AttLayer, self).__init__(**kwargs)
def build(self, input_shape):
# Create a trainable weight variable for this layer.
self.W = self.add_weight(name='kernel',
shape=(input_shape[-1],),
initializer='random_normal',
trainable=True)
super(AttLayer, self).build(input_shape) # Be sure to call this somewhere!
def call(self, x, mask=None):
eij = K.tanh(K.dot(x, self.W))
ai = K.exp(eij)
weights = ai/K.sum(ai, axis=1).dimshuffle(0,'x')
weighted_input = x*weights.dimshuffle(0,1,'x')
return weighted_input.sum(axis=1)
def compute_output_shape(self, input_shape):
return (input_shape[0], input_shape[-1])
def blstm_atten(inp_dim, vocab_size, embed_size, num_classes, learn_rate):
# K.clear_session()
model = Sequential()
model.add(Embedding(vocab_size, embed_size, input_length=inp_dim))
model.add(Dropout(0.25))
model.add(Bidirectional(LSTM(embed_size, return_sequences=True)))
model.add(AttLayer())
model.add(Dropout(0.50))
model.add(Dense(num_classes, activation='softmax'))
adam = optimizers.Adam(lr=learn_rate, beta_1=0.9, beta_2=0.999)
model.compile(loss='categorical_crossentropy',
optimizer='adam',
metrics=['accuracy'])
model.summary()
return model
def get_model(m_type,inp_dim, vocab_size, embed_size, num_classes, learn_rate):
if m_type == 'cnn':
model = cnn(inp_dim, vocab_size, embed_size, num_classes, learn_rate)
elif m_type == 'lstm':
model = lstm_keras(inp_dim, vocab_size, embed_size, num_classes, learn_rate)
elif m_type == "blstm":
model = blstm(inp_dim)
elif m_type == "blstm_attention":
model = blstm_atten(inp_dim, vocab_size, embed_size, num_classes, learn_rate)
else:
print "ERROR: Please specify a correst model"
return None
return model
| 5,025 | 39.208 | 115 |
py
|
mmda
|
mmda-main/setup.py
|
from setuptools import setup
setup()
| 38 | 8.75 | 28 |
py
|
mmda
|
mmda-main/examples/title_abstract.py
|
import pathlib
import sys
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.heuristic_predictors.dictionary_word_predictor import DictionaryWordPredictor
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.predictors.hf_predictors.vila_predictor import IVILAPredictor
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
pdf_file = pathlib.Path(sys.argv[1]).resolve()
print(f"reading pdf from from {pdf_file}")
pdf_plumber = PDFPlumberParser()
rasterizer = PDF2ImageRasterizer()
doc = pdf_plumber.parse(pdf_file)
doc.annotate_images(rasterizer.rasterize(pdf_file, dpi=72))
lp_predictor1 = LayoutParserPredictor.from_pretrained("lp://efficientdet/PubLayNet")
lp_predictor2 = LayoutParserPredictor.from_pretrained("lp://efficientdet/MFD")
blocks = lp_predictor1.predict(doc) + lp_predictor2.predict(doc)
doc.annotate(blocks=blocks)
vila_predictor = IVILAPredictor.from_pretrained(
"/home/ubuntu/tmp/vila",
added_special_sepration_token="[BLK]",
agg_level="row"
)
doc.annotate(vila_spans=vila_predictor.predict(doc))
dictionary_word_predictor = DictionaryWordPredictor("/dev/null")
words = dictionary_word_predictor.predict(doc)
doc.annotate(words=words)
title = " ".join(
" ".join(w.text for w in sg.words)
for sg in doc.vila_spans if sg.type == 0
)
abstract = " ".join(
" ".join(w.text for w in sg.words)
for sg in doc.vila_spans if sg.type == 2
)
print(f"Title = '{title}'")
print(f"Abstract = '{abstract}'")
| 1,510 | 31.847826 | 98 |
py
|
mmda
|
mmda-main/examples/section_nesting_prediction/main.py
|
"""
Tests for SectionNestingPredictor
@rauthur
"""
import pathlib
import unittest
from copy import deepcopy
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.hf_predictors.vila_predictor import IVILAPredictor
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.predictors.xgb_predictors.section_nesting_predictor import (
SectionNestingPredictor,
)
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.types.annotation import SpanGroup
def main():
file_path = pathlib.Path(__file__).parent
model_path = file_path / "nesting.bin"
pdf_path = file_path / "sample.pdf"
parser = PDFPlumberParser(extra_attrs=[])
rasterizer = PDF2ImageRasterizer()
layout_predictor = LayoutParserPredictor.from_pretrained(
"lp://efficientdet/PubLayNet"
)
vila = IVILAPredictor.from_pretrained(
"allenai/ivila-row-layoutlm-finetuned-s2vl-v2",
agg_level="row",
added_special_sepration_token="[BLK]",
)
predictor = SectionNestingPredictor(model_path)
doc = parser.parse(pdf_path)
images = rasterizer.rasterize(pdf_path, dpi=72)
doc.annotate_images(images)
blocks = layout_predictor.predict(doc)
doc.annotate(blocks=blocks)
results = vila.predict(doc)
doc.annotate(results=results)
# Extract sections from VILA predictions and re-add boxes
vila_sections = []
for i, span_group in enumerate(doc.results):
if span_group.type != 4:
continue
# Boxes are not returned from VILA so reach into tokens
token_spans = [deepcopy(t.spans) for t in span_group.tokens]
token_spans = [span for l in token_spans for span in l] # Flatten list
# Maintain the text from VILA for each span group but replace newlines
metadata = deepcopy(span_group.metadata)
metadata.text = span_group.text.replace("\n", " ")
vila_sections.append(
SpanGroup(
spans=token_spans,
box_group=deepcopy(span_group.box_group),
id=i, # Ensure some ID is created
doc=None, # Allows calling doc.annotate(...)
metadata=metadata,
)
)
doc.annotate(sections=vila_sections)
nestings = predictor.predict(doc)
section_index = {s.id: s for s in nestings}
for section in nestings:
parent_id = section.metadata.parent_id
if parent_id == -1:
print(f"Section '{section.text}' is top-level!")
continue
parent = section_index[parent_id]
print(f"Section '{section.text}' has parent '{parent.text}'")
if __name__ == "__main__":
main()
| 2,720 | 28.576087 | 79 |
py
|
mmda
|
mmda-main/examples/vlue_evaluation/main.py
|
"""Compare VILA predictors to other models on VLUE."""
import argparse
import csv
import os
from collections import defaultdict
from dataclasses import dataclass
from statistics import mean, stdev
from typing import Callable, Dict, List
from mmda.eval.vlue import (LabeledDoc, PredictedDoc, grobid_prediction,
read_labels, s2_prediction, score)
from mmda.parsers.grobid_parser import GrobidHeaderParser
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.parsers.symbol_scraper_parser import SymbolScraperParser
from mmda.predictors.hf_predictors.vila_predictor import (BaseVILAPredictor,
HVILAPredictor,
IVILAPredictor)
from mmda.predictors.lp_predictors import LayoutParserPredictor
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.types.annotation import SpanGroup
from mmda.types.document import Document
@dataclass
class VluePrediction:
"""Conforms to PredictedDoc protocol."""
id: str # pylint: disable=invalid-name
title: str
abstract: str
def _vila_docbank_extract_entities(types: List[str]):
def extractor(doc: Document) -> Dict[str, List[SpanGroup]]:
mapping = {
"paragraph": 0,
"title": 1,
"equation": 2,
"reference": 3,
"section": 4,
"list": 5,
"table": 6,
"caption": 7,
"author": 8,
"abstract": 9,
"footer": 10,
"date": 11,
"figure": 12,
}
rmapping = {v: k for k, v in mapping.items()}
int_types = set([mapping[x] for x in types])
result = defaultdict(list)
for span_group in doc.preds:
if span_group.type in int_types:
result[rmapping[span_group.type]].append(span_group)
return result
return extractor
def _vila_grotoap2_extract_entities(types: List[str]):
def extractor(doc: Document) -> Dict[str, List[SpanGroup]]:
# TODO: Have some sort of unified mapping between this and docbank
# TODO: Below title and abstract have been lower-cased to match docbank
mapping = {
"BIB_INFO": 0,
"REFERENCES": 1,
"UNKNOWN": 2,
"BODY_CONTENT": 3,
"PAGE_NUMBER": 4,
"TABLE": 5,
"ACKNOWLEDGMENT": 6,
"FIGURE": 7,
"CONFLICT_STATEMENT": 8,
"AFFILIATION": 9,
"DATES": 10,
"TYPE": 11,
"title": 12,
"AUTHOR": 13,
"abstract": 14,
"CORRESPONDENCE": 15,
"EDITOR": 16,
"COPYRIGHT": 17,
"AUTHOR_TITLE": 18,
"KEYWORDS": 19,
"GLOSSARY": 20,
"EQUATION": 21,
}
rmapping = {v: k for k, v in mapping.items()}
int_types = set([mapping[x] for x in types])
result = defaultdict(list)
for span_group in doc.preds:
if span_group.type in int_types:
result[rmapping[span_group.type]].append(span_group)
return result
return extractor
def vila_prediction(
id_: str,
doc: Document,
vila_predictor: BaseVILAPredictor, # pylint: disable=redefined-outer-name
vila_extractor: Callable[[Document], Dict[str, List[SpanGroup]]],
) -> VluePrediction:
# Predict token types
span_groups = vila_predictor.predict(doc)
doc.annotate(preds=span_groups)
extracted = vila_extractor(doc)
title = " ".join([" ".join(x.symbols) for x in extracted["title"]])
abstract = "\n".join([" ".join(x.symbols) for x in extracted["abstract"]])
return VluePrediction(id=id_, title=title, abstract=abstract)
def _vila_models(model_name: str):
if model_name == "ivila-block-layoutlm-finetuned-docbank":
vila_predictor = IVILAPredictor.from_pretrained(
"allenai/ivila-block-layoutlm-finetuned-docbank",
added_special_sepration_token="[BLK]", # FIXME: typo in underlying repo
agg_level="block",
)
vila_extractor = _vila_docbank_extract_entities(["title", "abstract"])
elif model_name == "ivila-block-layoutlm-finetuned-grotoap2":
vila_predictor = IVILAPredictor.from_pretrained(
"allenai/ivila-block-layoutlm-finetuned-grotoap2",
added_special_sepration_token="[BLK]",
agg_level="block",
)
vila_extractor = _vila_grotoap2_extract_entities(["title", "abstract"])
elif model_name == "hvila-block-layoutlm-finetuned-docbank":
vila_predictor = HVILAPredictor.from_pretrained(
"allenai/hvila-block-layoutlm-finetuned-docbank",
agg_level="block",
added_special_sepration_token="[BLK]",
group_bbox_agg="first",
)
vila_extractor = _vila_docbank_extract_entities(["title", "abstract"])
elif model_name == "hvila-row-layoutlm-finetuned-docbank":
vila_predictor = HVILAPredictor.from_pretrained(
"allenai/hvila-row-layoutlm-finetuned-docbank",
agg_level="row",
added_special_sepration_token="[SEP]",
group_bbox_agg="first",
)
vila_extractor = _vila_docbank_extract_entities(["title", "abstract"])
elif model_name == "hvila-block-layoutlm-finetuned-grotoap2":
vila_predictor = HVILAPredictor.from_pretrained(
"allenai/hvila-block-layoutlm-finetuned-grotoap2",
agg_level="block",
added_special_sepration_token="[BLK]",
group_bbox_agg="first",
)
vila_extractor = _vila_grotoap2_extract_entities(["title", "abstract"])
elif model_name == "hvila-row-layoutlm-finetuned-grotoap2":
vila_predictor = HVILAPredictor.from_pretrained(
"allenai/hvila-row-layoutlm-finetuned-grotoap2",
agg_level="row",
added_special_sepration_token="[SEP]",
group_bbox_agg="first",
)
vila_extractor = _vila_grotoap2_extract_entities(["title", "abstract"])
return vila_predictor, vila_extractor
def save_prediction(
writer: csv.DictWriter,
label: LabeledDoc,
pred: PredictedDoc,
model: str,
title_score: float,
abstract_score: float,
) -> None:
d = {
"SHA": label.id,
"URL": label.url,
"Model": model,
"Title": pred.title,
"TitleScore": title_score,
"Abstract": pred.abstract,
"AbstractScore": abstract_score,
}
writer.writerow(d)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--pdfs-basedir", type=str, nargs="?", required=True)
parser.add_argument("--labels-json-path", type=str, nargs="?", required=True)
parser.add_argument("--output-csv-path", type=str, nargs="?", required=True)
parser.add_argument("--vila-parser", type=str, nargs="?", required=True)
parser.add_argument("--sscraper-path", type=str, nargs="?", required=False)
args = parser.parse_args()
def pdf_path(id_: str) -> str:
return os.path.join(args.pdfs_basedir, id_, "{}.pdf".format(id_))
title_scores = defaultdict(list)
abstract_scores = defaultdict(list)
labels = read_labels(args.labels_json_path)
rasterizer = PDF2ImageRasterizer()
grobid_parser = GrobidHeaderParser()
if args.vila_parser == "pdfplumber":
vila_parser = PDFPlumberParser()
elif args.vila_parser == "sscraper":
if args.sscraper_path is None:
raise RuntimeError("Please provide --sscraper-path!")
vila_parser = SymbolScraperParser(args.sscraper_path)
with open(args.output_csv_path, "w", newline="") as csvfile:
fields = [
"SHA",
"URL",
"Model",
"Title",
"TitleScore",
"Abstract",
"AbstractScore",
]
writer = csv.DictWriter(csvfile, fieldnames=fields)
writer.writeheader()
for label in labels:
# Known failing PDFs are excluded ...
if label.id in [
# PDF Plumber failures
"396fb2b6ec96ff74e22ddd2484a9728257cccfbf",
"3ef6e51baee01b4c90c188a964f2298b7c309b07",
"4277d1ec41d88d595a0d80e4ab4146d8c2db2539",
"564a73c07436e1bd75e31b54825d2ba8e4fb68b7",
# SymbolScraper failures
"25b3966066bfe9d17dfa2384efd57085f0c546a5",
"9b69f0ca8bbc617bb48d76f73d269af5230b1a5e",
]:
continue
save_prediction(writer, label, label, "Gold", 1.0, 1.0)
item_pdf_path = pdf_path(label.id)
grobid_pred = grobid_prediction(item_pdf_path, grobid_parser)
title_scores["grobid"].append(score(label, grobid_pred, "title"))
abstract_scores["grobid"].append(score(label, grobid_pred, "abstract"))
save_prediction(
writer,
label,
grobid_pred,
"Grobid-0.7.0",
title_scores["grobid"][-1],
abstract_scores["grobid"][-1],
)
s2_pred = s2_prediction(label.id)
title_scores["s2"].append(score(label, s2_pred, "title"))
abstract_scores["s2"].append(score(label, s2_pred, "abstract"))
save_prediction(
writer,
label,
s2_pred,
"S2-API",
title_scores["s2"][-1],
abstract_scores["s2"][-1],
)
layout_predictor = LayoutParserPredictor.from_pretrained(
"lp://efficientdet/PubLayNet"
)
equation_layout_predictor = LayoutParserPredictor.from_pretrained(
"lp://efficientdet/MFD"
)
for vila_model_name in [
"ivila-block-layoutlm-finetuned-docbank",
"ivila-block-layoutlm-finetuned-grotoap2",
"hvila-block-layoutlm-finetuned-docbank",
"hvila-row-layoutlm-finetuned-docbank",
"hvila-block-layoutlm-finetuned-grotoap2",
"hvila-row-layoutlm-finetuned-grotoap2",
]:
vila_doc = vila_parser.parse(item_pdf_path)
images = rasterizer.rasterize(item_pdf_path, dpi=72)
vila_doc.annotate_images(images=images)
layout_regions = layout_predictor.predict(vila_doc)
equation_layout_regions = equation_layout_predictor.predict(vila_doc)
vila_doc.annotate(blocks=layout_regions + equation_layout_regions)
vila_predictor, vila_extractor = _vila_models(vila_model_name)
vila_pred = vila_prediction(
label.id,
vila_doc,
vila_predictor=vila_predictor,
vila_extractor=vila_extractor,
)
title_scores[vila_model_name].append(score(label, vila_pred, "title"))
abstract_scores[vila_model_name].append(
score(label, vila_pred, "abstract")
)
save_prediction(
writer,
label,
vila_pred,
vila_model_name,
title_scores[vila_model_name][-1],
abstract_scores[vila_model_name][-1],
)
for category, scores in {
"TITLE": title_scores,
"ABSTRACT": abstract_scores,
}.items():
print("-------- {} --------".format(category))
for key in sorted(list(scores.keys())):
data = scores[key]
print(
"{}---\nN: {}; Mean: {}; Std: {}".format(
key,
len(scores[key]),
mean(scores[key]),
stdev(scores[key]),
)
)
| 12,105 | 34.19186 | 86 |
py
|
mmda
|
mmda-main/examples/bibliography_extraction/main.py
|
from collections import defaultdict
from dataclasses import dataclass
from typing import Iterable, List, Optional
from mmda.eval.metrics import box_overlap
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.heuristic_predictors.grobid_citation_predictor import (
get_title,
)
from mmda.predictors.hf_predictors.vila_predictor import HVILAPredictor
from mmda.predictors.tesseract_predictors import TesseractBlockPredictor
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
from mmda.types.annotation import BoxGroup, SpanGroup
from mmda.types.document import Document
PDF_PATH = "resources/maml.pdf"
def _clone_span_group(span_group: SpanGroup):
return SpanGroup(
spans=span_group.spans,
id=span_group.id,
text=span_group.text,
type=span_group.type,
box_group=span_group.box_group,
)
@dataclass
class PageSpan:
num: int
start: int
end: int
def _index_document_pages(document) -> List[PageSpan]:
page_spans = []
# Assume document.pages yields SpanGroups with only 1 Span
for page in document.pages:
assert len(page.spans) == 1
span = page.spans[0]
page_spans.append(PageSpan(num=span.box.page, start=span.start, end=span.end))
return page_spans
def _find_page_num(span_group: SpanGroup, page_spans: List[PageSpan]) -> int:
s = min([span.start for span in span_group.spans])
e = max([span.end for span in span_group.spans])
for page_span in page_spans:
if s >= page_span.start and e <= page_span.end:
return page_span.num
raise RuntimeError(f"Unable to find page for {span_group}!")
def _highest_overlap_block(
token: SpanGroup, blocks: Iterable[BoxGroup]
) -> Optional[BoxGroup]:
assert len(token.spans) == 1
token_box = token.spans[0].box
found_block = None
found_score = 0.0
for curr_block in blocks:
assert len(curr_block.boxes) == 1
curr_box = curr_block.boxes[0]
curr_score = box_overlap(token_box, curr_box)
if curr_score > found_score:
found_score = curr_score
found_block = curr_block
return found_block
def extract_bibliography_grotoap2(document: Document) -> Iterable[SpanGroup]:
"""GROTOAP2 has type 1 for REFERENCES"""
return [_clone_span_group(sg) for sg in document.preds if sg.type == 1]
parser = PDFPlumberParser()
document = parser.parse(PDF_PATH)
rasterizer = PDF2ImageRasterizer()
# Use larger DPI for better results (supposedly) with Tesseract
images = rasterizer.rasterize(PDF_PATH, dpi=150)
document.annotate_images(images)
block_predictor = TesseractBlockPredictor()
blocks = block_predictor.predict(document)
document.annotate(blocks=blocks)
# Use smaller DPI images for VILA
images = rasterizer.rasterize(PDF_PATH, dpi=72)
document.annotate_images(images, is_overwrite=True)
vila_predictor = HVILAPredictor.from_pretrained(
"allenai/hvila-row-layoutlm-finetuned-grotoap2",
agg_level="block",
added_special_sepration_token="[BLK]",
group_bbox_agg="first",
)
preds = vila_predictor.predict(document)
document.annotate(preds=preds)
biblio = extract_bibliography_grotoap2(document)
document.annotate(bibliography=biblio)
# TESTING
bib = document.bibliography[0]
page_num = _find_page_num(bib, _index_document_pages(document))
# FIXME: We have to reference blocks b/c they've been coerced to SpanGroup in Document
page_blocks = [b for b in blocks if b.boxes[0].page == page_num]
block_tokens = defaultdict(list)
import pdb
pdb.set_trace()
# Group bib tokes into a block
for token in bib.tokens:
highest_overlap_block = _highest_overlap_block(token, page_blocks)
if highest_overlap_block:
block_tokens[highest_overlap_block.id].append(token)
# Print bibliography entries
for span_groups in block_tokens.values():
reference = " ".join(["".join(sg.symbols) for sg in span_groups])
reference = reference.replace("- ", "")
# Use grobid to get the title information from reference text
title = get_title(reference)
print(reference)
print(title)
print()
print()
| 4,148 | 27.417808 | 86 |
py
|
mmda
|
mmda-main/examples/vila_for_scidoc_parsing/main.py
|
import argparse
import contextlib
import json
import os
import re
import urllib.request
from tempfile import NamedTemporaryFile
from typing import Dict, Generator, List, Optional
from layoutparser.elements import Layout, Rectangle, TextBlock
from layoutparser.visualization import draw_box
from PIL.Image import Image
from tqdm import tqdm
from mmda.recipes.core_recipe import CoreRecipe
from mmda.types.annotation import SpanGroup
DEFAULT_DEST_DIR = os.path.expanduser("~/mmda_predictions")
def is_url(url: str) -> bool:
if os.path.exists(url):
return False
# regex to determine if a string is a valid URL
return re.search(r"^(?:http|ftp)s?://", url) is not None
def get_dir_name(path: str) -> str:
if is_url(path):
return path.split("/")[-1].rstrip(".pdf")
else:
return os.path.basename(path).rstrip(".pdf")
@contextlib.contextmanager
def download_pdf(url: str) -> Generator[str, None, None]:
name: Optional[str] = None
# Create a temporary file
with NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
# Download the file using urllib
with urllib.request.urlopen(url) as response:
# Save the downloaded data to the temporary file
temp_file.write(response.read())
# Get the name of the temporary file
name = temp_file.name
# return the name of the temporary file
yield name
# Delete the temporary file
os.remove(name)
def draw_tokens(
image: Image,
doc_tokens: List[SpanGroup],
color_map: Optional[Dict[int, str]] = None,
token_boundary_width: int = 0,
alpha: float = 0.25,
**lp_draw_box_kwargs,
):
"""Draw MMDA tokens as rectangles on the an image of a page."""
w, h = image.size
layout = [
TextBlock(
Rectangle(
*token.spans[0]
.box.get_absolute(page_height=h, page_width=w) # pyright: ignore
.coordinates
),
type=token.type,
text=token.text,
)
for token in doc_tokens
]
return draw_box(
image,
Layout(blocks=layout),
color_map=color_map,
box_width=token_boundary_width,
box_alpha=alpha,
**lp_draw_box_kwargs,
)
def draw_blocks(
image: Image,
doc_tokens: List[SpanGroup],
color_map: Optional[Dict[int, str]] = None,
token_boundary_width: int = 0,
alpha: float = 0.25,
**lp_draw_box_kwargs,
):
w, h = image.size
layout = [
TextBlock(
Rectangle(
*token.box_group.boxes[0] # pyright: ignore
.get_absolute(page_height=h, page_width=w)
.coordinates
),
type=token.type,
text=token.text,
)
for token in doc_tokens
]
return draw_box(
image,
Layout(blocks=layout),
color_map=color_map,
box_width=token_boundary_width,
box_alpha=alpha,
**lp_draw_box_kwargs,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--pdf-path",
type=str,
nargs="+",
required=True,
help="Path to PDF file(s) to be processed. Can be a URL.",
)
parser.add_argument(
"-d",
"--destination",
type=str,
default=DEFAULT_DEST_DIR,
help=(
"Path to directory where to save the results. "
"A directory will be created for each paper"
),
)
args = parser.parse_args()
recipe = CoreRecipe()
pbar = tqdm(args.pdf_path)
for pdf_path in pbar:
pbar.set_description(f"Working on {pdf_path}")
if is_url(pdf_path):
with download_pdf(pdf_path) as temp_file:
doc = recipe.from_path(temp_file)
else:
assert os.path.exists(pdf_path), f"PDF file {pdf_path} does not exist."
doc = recipe.from_path(pdf_path)
# get location where to save data
save_folder = os.path.join(args.destination, get_dir_name(pdf_path))
os.makedirs(save_folder, exist_ok=True)
# save images with layout and text predictions
for pid, (page, image) in enumerate(zip(doc.pages, doc.images)):
new_tokens = []
for pred in page.vila_span_groups:
for token in pred.tokens:
new_token = token.from_json(token.to_json())
new_token.type = pred.type
new_token.text = token.text
new_tokens.append(new_token)
# draw sections and equations
viz = draw_tokens(image, new_tokens, alpha=0.6)
viz = draw_blocks(viz, page.equations, alpha=0.2)
viz.save(f"{save_folder}/{pid}.png")
# Save all text alongside name of section it belongs to
with open(f"{save_folder}/sections.jsonl", "w") as f:
for pid, page in enumerate(doc.pages): # pyright: ignore
for pred in page.vila_span_groups:
data = {
"text": str(pred.text),
"type": pred.type,
"page": int(pid),
}
f.write(f"{json.dumps(data, sort_keys=True)}\n")
# Save all equations
with open(f"{save_folder}/equations.jsonl", "w") as f:
for pid, page in enumerate(doc.pages): # pyright: ignore
for pred in page.equations:
data = {
"text": str(pred.text),
"page": int(pid),
}
f.write(f"{json.dumps(data, sort_keys=True)}\n")
| 5,773 | 28.309645 | 83 |
py
|
mmda
|
mmda-main/src/mmda/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/eval/vlue.py
|
import json
import random
import string
from dataclasses import dataclass
from typing import Protocol
from mmda.eval import s2
from mmda.eval.metrics import levenshtein
from mmda.parsers.grobid_parser import GrobidHeaderParser
@dataclass(frozen=True)
class LabeledDoc:
id: str
title: str
abstract: str
url: str
class PredictedDoc(Protocol):
@property
def title(self):
raise NotImplementedError
@property
def abstract(self):
raise NotImplementedError
@dataclass
class DefaultPredictedDoc:
id: str
title: str
abstract: str
def grobid_prediction(pdf_path: str, parser: GrobidHeaderParser) -> PredictedDoc:
doc = parser.parse(pdf_path)
title = " ".join(doc.title[0].symbols)
abstract = "\n".join([" ".join(x.symbols) for x in doc.abstract])
return DefaultPredictedDoc(id=pdf_path, title=title, abstract=abstract)
def s2_prediction(id_: str) -> PredictedDoc:
metadata = s2.get_paper_metadata(id_)
title = metadata.title if metadata.title else ""
abstract = metadata.abstract if metadata.abstract else ""
return DefaultPredictedDoc(id=id_, title=title, abstract=abstract)
def random_prediction(label: LabeledDoc) -> PredictedDoc:
"""
Jumbled ASCII lowercase characters of same length as title/abstract
"""
def rand_str(n: int) -> str:
return "".join([random.choice(string.ascii_lowercase) for _ in range(n)])
random_title = rand_str(len(label.title))
random_abstract = rand_str(len(label.abstract))
return DefaultPredictedDoc(
id=label.id, title=random_title, abstract=random_abstract
)
def read_labels(labels_json_path: str) -> list[LabeledDoc]:
"""Read label JSON data into expected format for VLUE evaluation.
Args:
labels_json_path (str): Path to curated labels JSON file
Returns:
list[LabeledDoc]: List of labeled documents
"""
with open(labels_json_path, encoding="utf-8") as f:
labels = [LabeledDoc(**l) for l in json.loads(f.read())]
return labels
def score(label: LabeledDoc, pred: PredictedDoc, attr: str) -> float:
"""Evaluate a prediction for a specific field on VLUE.
Args:
label (LabeledDoc): Label read from JSON file
pred (PredictedDoc): Predicted title/abstract document
attr (str): Which field to evaluate
Returns:
float: Score between 0 and 1.
"""
a = label.__getattribute__(attr)
b = pred.__getattribute__(attr)
return 1 - levenshtein(a, b, case_sensitive=True) / max(len(a), len(b))
| 2,577 | 24.524752 | 81 |
py
|
mmda
|
mmda-main/src/mmda/eval/s2.py
|
from dataclasses import dataclass
from typing import Optional
import requests
_API_FIELDS = ["title", "abstract", "url"]
_API_URL = "https://api.semanticscholar.org/graph/v1/paper/{}?fields={}"
@dataclass
class PaperMetadata:
id: str
url: str
title: str
abstract: Optional[str]
def get_paper_metadata(paper_id: str, fields=_API_FIELDS) -> PaperMetadata:
qs = ",".join(fields)
url = _API_URL.format(paper_id, qs)
req = requests.get(url)
if req.status_code != 200:
raise RuntimeError(f"Unable to retrieve paper: {paper_id}!")
data = req.json()
return PaperMetadata(
id=data["paperId"],
url=data["url"],
title=data["title"],
abstract=data["abstract"],
)
| 743 | 21.545455 | 75 |
py
|
mmda
|
mmda-main/src/mmda/eval/metrics.py
|
from mmda.types.box import Box
def levenshtein(
s1: str,
s2: str,
case_sensitive: bool = True,
strip_spaces: bool = False,
normalize: bool = False,
) -> int:
"""See https://en.wikipedia.org/wiki/Levenshtein_distance.
Args:
s1 (str): String 1 for comparison
s2 (str): String 2 for comparison
case_sensitive (bool): When true compare strings as-is, downcase otherwise
strip_spaces (bool): When true remove spaces before comparing
normalize (bool): When true normalize by dividing by max word length
Returns:
int: The Levenshtein distance between strings
"""
if strip_spaces:
return levenshtein(
s1.replace(" ", ""),
s2.replace(" ", ""),
case_sensitive=case_sensitive,
strip_spaces=False,
normalize=normalize,
)
if not case_sensitive:
return levenshtein(
s1.lower(),
s2.lower(),
case_sensitive=True,
strip_spaces=strip_spaces,
normalize=normalize,
)
if len(s1) > len(s2):
# pylint: disable=arguments-out-of-order
return levenshtein(
s2,
s1,
case_sensitive=case_sensitive,
strip_spaces=strip_spaces,
normalize=normalize,
)
v0 = list(range(len(s2) + 1))
v1 = [0 for _ in range(len(s2) + 1)]
# pylint: disable=consider-using-enumerate
for i in range(len(s1)):
v1[0] = i + 1
for j in range(len(s2)):
d_ = v0[j + 1] + 1
i_ = v1[j] + 1
if s1[i] == s2[j]:
s_ = v0[j]
else:
s_ = v0[j] + 1
v1[j + 1] = min([d_, i_, s_])
v0 = v1
v1 = [0 for _ in range(len(s2) + 1)]
if normalize:
return v0[len(s2)] / len(s2)
else:
return v0[len(s2)]
def box_overlap(box: Box, container: Box) -> float:
"""Returns the percentage of area of a box inside of a container."""
bl, bt, bw, bh = box.xywh
br = bl + bw
bb = bt + bh
cl, ct, cw, ch = container.xywh
cr = cl + cw
cb = ct + ch
if bl >= cr:
# Box is 'after' right side of container
return 0.0
if br <= cl:
# Box is 'before' left side of container
return 0.0
if bt >= cb:
# Box is 'below' bottom of container
return 0.0
if bb <= ct:
# Box is 'above' top of container
return 0.0
if bl >= cl and br <= cr and bt >= ct and bb <= cb:
# Fully contained in container
return 1.0
# Bounded space coordinates
sl = max([bl, cl])
sr = min([br, cr])
st = max([bt, ct])
sb = min([bb, cb])
sw = sr - sl
sh = sb - st
return (sw * sh) / (bw * bh)
| 2,829 | 24.044248 | 82 |
py
|
mmda
|
mmda-main/src/mmda/eval/__init__.py
| 0 | 0 | 0 |
py
|
|
mmda
|
mmda-main/src/mmda/rasterizers/rasterizer.py
|
from typing import Iterable, Protocol
from mmda.types.image import PILImage
try:
import pdf2image
except ImportError:
pass
class Rasterizer(Protocol):
def rasterize(self, input_pdf_path: str, dpi: int, **kwargs) -> Iterable[PILImage]:
"""Given an input PDF return a List[Image]
Args:
input_pdf_path (str): Path to the input PDF to process
dpi (int): Used for specify the resolution (or `DPI, dots per inch
<https://en.wikipedia.org/wiki/Dots_per_inch>`_) when loading images of
the pdf. Higher DPI values mean clearer images (also larger file sizes).
Returns:
Iterable[PILImage]
"""
raise NotImplementedError
class PDF2ImageRasterizer(Rasterizer):
def rasterize(self, input_pdf_path: str, dpi: int, **kwargs) -> Iterable[PILImage]:
images = pdf2image.convert_from_path(pdf_path=input_pdf_path, dpi=dpi)
return images
| 978 | 31.633333 | 95 |
py
|
mmda
|
mmda-main/src/mmda/rasterizers/__init__.py
|
from mmda.rasterizers.rasterizer import PDF2ImageRasterizer
__all__ = [
'PDF2ImageRasterizer'
]
| 100 | 19.2 | 59 |
py
|
mmda
|
mmda-main/src/mmda/predictors/lp_predictors.py
|
from typing import Union, List, Dict, Any, Optional
from tqdm import tqdm
import layoutparser as lp
from mmda.types import Document, Box, BoxGroup, Metadata
from mmda.types.names import ImagesField, PagesField
from mmda.predictors.base_predictors.base_predictor import BasePredictor
class LayoutParserPredictor(BasePredictor):
REQUIRED_BACKENDS = ["layoutparser"]
REQUIRED_DOCUMENT_FIELDS = [PagesField, ImagesField]
def __init__(self, model):
self.model = model
@classmethod
def from_pretrained(
cls,
config_path: str = "lp://efficientdet/PubLayNet",
model_path: str = None,
label_map: Optional[Dict] = None,
extra_config: Optional[Dict] = None,
device: str = None,
):
"""Initialize a pre-trained layout detection model from
layoutparser. The parameters currently are the same as the
default layoutparser Detectron2 models
https://layout-parser.readthedocs.io/en/latest/api_doc/models.html ,
and will be updated in the future.
"""
model = lp.AutoLayoutModel(
config_path=config_path,
model_path=model_path,
label_map=label_map,
extra_config=extra_config,
device=device,
)
return cls(model)
def postprocess(self,
model_outputs: lp.Layout,
page_index: int,
image: "PIL.Image") -> List[BoxGroup]:
"""Convert the model outputs into the mmda format
Args:
model_outputs (lp.Layout):
The layout detection results from layoutparser for
a page image
page_index (int):
The index of the current page, used for creating the
`Box` object
image (PIL.Image):
The image of the current page, used for converting
to relative coordinates for the box objects
Returns:
List[BoxGroup]:
The detected layout stored in the BoxGroup format.
"""
# block.coordinates returns the left, top, bottom, right coordinates
page_width, page_height = image.size
return [
BoxGroup(
boxes=[
Box(
l=block.coordinates[0],
t=block.coordinates[1],
w=block.width,
h=block.height,
page=page_index,
).get_relative(
page_width=page_width,
page_height=page_height,
)
],
metadata=Metadata(type=block.type)
)
for block in model_outputs
]
def predict(self, document: Document) -> List[BoxGroup]:
"""Returns a list of Boxgroups for the detected layouts for all pages
Args:
document (Document):
The input document object
Returns:
List[BoxGroup]:
The returned Boxgroups for the detected layouts for all pages
"""
document_prediction = []
for image_index, image in enumerate(tqdm(document.images)):
model_outputs = self.model.detect(image)
document_prediction.extend(
self.postprocess(model_outputs, image_index, image)
)
return document_prediction
| 3,464 | 31.083333 | 77 |
py
|
mmda
|
mmda-main/src/mmda/predictors/tesseract_predictors.py
|
import csv
import io
import itertools
from dataclasses import dataclass
from typing import Dict, Iterable, Tuple
import pytesseract
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.types.annotation import BoxGroup
from mmda.types.box import Box
from mmda.types.document import Document
from mmda.types.names import ImagesField
@dataclass
class TesseractData:
block_num: int
par_num: int
line_num: int
word_num: int
left: float
top: float
width: float
height: float
conf: int
text: str
def lrtb(self) -> Tuple[float, float, float, float]:
return self.left, self.left + self.width, self.top, self.top + self.height
@classmethod
def from_csv(cls, line: Dict[str, str]) -> "TesseractData":
return TesseractData(
block_num=int(line["block_num"]),
par_num=int(line["par_num"]),
line_num=int(line["line_num"]),
word_num=int(line["word_num"]),
left=float(line["left"]),
top=float(line["top"]),
width=float(line["width"]),
height=float(line["height"]),
conf=int(line["conf"]),
text=line["text"],
)
class TesseractBlockPredictor(BasePredictor):
REQUIRED_BACKENDS = ["pytesseract"]
REQUIRED_DOCUMENT_FIELDS = [ImagesField]
def predict(self, document: Document) -> Iterable[BoxGroup]:
box_groups = []
for idx, image in enumerate(document.images):
data = pytesseract.image_to_data(image)
reader = csv.DictReader(io.StringIO(data), delimiter="\t")
# Gather up lines that have any text in them
parsed = [
TesseractData.from_csv(line)
for line in reader
if len(line["text"].strip()) > 0
]
# Discard boxes that are the entire page
parsed = [
p for p in parsed if p.width < image.width or p.height < image.height
]
# TODO: Also include left, top in sort?
parsed = sorted(parsed, key=lambda x: x.block_num)
for key, blocks in itertools.groupby(parsed, key=lambda x: x.block_num):
min_l = float("inf")
max_r = float("-inf")
min_t = float("inf")
max_b = float("-inf")
for block in blocks:
l, r, t, b = block.lrtb()
if l < min_l:
min_l = l
if r > max_r:
max_r = r
if t < min_t:
min_t = t
if b > max_b:
max_b = b
w = max_r - min_l
h = max_b - min_t
box_groups.append(
BoxGroup(
id=key,
boxes=[
Box(l=min_l, t=min_t, w=w, h=h, page=idx).get_relative(
image.width, image.height
)
],
)
)
return box_groups
| 3,199 | 29.47619 | 85 |
py
|
mmda
|
mmda-main/src/mmda/predictors/__init__.py
|
# flake8: noqa
from necessary import necessary
with necessary(["tokenizers"], soft=True) as TOKENIZERS_AVAILABLE:
if TOKENIZERS_AVAILABLE:
from mmda.predictors.heuristic_predictors.whitespace_predictor import WhitespacePredictor
from mmda.predictors.heuristic_predictors.dictionary_word_predictor import DictionaryWordPredictor
__all__ = ['DictionaryWordPredictor', 'WhitespacePredictor']
with necessary('pysbd', soft=True) as PYSBD_AVAILABLE:
if PYSBD_AVAILABLE:
from mmda.predictors.heuristic_predictors.sentence_boundary_predictor \
import PysbdSentenceBoundaryPredictor
__all__.append('PysbdSentenceBoundaryPredictor')
with necessary(["layoutparser", "torch", "torchvision", "effdet"], soft=True) as PYTORCH_AVAILABLE:
if PYTORCH_AVAILABLE:
from mmda.predictors.lp_predictors import LayoutParserPredictor
__all__.append('LayoutParserPredictor')
| 934 | 41.5 | 106 |
py
|
mmda
|
mmda-main/src/mmda/predictors/sklearn_predictors/svm_word_predictor.py
|
"""
SVM Word Predictor
Given a list of tokens, predict which tokens were originally part of the same word.
This does this in two phases: First, it uses a whitespace tokenizer to inform
whether tokens were originally part of the same word. Second, it uses a SVM
classifier to predict whether hyphenated segments should be considered a single word.
"""
import logging
import os
import re
import tarfile
import tempfile
from collections import defaultdict
from typing import Dict, List, Set, Tuple
from urllib.parse import urlparse
import numpy as np
import requests
from joblib import load
from scipy.sparse import hstack
from mmda.parsers.pdfplumber_parser import PDFPlumberParser
from mmda.predictors.heuristic_predictors.whitespace_predictor import (
WhitespacePredictor,
)
from mmda.predictors.sklearn_predictors.base_sklearn_predictor import (
BaseSklearnPredictor,
)
from mmda.types import Document, Metadata, Span, SpanGroup
logger = logging.getLogger(__name__)
class IsWordResult:
def __init__(self, original: str, new: str, is_edit: bool) -> None:
self.original = original
self.new = new
self.is_edit = is_edit
class SVMClassifier:
def __init__(self, ohe_encoder, scaler, estimator, unigram_probs):
self.ohe_encoder = ohe_encoder
self.scaler = scaler
self.estimator = estimator
self.unigram_probs = unigram_probs
self.default_prob = unigram_probs["<unk>"]
self.sparse_columns = [
"shape",
"s_bg1",
"s_bg2",
"s_bg3",
"p_bg1",
"p_bg2",
"p_bg3",
"p_lower",
"s_lower",
]
self.dense_columns = [
"p_upper",
"s_upper",
"p_number",
"s_number",
"p_isalpha",
"s_isalpha",
"p_len",
"s_len",
"multi_hyphen",
"uni_prob",
]
@classmethod
def from_path(cls, tar_path: str):
with tempfile.TemporaryDirectory() as tmp_dir:
if urlparse(url=tar_path).scheme != "":
r = requests.get(tar_path)
with open(
os.path.join(tmp_dir, "svm_word_predictor.tar.gz"), "wb"
) as f:
f.write(r.content)
tar_path = os.path.join(tmp_dir, "svm_word_predictor.tar.gz")
with tarfile.open(tar_path, "r:gz") as tar:
tar.extractall(path=tmp_dir)
return cls.from_directory(tmp_dir)
@classmethod
def from_directory(cls, dir: str):
classifier = SVMClassifier.from_paths(
ohe_encoder_path=os.path.join(dir, "svm_word_predictor/ohencoder.joblib"),
scaler_path=os.path.join(dir, "svm_word_predictor/scaler.joblib"),
estimator_path=os.path.join(dir, "svm_word_predictor/hyphen_clf.joblib"),
unigram_probs_path=os.path.join(
dir, "svm_word_predictor/unigram_probs.pkl"
),
)
return classifier
@classmethod
def from_paths(
cls,
ohe_encoder_path: str,
scaler_path: str,
estimator_path: str,
unigram_probs_path: str,
):
ohe_encoder = load(ohe_encoder_path)
scaler = load(scaler_path)
estimator = load(estimator_path)
unigram_probs = load(unigram_probs_path)
classifier = SVMClassifier(
ohe_encoder=ohe_encoder,
scaler=scaler,
estimator=estimator,
unigram_probs=unigram_probs,
)
return classifier
def batch_predict(self, words: List[str], threshold: float) -> List[IsWordResult]:
if any([word.startswith("-") or word.endswith("-") for word in words]):
raise ValueError("Words should not start or end with hyphens.")
all_features, word_id_to_feature_ids = self._get_features(words)
all_scores = self.estimator.decision_function(all_features)
results = []
for word_id, feature_ids in word_id_to_feature_ids.items():
word = words[word_id]
word_segments = word.split("-")
score_per_hyphen_in_word = all_scores[feature_ids]
new_word = word_segments[0]
for word_segment, hyphen_score in zip(
word_segments[1:], score_per_hyphen_in_word
):
if hyphen_score > threshold:
new_word += "-"
else:
new_word += ""
new_word += word_segment
results.append(
IsWordResult(original=word, new=new_word, is_edit=word != new_word)
)
return results
def _get_dense_features(self, part: str, name_prefix: str):
upper = int(part[0].isupper())
number = int(part.isnumeric())
alpha = int(part.isalpha())
lower = part.lower()
plen = len(part)
return {
f"{name_prefix}_upper": upper,
f"{name_prefix}_number": number,
f"{name_prefix}_isalpha": alpha,
f"{name_prefix}_len": plen,
}
def _get_features(self, words: List[str]):
sparse_all, dense_all = [], []
idx, word_id_to_feature_ids = 0, dict()
for widx, word in enumerate(words):
split = word.split("-")
for i, s in enumerate(split[:-1]):
sparse_features, dense_features = dict(), dict()
prefix = "-".join(split[: i + 1])
suffix = "-".join(split[i + 1 :])
if widx not in word_id_to_feature_ids:
word_id_to_feature_ids[widx] = []
word_id_to_feature_ids[widx].append(idx)
idx += 1
dense_features.update(self._get_dense_features(prefix, "p"))
dense_features.update(self._get_dense_features(suffix, "s"))
orig_uni_prob = self.unigram_probs.get(word, self.default_prob)
presuf_uni_prob = self.unigram_probs.get(
f"{prefix}{suffix}", self.default_prob
)
dense_features["uni_prob"] = orig_uni_prob - presuf_uni_prob
dense_features["multi_hyphen"] = int(word.count("-") > 1)
sparse_features["shape"] = re.sub("\w", "x", word)
sparse_features["s_lower"] = suffix.lower()
sparse_features["s_bg1"] = suffix[:2]
sparse_features["s_bg2"] = suffix[1:3] if len(suffix) > 2 else ""
sparse_features["s_bg3"] = suffix[2:4] if len(suffix) > 3 else ""
sparse_features["p_lower"] = prefix.lower()
sparse_features["p_bg1"] = prefix[-2:][::-1] if len(prefix) > 1 else ""
sparse_features["p_bg2"] = (
prefix[-3:-1][::-1] if len(prefix) > 2 else ""
)
sparse_features["p_bg3"] = (
prefix[-4:-2][::-1] if len(prefix) > 3 else ""
)
sparse_all.append([sparse_features[k] for k in self.sparse_columns])
dense_all.append([dense_features[k] for k in self.dense_columns])
dense_transformed = self.scaler.transform(dense_all)
sparse_transformed = self.ohe_encoder.transform(sparse_all)
return hstack([sparse_transformed, dense_transformed]), word_id_to_feature_ids
class SVMWordPredictor(BaseSklearnPredictor):
def __init__(
self,
classifier: SVMClassifier,
threshold: float = -1.5,
punct_as_words: str = PDFPlumberParser.DEFAULT_PUNCTUATION_CHARS.replace(
"-", ""
),
):
self.classifier = classifier
self.whitespace_predictor = WhitespacePredictor()
self.threshold = threshold
self.punct_as_words = punct_as_words
@classmethod
def from_path(cls, tar_path: str):
classifier = SVMClassifier.from_path(tar_path=tar_path)
predictor = SVMWordPredictor(classifier=classifier)
return predictor
@classmethod
def from_directory(cls, dir: str, threshold: float = -1.5):
classifier = SVMClassifier.from_directory(dir=dir)
predictor = SVMWordPredictor(classifier=classifier, threshold=threshold)
return predictor
def predict(self, document: Document) -> List[SpanGroup]:
# clean input
document = self._make_clean_document(document=document)
# validate input
self._validate_tokenization(document=document)
# initialize output data using whitespace tokenization
# also avoid grouping specific punctuation. each instance should be their own word.
(
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) = self._predict_with_whitespace(document=document)
self._validate_token_word_assignments(word_id_to_token_ids=word_id_to_token_ids)
# split up words back into tokens based on punctuation
(
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) = self._keep_punct_as_words(
document=document,
word_id_to_token_ids=word_id_to_token_ids,
punct_as_words=self.punct_as_words,
)
self._validate_token_word_assignments(word_id_to_token_ids=word_id_to_token_ids)
# get hyphen word candidates
hyphen_word_candidates = self._find_hyphen_word_candidates(
tokens=document.tokens,
token_id_to_word_id=token_id_to_word_id,
word_id_to_token_ids=word_id_to_token_ids,
word_id_to_text=word_id_to_text,
)
candidate_texts = [
word_id_to_text[prefix_word_id] + word_id_to_text[suffix_word_id]
for prefix_word_id, suffix_word_id in hyphen_word_candidates
]
# filter candidate texts
hyphen_word_candidates, candidate_texts = self._filter_word_candidates(
hyphen_word_candidates=hyphen_word_candidates,
candidate_texts=candidate_texts,
)
# only triggers if there are hyphen word candidates
if hyphen_word_candidates:
# classify hyphen words
results = self.classifier.batch_predict(
words=candidate_texts, threshold=self.threshold
)
# update output data based on hyphen word candidates
# first, we concatenate words based on prefix + suffix. this includes hyphen.
# second, we modify the text value (e.g. remove hyphens) if classifier says.
for (prefix_word_id, suffix_word_id), result in zip(
hyphen_word_candidates, results
):
impacted_token_ids = (
word_id_to_token_ids[prefix_word_id]
+ word_id_to_token_ids[suffix_word_id]
)
word_id_to_token_ids[prefix_word_id] = impacted_token_ids
word_id_to_token_ids.pop(suffix_word_id)
word_id_to_text[prefix_word_id] += word_id_to_text[suffix_word_id]
word_id_to_text.pop(suffix_word_id)
if result.is_edit is True:
word_id_to_text[prefix_word_id] = result.new
token_id_to_word_id = {
token_id: word_id
for word_id, token_ids in word_id_to_token_ids.items()
for token_id in token_ids
}
self._validate_token_word_assignments(
word_id_to_token_ids=word_id_to_token_ids
)
# make into spangroups
words = self._create_words(
document=document,
token_id_to_word_id=token_id_to_word_id,
word_id_to_text=word_id_to_text,
)
return words
def _make_clean_document(self, document: Document) -> Document:
"""Word predictor doesnt work on documents with poor tokenizations,
such as when there are empty tokens. This cleans up the document.
We keep this pretty minimal, such as ignoring Span Boxes since dont need
them for word prediction."""
new_tokens = []
current_id = 0
for token in document.tokens:
if token.text.strip() != "":
new_token = SpanGroup(
spans=[
Span(start=span.start, end=span.end) for span in token.spans
],
id=current_id,
)
new_tokens.append(new_token)
current_id += 1
new_doc = Document(symbols=document.symbols)
new_doc.annotate(tokens=new_tokens)
return new_doc
def _recursively_remove_trailing_hyphens(self, word: str) -> str:
if word.endswith("-"):
return self._recursively_remove_trailing_hyphens(word=word[:-1])
else:
return word
def _validate_tokenization(self, document: Document):
"""This Word Predictor relies on a specific type of Tokenization
in which hyphens ('-') must be their own token. This verifies.
Additionally, doesnt work unless there's an `.id` field on each token.
See `_cluster_tokens_by_whitespace()` for more info.
"""
for token in document.tokens:
if "-" in token.text and token.text != "-":
raise ValueError(
f"Document contains Token with hyphen, but not as its own token."
)
if token.id is None:
raise ValueError(
f"Document contains Token without an `.id` field, which is necessary for this word Predictor's whitespace clustering operation."
)
if token.text.strip() == "":
raise ValueError(
f"Document contains Token with empty text, which is not allowed."
)
def _validate_token_word_assignments(
self, word_id_to_token_ids, allow_missed_tokens: bool = True
):
for word_id, token_ids in word_id_to_token_ids.items():
start = min(token_ids)
end = max(token_ids)
assert (
len(token_ids) == end - start + 1
), f"word={word_id} comprised of disjoint token_ids={token_ids}"
if not allow_missed_tokens:
all_token_ids = {
token_id
for token_id in word_id_to_token_ids.values()
for token_id in token_ids
}
if len(all_token_ids) < max(all_token_ids):
raise ValueError(f"Not all tokens are assigned to a word.")
def _cluster_tokens_by_whitespace(self, document: Document) -> List[List[int]]:
"""
`whitespace_tokenization` is necessary because lack of whitespace is an indicator that
adjacent tokens belong in a word together.
"""
_ws_tokens: List[SpanGroup] = self.whitespace_predictor.predict(
document=document
)
document.annotate(_ws_tokens=_ws_tokens)
# token -> ws_tokens
token_id_to_ws_token_id = {}
for token in document.tokens:
overlap_ws_tokens = token._ws_tokens
if overlap_ws_tokens:
token_id_to_ws_token_id[token.id] = overlap_ws_tokens[0].id
# ws_token -> tokens
ws_token_id_to_tokens = defaultdict(list)
for token_id, ws_token_id in token_id_to_ws_token_id.items():
ws_token_id_to_tokens[ws_token_id].append(token_id)
# cluster tokens by whitespace
clusters = [
sorted(ws_token_id_to_tokens[ws_token_id])
for ws_token_id in range(len(ws_token_id_to_tokens))
]
# cleanup
document.remove("_ws_tokens")
return clusters
def _predict_with_whitespace(self, document: Document):
"""Predicts word boundaries using whitespace tokenization."""
# precompute whitespace tokenization
whitespace_clusters = self._cluster_tokens_by_whitespace(document=document)
# assign word ids
token_id_to_word_id = {}
word_id_to_token_ids = defaultdict(list)
for word_id, token_ids_in_cluster in enumerate(whitespace_clusters):
for token_id in token_ids_in_cluster:
token_id_to_word_id[token_id] = word_id
word_id_to_token_ids[word_id].append(token_id)
# get word strings
word_id_to_text = {}
for word_id, token_ids in word_id_to_token_ids.items():
word_id_to_text[word_id] = "".join(
document.tokens[token_id].text for token_id in token_ids
)
return token_id_to_word_id, word_id_to_token_ids, word_id_to_text
def _keep_punct_as_words(
self, document: Document, word_id_to_token_ids: Dict, punct_as_words: str
):
# keep track of which tokens are punctuation
token_ids_are_punct = set()
for token_id, token in enumerate(document.tokens):
if token.text in punct_as_words:
token_ids_are_punct.add(token_id)
# re-cluster punctuation tokens into their own words
new_clusters = []
for old_cluster in word_id_to_token_ids.values():
for new_cluster in self._group_adjacent_with_exceptions(
adjacent=old_cluster, exception_ids=token_ids_are_punct
):
new_clusters.append(new_cluster)
# reorder
new_clusters = sorted(new_clusters, key=lambda x: min(x))
# reassign word ids
new_token_id_to_word_id = {}
new_word_id_to_token_ids = defaultdict(list)
for word_id, token_ids_in_cluster in enumerate(new_clusters):
for token_id in token_ids_in_cluster:
new_token_id_to_word_id[token_id] = word_id
new_word_id_to_token_ids[word_id].append(token_id)
# get word strings
new_word_id_to_text = {}
for word_id, token_ids in new_word_id_to_token_ids.items():
new_word_id_to_text[word_id] = "".join(
document.tokens[token_id].text for token_id in token_ids
)
return new_token_id_to_word_id, new_word_id_to_token_ids, new_word_id_to_text
def _group_adjacent_with_exceptions(
self, adjacent: List[int], exception_ids: Set[int]
) -> List[List[int]]:
result = []
group = []
for e in adjacent:
if e in exception_ids:
if group:
result.append(group)
result.append([e])
group = []
else:
group.append(e)
if group:
result.append(group)
return result
def _find_hyphen_word_candidates(
self,
tokens,
token_id_to_word_id,
word_id_to_token_ids,
word_id_to_text,
) -> Tuple[int, int]:
"""Finds the IDs of hyphenated words (in prefix + suffix format)."""
# get all hyphen tokens
# TODO: can refine this further by restricting to only tokens at end of `rows`
hyphen_token_ids = []
for token_id, token in enumerate(tokens):
if token.text == "-":
hyphen_token_ids.append(token_id)
# get words that contain hyphen token, but only at the end (i.e. broken word)
# these form the `prefix` of a potential hyphenated word
#
# edge case: sometimes the prefix word is *just* a hyphen. this means the word
# itself is actually just a hyphen (e.g. like in tables of results)
# dont consider these as candidates
prefix_word_ids = set()
for hyphen_token_id in hyphen_token_ids:
prefix_word_id = token_id_to_word_id[hyphen_token_id]
prefix_word_text = word_id_to_text[prefix_word_id]
if prefix_word_text.endswith("-") and not prefix_word_text == "-":
prefix_word_ids.add(prefix_word_id)
# get words right after the prefix (assumed words in reading order)
# these form the `suffix` of a potential hyphenated word
# together, a `prefix` and `suffix` form a candidate pair
#
# edge case: sometimes the token stream ends with a hyphenated
# word. this means suffix_word_id wont exist. dont consider these
word_id_pairs = []
for prefix_word_id in prefix_word_ids:
suffix_word_id = prefix_word_id + 1
suffix_word_text = word_id_to_text.get(suffix_word_id)
if suffix_word_text is None:
continue
word_id_pairs.append((prefix_word_id, suffix_word_id))
return sorted(word_id_pairs)
def _filter_word_candidates(
self, hyphen_word_candidates: list, candidate_texts: list
) -> tuple:
hyphen_word_candidates_filtered = []
candidate_texts_filtered = []
for hyphen_word_candidate, candidate_text in zip(
hyphen_word_candidates, candidate_texts
):
if candidate_text.endswith("-") or candidate_text.startswith("-"):
continue
else:
hyphen_word_candidates_filtered.append(hyphen_word_candidate)
candidate_texts_filtered.append(candidate_text)
return hyphen_word_candidates_filtered, candidate_texts_filtered
def _create_words(
self, document: Document, token_id_to_word_id, word_id_to_text
) -> List[SpanGroup]:
words = []
tokens_in_word = [document.tokens[0]]
current_word_id = 0
new_word_id = 0
for token_id in range(1, len(document.tokens)):
token = document.tokens[token_id]
word_id = token_id_to_word_id.get(token_id)
if word_id is None:
logger.debug(
f"Token {token_id} has no word ID. Likely PDF Parser produced empty tokens."
)
continue
if word_id == current_word_id:
tokens_in_word.append(token)
else:
spans = [
Span.small_spans_to_big_span(
spans=[
span for token in tokens_in_word for span in token.spans
],
merge_boxes=False,
)
]
metadata = (
Metadata(text=word_id_to_text[current_word_id])
if len(tokens_in_word) > 1
else None
)
word = SpanGroup(
spans=spans,
id=new_word_id,
metadata=metadata,
)
words.append(word)
tokens_in_word = [token]
current_word_id = word_id
new_word_id += 1
# last bit
spans = [
Span.small_spans_to_big_span(
spans=[span for token in tokens_in_word for span in token.spans],
merge_boxes=False,
)
]
metadata = (
Metadata(text=word_id_to_text[current_word_id])
if len(tokens_in_word) > 1
else None
)
word = SpanGroup(
spans=spans,
id=new_word_id,
metadata=metadata,
)
words.append(word)
new_word_id += 1
return words
| 23,546 | 38.376254 | 148 |
py
|
mmda
|
mmda-main/src/mmda/predictors/sklearn_predictors/base_sklearn_predictor.py
|
from abc import abstractmethod
from typing import Any, Dict, List, Union
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.types.document import Document
class BaseSklearnPredictor(BasePredictor):
REQUIRED_BACKENDS = ["sklearn", "numpy", "scipy", "tokenizers"]
@classmethod
def from_path(cls, tar_path: str):
raise NotImplementedError
| 392 | 27.071429 | 72 |
py
|
mmda
|
mmda-main/src/mmda/predictors/xgb_predictors/citation_link_predictor.py
|
from scipy.stats import rankdata
import numpy as np
import os
import pandas as pd
from typing import List, Dict, Tuple
import xgboost as xgb
from mmda.types.document import Document
from mmda.featurizers.citation_link_featurizers import CitationLink, featurize
class CitationLinkPredictor:
def __init__(self, artifacts_dir: str, threshold):
full_model_path = os.path.join(artifacts_dir, "links_v1.json")
model = xgb.XGBClassifier()
model.load_model(full_model_path)
self.model = model
self.threshold = threshold
# returns a paired mention id and bib id to represent a link
def predict(self, doc: Document) -> List[Tuple[str, str]]:
if len(doc.bibs) == 0:
return []
predicted_links = []
# iterate over mentions
for mention in doc.mentions:
# create all possible links for this mention
possible_links = []
for bib in doc.bibs:
link = CitationLink(mention = mention, bib = bib)
possible_links.append(link)
# featurize and find link with highest score
X_instances = featurize(possible_links)
y_pred = self.model.predict_proba(X_instances)
match_scores = [pred[1] for pred in y_pred] # probability that label is 1
match_index = np.argmax(match_scores)
selected_link = possible_links[match_index]
if match_scores[match_index] < self.threshold: continue
predicted_links.append((selected_link.mention.id, selected_link.bib.id))
return predicted_links
| 1,620 | 34.23913 | 85 |
py
|
mmda
|
mmda-main/src/mmda/predictors/xgb_predictors/section_nesting_predictor.py
|
"""
SectionNestingPredictor -- Use token-level predictions for "Section" to predict the
parent-child relationships between sections.
Adapted from https://github.com/rauthur/section-annotations-gold
@rauthur
"""
import json
import logging
import re
from collections import OrderedDict
from copy import deepcopy
from dataclasses import dataclass
from functools import cached_property
from typing import Dict, List, Optional, Sequence, Tuple
import numpy as np
import xgboost as xgb
from mmda.predictors.base_predictors.base_predictor import BasePredictor
from mmda.types.annotation import SpanGroup
from mmda.types.box import Box
from mmda.types.document import Document
from mmda.types.names import PagesField, SectionsField
@dataclass
class Example:
parent_id: int
parent_text: str
parent_is_root: bool
child_id: int
child_text: str
parent_no_font_size: bool
child_no_font_size: bool
is_one_size_larger_font: bool
same_font: bool
parent_bold_font: bool
child_bold_font: bool
normalized_page_distance: float
on_same_page: bool
relative_y_pos: int
relative_x_pos: int
abs_x_diff_pos: float
abs_y_diff_pos: float
parent_has_num_prefix: bool
child_has_num_prefix: bool
child_num_prefix_is_top_level: bool
parent_prefix_is_implied_parent_of_child_prefix: bool
child_text_starts_with_something_ending_with_a_period: bool
child_is_top_level_keyword: bool
child_is_all_caps: bool
child_starts_with_upper_letter_prefix: bool
parent_text_starts_with_something_ending_with_a_period: bool
parent_is_top_level_keyword: bool
parent_is_all_caps: bool
parent_starts_with_upper_letter_prefix: bool
@dataclass
class _FontInfo:
size: float
name: str
class PdfStats:
sections: Sequence[SpanGroup]
section_index: Dict[int, SpanGroup]
fontinfo_index: Dict[int, _FontInfo]
def __init__(self, sections) -> None:
self.sections = sections
self._build_section_index()
self._build_fontinfo_index()
def section(self, id_: int) -> SpanGroup:
return self.section_index[id_]
def section_fontsize(self, id_: int) -> float:
return self.fontinfo_index[id_].size
def section_fontname(self, id_: int) -> str:
return self.fontinfo_index[id_].name
def _build_section_index(self):
self.section_index = {s.id: s for s in self.sections}
def _build_fontinfo_index(self):
self.fontinfo_index = {}
for section in self.sections:
assert section.id is not None, "Sections must have an ID"
self.fontinfo_index[section.id] = _FontInfo(
size=self._round_size_with_default(section),
name=self._fontname_with_default(section),
)
@cached_property
def unique_fontsizes(self) -> List[float]:
sizes = {self._round_size_with_default(s) for s in self.sections}
return sorted([s for s in sizes if s > 0])
def _round_size_with_default(self, section: SpanGroup, default=-1) -> float:
return round(section.metadata.get("size", default), 4)
def _fontname_with_default(self, section: SpanGroup, default="[NONE]") -> str:
return section.metadata.get("fontname", default)
NUM_PREFIX_REGEX = "^([0-9\.]+)"
def num_prefix(s: str) -> Tuple[Optional[str], Optional[str]]:
m = re.search(NUM_PREFIX_REGEX, s)
if m is None:
return None, None
s = m.group(0)
if s.endswith("."):
s = s[:-1]
if "." in s:
p = ".".join(s.split(".")[:-1])
else:
p = None
return s, p
def child_text_starts_with_something_ending_with_a_period(
s: SpanGroup,
) -> bool:
if s.text is None:
return False
text = s.text.strip()
if "." not in text:
return False
parts = text.split(" ")
# There must be at least 2 words
if len(parts) <= 1:
return False
# Ensure there is 1 occurence of '.' at the end of the word
if not parts[0].endswith("."):
return False
if sum([1 if c == "." else 0 for c in parts[0]]) != 1:
return False
# Numbering should not be too long
if len(parts[0]) > 3:
return False
return True
_TOP_LEVEL_KEYWORDS = [
"abstract",
"introduction",
"conclusions",
"references",
"acknowledgements",
"methods",
"discussion",
"keywords",
"appendix",
]
def child_is_top_level_keyword(s: SpanGroup) -> bool:
if s.text is None:
return False
text = s.text.strip().lower()
# Trim any trailing punctuation like "Acknowledgements."
if text.endswith(".") or text.endswith(":"):
text = text[:-1]
if len(text) == 0:
return False
# Single-word by may have some prefix like "I. Introduction"
if len(text.split(" ")) > 2:
return False
for kw in _TOP_LEVEL_KEYWORDS:
if text.endswith(kw):
return True
return False
def child_is_all_caps(s: SpanGroup) -> bool:
if s.text is None:
return False
text = s.text.strip()
if len(text) == 0:
return False
return text.upper() == text
def child_starts_with_upper_letter_prefix(s: SpanGroup) -> bool:
if s.text is None:
return False
text = s.text.strip()
if len(text) == 0:
return False
parts = text.split(" ")
if len(parts) <= 1:
return False
if len(parts[0]) != 1:
return False
return parts[0] >= "A" and parts[0] <= "Z"
def span_group_page(span_group: SpanGroup) -> int:
if len(span_group.spans) == 0:
return -1
return span_group.spans[0].box.page
SPAN_GROUP_ROOT = SpanGroup(spans=[], id=-1)
def make_example(
pdf_stats: PdfStats,
a: SpanGroup,
b: SpanGroup,
num_pages: int,
) -> Example:
parent_is_root = a.id == -1
a_font_size = -1 if parent_is_root else pdf_stats.section_fontsize(a.id)
if a_font_size == -1:
parent_no_font_size = True
else:
parent_no_font_size = False
b_font_size = pdf_stats.section_fontsize(b.id)
if b_font_size == -1:
child_no_font_size = True
else:
child_no_font_size = False
if (not parent_no_font_size) and (not child_no_font_size):
a_font_index = pdf_stats.unique_fontsizes.index(a_font_size)
b_font_index = pdf_stats.unique_fontsizes.index(b_font_size)
assert a_font_index >= 0
assert b_font_index >= 0
is_one_size_larger_font = True if a_font_index - b_font_index == 1 else False
else:
is_one_size_larger_font = False
parent_prefix, _ = num_prefix(a.text)
child_prefix, implied_parent = num_prefix(b.text)
b_box = Box.small_boxes_to_big_box(boxes=[s.box for s in b.spans])
if parent_is_root:
a_box = Box(l=0, t=0, w=0, h=0, page=0)
relative_x_pos = -1
relative_y_pos = -1
a_font_name = "[ROOT]"
b_font_name = pdf_stats.section_fontname(b.id)
else:
a_box = Box.small_boxes_to_big_box(boxes=[s.box for s in a.spans])
relative_x_pos = 0
if a_box.l < b_box.l:
relative_x_pos = -1
elif b_box.l < a_box.l:
relative_x_pos = 1
relative_y_pos = 0
if a_box.t < b_box.t:
relative_y_pos = -1
elif b_box.t < a_box.t:
relative_y_pos = 1
a_font_name = pdf_stats.section_fontname(a.id)
b_font_name = pdf_stats.section_fontname(b.id)
a_page = span_group_page(a)
b_page = span_group_page(b)
return Example(
parent_id=a.id,
parent_text=a.text,
parent_is_root=parent_is_root,
child_id=b.id,
child_text=b.text,
parent_no_font_size=parent_no_font_size,
child_no_font_size=child_no_font_size,
same_font=a_font_name == b_font_name,
parent_bold_font="bold" in a_font_name.lower(),
child_bold_font="bold" in b_font_name.lower(),
is_one_size_larger_font=is_one_size_larger_font,
normalized_page_distance=(b_page - a_page) / num_pages,
on_same_page=a_page == b_page,
relative_x_pos=relative_x_pos,
relative_y_pos=relative_y_pos,
abs_x_diff_pos=abs(a_box.l - b_box.l),
abs_y_diff_pos=abs(a_box.t - b_box.t),
parent_has_num_prefix=not parent_prefix is None,
child_has_num_prefix=not child_prefix is None,
child_num_prefix_is_top_level=(
child_prefix is not None and implied_parent is None
),
parent_prefix_is_implied_parent_of_child_prefix=(
parent_prefix is not None and parent_prefix == implied_parent
),
child_text_starts_with_something_ending_with_a_period=child_text_starts_with_something_ending_with_a_period(
b
),
child_is_top_level_keyword=child_is_top_level_keyword(b),
child_is_all_caps=child_is_all_caps(b),
child_starts_with_upper_letter_prefix=child_starts_with_upper_letter_prefix(b),
parent_text_starts_with_something_ending_with_a_period=child_text_starts_with_something_ending_with_a_period(
a
),
parent_is_top_level_keyword=child_is_top_level_keyword(a),
parent_is_all_caps=child_is_all_caps(a),
parent_starts_with_upper_letter_prefix=child_starts_with_upper_letter_prefix(a),
)
@dataclass
class SectionNode:
prev: Optional["SectionNode"]
next: Optional["SectionNode"]
section: SpanGroup
class SectionIndex:
index: Dict[int, SectionNode]
def __init__(self) -> None:
self.index = OrderedDict()
self.index[-1] = SectionNode(
prev=None,
next=None,
section=SPAN_GROUP_ROOT,
)
def add(self, section: SpanGroup, parent_id: int):
if parent_id not in self.index:
raise ValueError("Cannot find parent!")
parent = self.index[parent_id]
curr = parent.next
while curr is not None:
currnext = curr.next
del self.index[curr.section.id]
del curr
curr = currnext
node = SectionNode(prev=parent, next=None, section=section)
parent.next = node
self.index[section.id] = node
def __str__(self) -> str:
curr = self.index[-1]
nodes = []
while curr is not None:
nodes.append(f"[{curr.section.id}] {curr.section.text}")
curr = curr.next
return " -> ".join(nodes)
def bf(b: bool):
return 1.0 if b else 0.0
def convert_example(x: Example):
return [
bf(x.is_one_size_larger_font),
bf(x.same_font),
bf(x.parent_no_font_size),
bf(x.child_no_font_size),
bf(x.parent_bold_font),
bf(x.child_bold_font),
x.normalized_page_distance,
bf(x.on_same_page),
x.relative_y_pos,
x.relative_x_pos,
x.abs_x_diff_pos,
x.abs_y_diff_pos,
bf(x.parent_has_num_prefix),
bf(x.child_has_num_prefix),
bf(x.child_num_prefix_is_top_level),
bf(x.parent_prefix_is_implied_parent_of_child_prefix),
bf(x.parent_is_root),
bf(x.child_text_starts_with_something_ending_with_a_period),
bf(x.child_is_top_level_keyword),
bf(x.child_is_all_caps),
bf(x.child_starts_with_upper_letter_prefix),
bf(x.parent_text_starts_with_something_ending_with_a_period),
bf(x.parent_is_top_level_keyword),
bf(x.parent_is_all_caps),
bf(x.parent_starts_with_upper_letter_prefix),
]
class SectionNestingPredictor(BasePredictor):
REQUIRED_BACKENDS = None
REQUIRED_DOCUMENT_FIELDS = [SectionsField, PagesField]
def __init__(self, model_file: str) -> None:
super().__init__()
self.model = xgb.XGBClassifier()
self.model.load_model(model_file)
def predict(self, document: Document) -> List[SpanGroup]:
sections = document.sections
if len(sections) == 0:
return []
index = SectionIndex()
pdf_stats = PdfStats(sections)
results = []
for section in sections:
xs = []
# FIXME: Debugging only?
parent_texts = []
parent_ids = []
for node in index.index.values():
x = make_example(pdf_stats, node.section, section, len(document.pages))
xs.append(convert_example(x))
parent_texts.append(node.section.text)
parent_ids.append(node.section.id)
logging.debug("SECTION: %s [%i]", section.text, section.id)
logging.debug("CANDIDATES: %s", json.dumps(parent_texts))
pos_probs = self.model.predict_proba(xs)[:, 1]
pos_probs = pos_probs / sum(pos_probs)
pos_index = np.argmax(pos_probs)
logging.debug(json.dumps([float(round(p, 4)) for p in pos_probs]))
logging.debug(f"Picked {parent_texts[pos_index]}!")
parent_id = parent_ids[pos_index]
# Maintain the text from VILA for each span group
metadata = deepcopy(section.metadata)
metadata.parent_id = parent_id
results.append(
SpanGroup(
spans=deepcopy(section.spans),
box_group=deepcopy(section.box_group),
id=deepcopy(section.id), # Ensure some ID is created
doc=None, # Allows calling doc.annotate(...)
metadata=metadata,
)
)
index.add(section, parent_ids[pos_index])
return results
| 13,683 | 26.813008 | 117 |
py
|
mmda
|
mmda-main/src/mmda/predictors/xgb_predictors/__init__.py
| 0 | 0 | 0 |
py
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.