code stringlengths 17 6.64M |
|---|
class SqueezeExpandDilatedDecoder(nn.Module):
def __init__(self, in_channels, num_classes, inter_channels, feature_scales, foreground_channel=False, ConvType=nn.Conv3d, PoolType=nn.AvgPool3d, NormType=nn.Identity):
super().__init__()
assert (tuple(feature_scales) == (4, 8, 16, 32))
Poolin... |
class ExponentialLR(torch.optim.lr_scheduler._LRScheduler):
'Decays the learning rate of each parameter group by gamma every epoch.\n When last_epoch=-1, sets initial lr as lr.\n\n Args:\n optimizer (Optimizer): Wrapped optimizer.\n last_epoch (int): The index of last epoch. Default: -1.\n ... |
class InterruptException(RuntimeError):
def __init__(self, *args):
super(self.__class__, self).__init__(*args)
|
class InterruptDetector():
def __init__(self):
self.__is_interrupted = False
def start(self):
signal.signal(signal.SIGINT, self.__set_interrupted)
signal.signal(signal.SIGTERM, self.__set_interrupted)
def __set_interrupted(self, signum, frame):
self.__is_interrupted = Tr... |
def parse_args(parser):
assert isinstance(parser, ArgumentParser)
args = parser.parse_args()
(pos_group, optional_group) = (parser._action_groups[0], parser._action_groups[1])
args_dict = args._get_kwargs()
pos_optional_arg_names = ([arg.dest for arg in pos_group._group_actions] + [arg.dest for ar... |
class Trainer(object):
def __init__(self, cfg, model_save_dir, args, logger):
self.num_gpus = dist_utils.get_world_size()
self.local_rank = dist_utils.get_rank()
self.local_device = dist_utils.get_device()
self.is_main_process = dist_utils.is_main_process()
self.console_lo... |
def create_logger(args):
logger = logging.getLogger('MaskTCNNTrainLogger')
if dist_utils.is_main_process():
logger.setLevel(args.log_level)
else:
logger.setLevel(args.subprocess_log_level)
ch = logging.StreamHandler()
formatter = logging.Formatter('[%(proc_id)d] %(asctime)s - %(lev... |
def setup_cfg(args, model_dir, ignore_existing_cfg):
if args.cfg:
print('[ INFO] Loading config from {}'.format(args.cfg))
global_cfg.merge_from_file(args.cfg)
return
if ignore_existing_cfg:
return
if args.restore_session:
expected_config_filepath = os.path.realpath... |
def start(args, cfg):
if (dist_utils.get_rank() > 0):
warnings.filterwarnings('ignore')
logger = create_logger(args)
model_save_dir = os.path.join(ModelPaths.checkpoint_base_dir(), cfg.MODE, args.model_dir)
if dist_utils.is_main_process():
os.makedirs(model_save_dir, exist_ok=True)
... |
def init_distributed(args, cfg, num_gpus):
os.environ['MASTER_ADDR'] = 'localhost'
os.environ['MASTER_PORT'] = (args.master_port if args.master_port else '12356')
timeout = timedelta(0, 25)
dist.init_process_group('nccl', rank=args.local_rank, world_size=num_gpus, timeout=timeout)
try:
sta... |
def main(args):
if os.path.isabs(args.cfg):
cfg_path = args.cfg
else:
cfg_path = os.path.join(RepoPaths.configs_dir(), args.cfg)
print('Restoring config from: {}'.format(cfg_path))
global_cfg.merge_from_file(cfg_path)
num_gpus = torch.cuda.device_count()
if (args.allow_multigpu... |
class ModelOutputManager(object):
def __init__(self, division_factor, excluded_keys=()):
self.division_factor = float(division_factor)
self.tensor_vars = defaultdict((lambda : 0.0))
self.other_vars = defaultdict((lambda : 0.0))
self.excluded_keys = excluded_keys
@torch.no_gra... |
class TrainingLogger(object):
def __init__(self, output_dir, num_iterations=None):
self.total_iterations = num_iterations
self.output_dir = output_dir
os.makedirs(self.output_dir, exist_ok=True)
self.__writer = tensorboardX.SummaryWriter(self.output_dir)
self.__train_start... |
def var_keys_to_str(losses):
s = ''
for (k, v) in losses.items():
if (k == 'lr'):
s += 'LR: {:.2E} - '.format(v)
else:
s += '{:s}: {:.3f} - '.format(_VAR_KEY_TO_DISP_STR[k], v)
return s[:(- 3)]
|
def register_log_level_type(parser):
def str2LogLevel(v):
if (v.lower() == 'fatal'):
return logging.FATAL
elif (v.lower() == 'critical'):
return logging.CRITICAL
elif (v.lower() == 'error'):
return logging.ERROR
elif (v.lower() in ('warn', 'warn... |
def create_concat_dataset_for_davis(total_samples, print_fn):
if (print_fn is None):
print_fn = print
print_fn('Creating training dataset for Davis...')
assert (cfg.INPUT.NUM_CLASSES == 2)
datasets = []
ds_weights = []
ds_names = []
ds_cfg = cfg.DATA.DAVIS
datasets.append(CocoD... |
def create_concat_dataset_for_youtube_vis(total_samples, print_fn):
if (print_fn is None):
print_fn = print
print_fn('Creating training dataset for YouTube-VIS...')
assert (cfg.INPUT.NUM_CLASSES == 41)
datasets = []
ds_weights = []
ds_names = []
ds_cfg = cfg.DATA.YOUTUBE_VIS
da... |
def create_concat_dataset_for_kitti_mots(total_samples, print_fn=None):
if (print_fn is None):
print_fn = print
print_fn('Creating training dataset for KITTI-MOTS...')
assert (cfg.INPUT.NUM_CLASSES == 3)
datasets = []
ds_weights = []
ds_names = []
ds_cfg = cfg.DATA.KITTI_MOTS
i... |
def create_training_dataset(total_samples, print_fn=None):
dataset_creation_fns = {'davis': create_concat_dataset_for_davis, 'youtube_vis': create_concat_dataset_for_youtube_vis, 'kitti_mots': create_concat_dataset_for_kitti_mots}
try:
return dataset_creation_fns[cfg.TRAINING.MODE](total_samples, prin... |
def create_optimizer(model, cfg, print_fn=None):
if (print_fn is None):
print_fn = print
if (cfg.OPTIMIZER.lower() == 'sgd'):
optimizer = torch.optim.SGD(model.parameters(), cfg.INITIAL_LR, cfg.MOMENTUM, weight_decay=cfg.WEIGHT_DECAY, nesterov=cfg.NESTEROV)
print_fn('Using SGD optimize... |
def create_lr_scheduler(optimizer, cfg, print_fn=None):
if (print_fn is None):
print_fn = print
if (cfg.LR_DECAY_TYPE == 'step'):
lr_scheduler = lrs.MultiStepLR(optimizer, cfg.LR_DECAY_STEPS, cfg.LR_DECAY_FACTOR)
print_fn('Multistep LR decay at {} steps with decay factor {}'.format(cfg... |
def create_training_data_loader(dataset, batch_size, shuffle, collate_fn=None, num_workers=0, elapsed_iters=0):
is_distributed = dist_utils.is_distributed()
if is_distributed:
sampler = CustomDistributedSampler(dataset, dist_utils.get_world_size(), dist_utils.get_rank(), shuffle)
elif shuffle:
... |
class Loss(object):
EMBEDDING_VARIANCE = 'embedding_variance_loss'
EMBEDDING_DISTANCE = 'embedding_distance_loss'
EMBEDDING = 'embedding_loss'
SEMSEG = 'semantic_segmentation_loss'
AUXILIARY = 'auxiliary'
EIGENVALUE_RATIO = 'eigenvalue_ratio_loss'
LOVASZ_LOSS = 'lovasz_loss'
SEEDINESS_... |
class ModelOutput(object):
TRACKER_INPUT_FEATURES = ('tracker_input_features',)
SEMSEG_MASKS = ('semseg_masks',)
EMBEDDINGS = ('embeddings',)
EMBEDDING_VARIANCES = 'variances'
SEEDINESS_MAP = 'seediness_map'
EMBEDDING_OFFSETS = 'embedding_offsets'
MASK_GRADIENTS = 'mask_gradients'
OFFS... |
class RepoPaths(object):
def __init__(self):
raise ValueError("Static class 'RepoPaths' should not be instantiated")
@staticmethod
def dataset_meta_info_dir():
return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir, 'data', 'metainfo'))
@staticmethod
def confi... |
def is_distributed():
if (not dist.is_available()):
return False
return dist.is_initialized()
|
def get_world_size():
if (not dist.is_available()):
return 1
if (not dist.is_initialized()):
return 1
return dist.get_world_size()
|
def get_rank():
if (not dist.is_available()):
return 0
if (not dist.is_initialized()):
return 0
return dist.get_rank()
|
def is_main_process():
return (get_rank() == 0)
|
def get_device():
return 'cuda:{}'.format(get_rank())
|
def synchronize():
'\n Helper function to synchronize (barrier) among all processes when\n using distributed training\n '
if (not dist.is_available()):
return
if (not dist.is_initialized()):
return
world_size = dist.get_world_size()
if (world_size == 1):
return
... |
def all_gather(data):
'\n Run all_gather on arbitrary picklable data (not necessarily tensors)\n Args:\n data: any picklable object\n Returns:\n list[data]: list of data gathered from each rank\n '
world_size = get_world_size()
if (world_size == 1):
return [data]
buff... |
def reduce_dict(input_dict, average=True):
'\n Args:\n input_dict (dict): all the values will be reduced\n average (bool): whether to do average or sum\n Reduce the values in the dictionary from all processes so that process with rank\n 0 has the averaged results. Returns a dict with the sa... |
class GlobalRegistry(object):
'\n A helper class for managing registering object types and accessing them from somewhere else in the project.\n\n Eg. creating a registry:\n some_registry = GlobalRegistry.get("registry_name")\n\n There\'re two ways of registering new modules:\n 1): normal way is... |
def _get_env_var(varname):
value = os.getenv(varname)
if (not value):
raise EnvironmentError("Required environment variable '{}' is not set.".format(varname))
return value
|
class ModelPaths(object):
def __init__(self):
pass
@staticmethod
def checkpoint_base_dir():
return os.path.join(_get_env_var('STEMSEG_MODELS_DIR'), 'checkpoints')
@staticmethod
def pretrained_backbones_dir():
return os.path.join(_get_env_var('STEMSEG_MODELS_DIR'), 'pretr... |
class Timer(object):
_TIMERS = dict()
def __init__(self, name):
self._name = name
self.__tic_time = None
self.__total_duration = 0.0
def __enter__(self):
self.tic()
def __exit__(self, exc_type, exc_val, exc_tb):
self.toc()
def tic(self):
assert (... |
class _CVTransformBase(object):
def __init__(self, name):
self.name = name
|
class Identity(_CVTransformBase):
def __init__(self):
super(self.__class__, self).__init__('identity')
def __call__(self, image):
return image
|
class ReverseColorChannels(_CVTransformBase):
def __init__(self, format='HWC'):
super(self.__class__, self).__init__('reverse color channels')
if (format == 'HWC'):
self.dim = 2
elif (format == 'CHW'):
self.dim = 0
else:
raise ValueError("Invali... |
class Normalize(_CVTransformBase):
def __init__(self, norm_factor, mean, std):
super(self.__class__, self).__init__('normalize')
self.__norm_factor = np.float32(norm_factor)
self.__mean = np.array([[mean]], np.float32)
self.__std = np.array([[std]], np.float32)
def __call__(s... |
class ReverseNormalize(_CVTransformBase):
def __init__(self, norm_factor, mean, std, dtype=np.uint8):
super(self.__class__, self).__init__('reverse normalize')
self.__norm_factor = np.float32(norm_factor)
self.__mean = np.array([[mean]], np.float32)
self.__std = np.array([[std]], ... |
class ToTorchTensor(_CVTransformBase):
def __init__(self, format='HWC', dtype=None):
super(self.__class__, self).__init__('to torch tensor')
assert (format in ['HWC', 'CHW'])
self.format = format
self.dtype = dtype
def __call__(self, image):
tensor = torch.from_numpy(... |
class Compose(_CVTransformBase):
def __init__(self, transforms):
super(self.__class__, self).__init__('composition')
self.__transforms = transforms
def __call__(self, image):
for transform in self.__transforms:
image = transform(image)
return image
|
class BatchImageTransform(_CVTransformBase):
def __init__(self, transform):
super(self.__class__, self).__init__('batch image transform')
self.__transform = transform
def __call__(self, *images):
return [self.__transform(image) for image in images]
|
def create_color_map(N=256, normalized=False):
def bitget(byteval, idx):
return ((byteval & (1 << idx)) != 0)
dtype = ('float32' if normalized else 'uint8')
cmap = np.zeros((N, 3), dtype=dtype)
for i in range(N):
r = g = b = 0
c = i
for j in range(8):
r = (... |
def overlay_mask_on_image(image, mask, mask_opacity=0.6, mask_color=(0, 255, 0)):
if (mask.ndim == 3):
assert (mask.shape[2] == 1)
_mask = mask.squeeze(axis=2)
else:
_mask = mask
mask_bgr = np.stack((_mask, _mask, _mask), axis=2)
masked_image = np.where((mask_bgr > 0), mask_col... |
def act_layer(act_type, inplace=False, neg_slope=0.2, n_prelu=1):
'\n '
act_type = act_type.lower()
if (act_type == 'relu'):
layer = nn.ReLU(inplace)
elif (act_type == 'leakyrelu'):
layer = nn.LeakyReLU(neg_slope, inplace)
elif (act_type == 'prelu'):
layer = nn.PReLU(num... |
def norm_layer(norm_type, nc):
'\n '
norm_type = norm_type.lower()
if (norm_type == 'batch'):
layer = nn.BatchNorm1d(nc, affine=True)
elif (norm_type == 'instance'):
layer = nn.InstanceNorm1d(nc, affine=False)
else:
raise NotImplementedError(('normalization layer [%s] is... |
class MLPConv(nn.Sequential):
def __init__(self, channels, act_type='relu', norm_type='batch', bias=True):
m = []
for i in range(1, len(channels)):
m.append(nn.Conv1d(channels[(i - 1)], channels[i], kernel_size=1, bias=bias))
if norm_type:
m.append(norm_lay... |
class MLPLinear(nn.Sequential):
def __init__(self, channels, act_type='relu', norm_type='batch', bias=True):
m = []
for i in range(1, len(channels)):
m.append(nn.Linear(channels[(i - 1)], channels[i], bias))
if (norm_type and (norm_type != 'None')):
m.appen... |
class MultiSeq(nn.Sequential):
def __init__(self, *args):
super(MultiSeq, self).__init__(*args)
def forward(self, *inputs):
for module in self._modules.values():
if (type(inputs) == tuple):
inputs = module(*inputs)
else:
inputs = module... |
class MRConv(MessagePassing):
def __init__(self, nn, aggr='max', **kwargs):
super(MRConv, self).__init__(aggr=aggr, **kwargs)
self.nn = nn
self.reset_parameters()
def reset_parameters(self):
reset(self.nn)
def forward(self, x, edge_index):
''
x = (x.unsqu... |
class EdgeConv2(MessagePassing):
def __init__(self, nn, aggr='max', **kwargs):
super(EdgeConv2, self).__init__(aggr=aggr, **kwargs)
self.nn = nn
self.reset_parameters()
def reset_parameters(self):
reset(self.nn)
def forward(self, x, edge_index):
''
x = (x... |
class SAGEConv2(MessagePassing):
def __init__(self, local_nn, global_nn, aggr='max', **kwargs):
super(SAGEConv2, self).__init__(aggr=aggr, **kwargs)
self.local_nn = local_nn
self.global_nn = global_nn
self.reset_parameters()
def reset_parameters(self):
reset(self.loca... |
def eval_unalign_batch1(model, loader):
'\n batch_size must be 1\n return:\n predictList: (N, Px)\n lossList: (N, )\n '
predictList = []
lossList = []
for data in loader:
(loss, out) = model.test(data, if_eval=True)
lossList.append(loss.item())
predictList.app... |
def eval_align_batchN(model, loader, P=256):
'\n return:\n predictList: (N, P) e.g. (N, 256)\n lossList: (B, )\n '
predictList = []
lossList = []
for data in loader:
(loss, out) = model.test(data, if_eval=True)
lossList.append(loss.item())
predictList.extend(out.... |
def get_eval_result(test_data, predict):
for (i, data) in enumerate(test_data):
predict_result = predict[i]
sketch = data['drawing']
for stroke in sketch:
label_num = len(stroke[2])
stroke[2] = predict_result[:label_num]
predict_result = predict_result[l... |
def eval_without_len(testData, predict):
p_metric_list = []
c_metric_list = []
for (i, data) in enumerate(testData):
predict_result = predict[i]
p_right = 0
p_sum = len(predict_result)
sketch = data['drawing']
c_right = 0
c_sum = len(sketch)
for (j, ... |
def eval_with_len(testData, predict):
p_metric_list = []
c_metric_list = []
for (i, data) in enumerate(testData):
predict_result = predict[i]
p_right = 0
p_sum = 0
sketch = data['drawing']
c_right = 0
c_sum = 0
for stroke in sketch:
if (s... |
def run_eval(opt=None, model=None, loader=None, dataset='test', write_result=False):
if (opt is None):
opt = TestOptions().parse()
if (model is None):
model = SketchModel(opt)
if (loader is None):
loader = load_data(opt, datasetType=dataset, permutation=opt.permutation)
if (opt... |
class SketchModel():
def __init__(self, opt):
self.opt = opt
self.is_train = opt.is_train
self.gpu_ids = opt.gpu_ids
self.device = (torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu'))
self.save_dir = os.path.join(opt.checkpoints_dir, o... |
def mkdir(path):
if (not os.path.exists(path)):
os.makedirs(path)
|
def set_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cuda.benchmark = False
np.random.seed(seed)
random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed)
|
class BaseOptions():
def __init__(self):
self.parser = argparse.ArgumentParser()
self.initialized = False
def initialize(self):
self.parser.add_argument('--class-name', type=str, required=True, help='the name of the class to train or test')
self.parser.add_argument('--points-... |
class TrainOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--epoch', type=int, default=100, help='epoch')
self.parser.add_argument('--lr', type=float, default=0.002, help='initial learning rate for adam')
self.parser.add_argument(... |
class TestOptions(BaseOptions):
def initialize(self):
BaseOptions.initialize(self)
self.parser.add_argument('--timestamp', type=str, default='-', help='the timestep of the model')
self.parser.add_argument('--print-freq', type=int, default=2, help='frequency of showing training results on ... |
def removeSinglePoint(data):
newData = []
for stroke in data:
if (len(stroke[0]) > 1):
newData.append(stroke)
return newData
|
def findMinMaxPoint(data):
'\n data: [[[x0,x1,x2,...],[y0,y1,y2,...]] * storke_number]\n '
minX = min(list(map((lambda x: min(x[0])), data)))
maxX = max(list(map((lambda x: max(x[0])), data)))
minY = min(list(map((lambda x: min(x[1])), data)))
maxY = max(list(map((lambda x: max(x[1])), data)... |
def centeredSketch(data):
'\n data: [[[x0,x1,x2,...],[y0,y1,y2,...]] * storke_number]\n '
def centered(data, scale, old_center, new_center):
centered_data = []
for stroke in data:
x = list(map((lambda x: int((((x - old_center[0]) * scale) + new_center[0]))), stroke[0]))
... |
def rotate_theta(data, theta):
'\n '
m = np.array([[math.cos(theta), math.sin(theta)], [(- math.sin(theta)), math.cos(theta)]])
rotated_data = []
for stroke in data:
label = stroke[2]
stroke_data = np.matmul(m, np.array(stroke[:2])).tolist()
stroke_data.append(label)
... |
def add_normal_noise(data, scale=1.0):
noise_data = []
for stroke in data:
label = stroke[2]
stroke_data = np.array(stroke[:2])
stroke_data += (scale * np.random.randn(*stroke_data.shape)).astype(np.int32)
stroke_data = stroke_data.tolist()
stroke_data.append(label)
... |
def set_seed(seed):
np.random.seed(seed)
|
def dislocate_stroke(stroke, ranges):
if (ranges == 0):
return
random_range = int((256 * ranges))
offset_x = np.random.randint((- random_range), random_range)
offset_y = np.random.randint((- random_range), random_range)
stroke[0] = list(map((lambda x: (x + offset_x)), stroke[0]))
strok... |
def dislocate(sketch, percent, ranges):
stroke_num = len(sketch)
dislocate_stroke_num = int((stroke_num * percent))
idxs = np.random.choice(stroke_num, dislocate_stroke_num, replace=False)
for idx in idxs:
dislocate_stroke(sketch[idx], ranges)
label = list(map((lambda s: s[2][0]), sketch))... |
def mkdir(path):
if (not os.path.exists(path)):
os.makedirs(path)
|
def run_train(train_params=None, test_params=None):
opt = TrainOptions().parse(train_params)
testopt = TestOptions().parse(test_params)
testopt.timestamp = opt.timestamp
testopt.batch_size = 30
model = SketchModel(opt)
model.print_detail()
writer = Writer(opt)
trainDataloader = load_da... |
def mkdir(path):
if (not os.path.exists(path)):
os.makedirs(path)
|
def load_data(opt, datasetType='train', permutation=False, shuffle=False):
data_set = SketchDataset(opt=opt, root=os.path.join('data', opt.dataset, 'train'), class_name=opt.class_name, split=datasetType, permutation=permutation)
data_loader = DataLoader(data_set, batch_size=opt.batch_size, shuffle=shuffle, nu... |
def get_scheduler(optimizer, opt):
if (opt.lr_policy == 'lambda'):
def lambda_rule(epoch):
lr_l = (1.0 - (max(0, (((epoch + 1) + opt.epoch_count) - opt.niter)) / float((opt.niter_decay + 1))))
return lr_l
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
... |
def build_record(recode, opt):
recode['dataset'] = opt.dataset
recode['in_feature'] = opt.in_feature
net_structure = {}
net_structure['n_blocks'] = opt.n_blocks
net_structure['channels'] = opt.channels
net_structure['gcn_type'] = opt.gcn_type
net_structure['mixedge'] = opt.mixedge
if (... |
class Writer():
def __init__(self, opt):
self.name = opt.class_name
self.opt = opt
self.save_dir = os.path.join(opt.checkpoints_dir, opt.dataset, opt.class_name, opt.timestamp)
self.log_name = os.path.join(self.save_dir, 'loss_log.txt')
self.testacc_log = os.path.join(self... |
class CUBDataset(datasets.ImageFolder):
'\n Wrapper for the CUB-200-2011 dataset. \n Method DatasetBirds.__getitem__() returns tuple of image and its corresponding label. \n Dataset per https://github.com/slipnitskaya/caltech-birds-advanced-classification\n '
def __init__(self, root, transform... |
def _transform(n_px):
return transforms.Compose([transforms.Resize(n_px, interpolation=Image.BICUBIC), transforms.CenterCrop(n_px), (lambda image: image.convert('RGB')), transforms.ToTensor(), transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711))])
|
def stringtolist(description):
return [descriptor[2:] for descriptor in description.split('\n') if ((descriptor != '') and descriptor.startswith('- '))]
|
def mod_stringtolist(description):
output_list = []
for descriptor in description.split('\n'):
if (descriptor == ''):
continue
if descriptor.startswith('- '):
output_list.append(descriptor[2:])
elif descriptor.startswith('-'):
output_list.append(desc... |
def stringtolist_opt(description, prompt_to_trim=None):
if (prompt_to_trim is not None):
description = description[len(prompt_to_trim):]
descriptorlist = []
description = description.split('Q:')[0]
linesplit = description.split('\n')
for (i, descriptor) in enumerate(linesplit):
if ... |
def wordify(string):
word = string.replace('_', ' ')
return word
|
def make_descriptor_sentence(descriptor):
if (descriptor.startswith('a') or descriptor.startswith('an')):
return f'which is {descriptor}'
elif (descriptor.startswith('has') or descriptor.startswith('often') or descriptor.startswith('typically') or descriptor.startswith('may') or descriptor.startswith(... |
def modify_descriptor(descriptor, apply_changes):
if apply_changes:
return make_descriptor_sentence(descriptor)
return descriptor
|
def generate_prompt(category_name: str):
return f'''Q: What are useful visual features for distinguishing a lemur in a photo?
A: There are several useful visual features to tell there is a lemur in a photo:
- four-limbed primate
- black, grey, white, brown, or red-brown
- wet and hairless nose with curved nostril... |
def generate_prompt_shots(category_name, shots, shot_names):
output = ''
for shot_name in shot_names:
output += shots[shot_name]
return f'''{output}
Q: What are useful features for distinguishing a {category_name} in a photo?
A: There are several useful visual features to tell there is a {categor... |
def generate_prompt_noshots(category_name):
return f'''Q: What are useful features for distinguishing a {category_name} in a photo?
A: There are several useful visual features to tell there is a {category_name} in a photo:
- a'''
|
def generate_prompt(category_name: str):
return f'''Q: What are useful visual features for distinguishing a lemur in a photo?
A: There are several useful visual features to tell there is a lemur in a photo:
- four-limbed primate
- black, grey, white, brown, or red-brown
- wet and hairless nose with curved nostril... |
def partition(lst, size):
for i in range(0, len(lst), size):
(yield list(itertools.islice(lst, i, (i + size))))
|
def obtain_descriptors_and_save(filename, class_list):
responses = {}
descriptors = {}
prompts = [generate_prompt(category.replace('_', ' ')) for category in class_list]
responses = [openai.Completion.create(model='text-davinci-003', prompt=prompt_partition, temperature=0.0, max_tokens=100) for prompt... |
def compute_description_encodings(model):
description_encodings = OrderedDict()
for (k, v) in gpt_descriptions.items():
tokens = clip.tokenize(v).to(hparams['device'])
description_encodings[k] = F.normalize(model.encode_text(tokens))
return description_encodings
|
def compute_label_encodings(model):
label_encodings = F.normalize(model.encode_text(clip.tokenize([((hparams['label_before_text'] + wordify(l)) + hparams['label_after_text']) for l in label_to_classname]).to(hparams['device'])))
return label_encodings
|
def aggregate_similarity(similarity_matrix_chunk, aggregation_method='mean'):
if (aggregation_method == 'max'):
return similarity_matrix_chunk.max(dim=1)[0]
elif (aggregation_method == 'sum'):
return similarity_matrix_chunk.sum(dim=1)
elif (aggregation_method == 'mean'):
return sim... |
def show_from_indices(indices, images, labels=None, predictions=None, predictions2=None, n=None, image_description_similarity=None, image_labels_similarity=None):
if ((indices is None) or (len(indices) == 0)):
print('No indices provided')
return
if (n is not None):
indices = indices[:n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.