code stringlengths 101 5.91M |
|---|
def get_subdomain_xs(ds, scales):
xs = []
for (d, scale) in zip(ds, scales):
x = np.cumsum(np.pad(d, (1, 0)))
x = (((2 * (x - x.min())) / (x.max() - x.min())) - 1)
xs.append((scale * x))
return xs |
class CUB_Sentence_ft(VAE):
def __init__(self, params):
super(CUB_Sentence_ft, self).__init__(prior_dist=dist.Normal, likelihood_dist=FakeCategorical, post_dist=dist.Normal, enc=Enc(params.latent_dim), dec=Dec(params.latent_dim), params=params)
grad = {'requires_grad': params.learn_prior}
se... |
def RunKaldiCommand(command, wait=True):
p = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if wait:
[stdout, stderr] = p.communicate()
if (p.returncode is not 0):
raise Exception('There was an error while running the command {0}\n\n{1}'.format(... |
class Visualization(object):
def __init__(self, seq_info, update_ms):
image_shape = seq_info['image_size'][::(- 1)]
aspect_ratio = (float(image_shape[1]) / image_shape[0])
image_shape = (1024, int((aspect_ratio * 1024)))
self.viewer = ImageViewer(update_ms, image_shape, ('Figure %s' ... |
class ImportTestCase(unittest.TestCase):
def test_import(self):
import dtw
from dtw import dtw as dist
from dtw import accelerated_dtw
def test_has_version(self):
from dtw import __version__ |
.parametrize('loader_parameters', [{'path_data': [str(Path(__data_testing_dir__, 'data_test_png_tif'))], 'target_suffix': ['_seg-myelin-manual'], 'extensions': ['.png', '.tif'], 'roi_params': {'suffix': None, 'slice_filter_roi': None}, 'contrast_params': {'contrast_lst': [], 'balance': {}}, 'slice_axis': 'axial', 'slic... |
def main():
for split in splits:
output_file = os.path.join(seg_dir, (split + '_align'), (split + '_word_align.tsv'))
origin_file = os.path.join(data_dir, (split + '_raw.tsv'))
output_table = load_df_from_tsv(output_file)
origin_table = load_df_from_tsv(origin_file)
concat_ta... |
class MarianTokenizer(PreTrainedTokenizer):
vocab_files_names = vocab_files_names
model_input_names = ['attention_mask']
language_code_re = re.compile('>>.+<<')
def __init__(self, vocab, source_spm, target_spm, source_lang=None, target_lang=None, unk_token='<unk>', eos_token='</s>', pad_token='<pad>', m... |
def find_reference_section_no_title_generic(docbody, marker_patterns):
if (not docbody):
return None
ref_start_line = ref_line_marker = None
found_ref_sect = False
for (reversed_index, line) in enumerate(reversed(docbody)):
mark_match = regex_match_list(line.strip(), marker_patterns)
... |
class CollabList(TabularList):
(_item_cls, _label_cls, _processor) = (CollabLine, FloatList, CollabProcessor)
def reconstruct(self, t: Tensor):
return CollabLine(tensor(t), tensor([]), self.classes, self.col_names) |
class EmptyCollectionException(RuntimeError):
def __init__(self):
super(EmptyCollectionException, self).__init__('The collection is empty') |
def create_model(use_selfatt=False, use_fc=False, dropout=None, stage1_weights=False, dataset=None, log_dir=None, test=False, *args):
print('Loading Scratch ResNet 10 Feature Model.')
resnet10 = ResNet(BasicBlock, [1, 1, 1, 1], use_modulatedatt=use_selfatt, use_fc=use_fc, dropout=None)
if (not test):
... |
def _union_lcs(evaluated_sentences, reference_sentence, prev_union=None):
if (prev_union is None):
prev_union = set()
if (len(evaluated_sentences) <= 0):
raise ValueError('Collections must contain at least 1 sentence.')
lcs_union = prev_union
prev_count = len(prev_union)
reference_wo... |
def get_trimmed_wordvec_vectors(filename, vocab):
with open(filename, 'r') as inFile:
inFile.readline()
dim = (len(inFile.readline().strip().split()) - 1)
embeddings = np.random.uniform((- 0.1), 0.1, size=((len(vocab) + 1), dim))
with open(filename, 'r') as inFile:
for line in inFile... |
def _convert_to_bchar(in_path_prefix: str, src: str, tgt: str, out_path: str):
with open(out_path, 'w') as f_o:
for lang in [src, tgt]:
with open(f'{in_path_prefix}.{lang}') as f:
for s in f:
f_o.write((byte_encode(s.strip()) + '\n')) |
class OptimizerDict(dict):
def __init__(self, *args, **kwargs):
super(OptimizerDict, self).__init__(*args, **kwargs)
def state_dict(self):
return [optim.state_dict() for optim in self.values()]
def load_state_dict(self, state_dicts):
for (state_dict, optim) in zip(state_dicts, self.v... |
class CombinedLoss(torch.nn.Module):
def __init__(self, criteria: Sequence[torch.nn.Module], weight: Optional[Sequence[float]]=None, device: Optional[torch.device]=None):
super().__init__()
self.criteria = torch.nn.ModuleList(criteria)
self.device = device
if (weight is None):
... |
def data_load(filename, axisname, label):
datanumber = axisname.split('.')
if (eval(datanumber[0]) < 100):
realaxis = (('X0' + datanumber[0]) + axis[0])
else:
realaxis = (('X' + datanumber[0]) + axis[0])
fl = loadmat(filename)[realaxis]
fl = fl.reshape((- 1))
data = []
lab = ... |
def _build_non_max_suppressor(nms_config):
if ((nms_config.iou_threshold < 0) or (nms_config.iou_threshold > 1.0)):
raise ValueError('iou_threshold not in [0, 1.0].')
if (nms_config.max_detections_per_class > nms_config.max_total_detections):
raise ValueError('max_detections_per_class should be ... |
def main_worker(gpu, ngpus_per_node, args):
global best_acc1
args.gpu = gpu
class_num = {'cub': 200, 'cars': 196, 'dogs': 120, 'fgvc': 100}
if (args.gpu is not None):
print('Use GPU: {} for training'.format(args.gpu))
if args.distributed:
if ((args.dist_url == 'env://') and (args.ran... |
_HEADS_REGISTRY.register()
class VanillaHungarianBBoxIOUTracker(BaseHungarianTracker):
def __init__(self, *, video_height: int, video_width: int, max_num_instances: int=200, max_lost_frame_count: int=0, min_box_rel_dim: float=0.02, min_instance_period: int=1, track_iou_threshold: float=0.5, **kwargs):
super... |
class dataset_it(Dataset):
def __init__(self, data_dir, input1, transform_1, queue_length=20, samples_per_volume=5, patch_size=128, num_workers=8, shuffle_subjects=True, shuffle_patches=True, sup=True, num_images=None):
super(dataset_it, self).__init__()
self.subjects_1 = []
image_dir_1 = ((... |
class CelebAHQValidation(FacesBase):
def __init__(self, size, keys=None):
super().__init__()
root = 'data/celebahq'
with open('data/celebahqvalidation.txt', 'r') as f:
relpaths = f.read().splitlines()
paths = [os.path.join(root, relpath) for relpath in relpaths]
s... |
class ContextAdjustmentLayer(nn.Module):
def __init__(self, num_blocks=8, feature_dim=16, expansion=3):
super().__init__()
self.num_blocks = num_blocks
self.in_conv = nn.Conv2d(4, feature_dim, kernel_size=3, padding=1)
self.layers = nn.ModuleList([ResBlock(feature_dim, expansion) for... |
def writetextfile(data, filename):
with open(filename, 'w') as f:
f.writelines(data)
f.close() |
def test():
net = Net(nclass=23).cuda()
print(net)
x = Variable(torch.randn(1, 3, 224, 224)).cuda()
y = net(x)
print(y)
params = net.parameters()
sum = 0
for param in params:
sum += param.nelement()
print('Total params:', sum) |
class UnitTest(unittest.TestCase):
def setUp(self) -> None:
os.environ['IMAGE_SERVER_IP'] = 'test_server_ip'
return super().setUp()
def tearDown(self) -> None:
if os.path.exists('./MagicMock'):
shutil.rmtree('./MagicMock')
def test_find_GPS_image(self):
img_file_p... |
class HPOMixin():
FIT_KEYS = {'x', 'y', 'batch_size', 'epochs', 'verbose', 'callbacks', 'validation_split', 'validation_data', 'shuffle', 'class_weight', 'sample_weight', 'initial_epoch', 'steps_per_epoch', 'validation_steps', 'validation_batch_size', 'validation_freq', 'max_queue_size', 'workers', 'use_multiproces... |
class VeEvalDataset(VqaEvalDataset):
def __init__(self, *args, **kwargs):
super().__init__(3, *args, **kwargs) |
def test_ic_uni(model, data_loader, model_path=None, ic_type='spearman', verbose=False):
if model_path:
model.load_state_dict(torch.load(model_path))
model.eval()
loss_all = []
ic_all = []
for slc in tqdm(data_loader.iter_daily(), total=data_loader.daily_length):
(data, label, _, _) ... |
def stdout(ts_or_cell_num: Union[(int, Timestamp)]) -> Optional[str]:
try:
cell_num = _to_cell_num(ts_or_cell_num)
captured = cells().at_counter(cell_num).captured_output
return (None if (captured is None) else str(captured.stdout))
except KeyError:
raise ValueError(('cell with c... |
def _format_entry(indent, entry):
color = ''
indent = (' ' * indent)
if entry.typechanged:
color = RED
elif entry.added:
color = GREEN
elif entry.modified:
color = BLUE
if (entry.key == '__doc__'):
color = GREY
doc_string = entry.value.replace('\n', ('\n' ... |
_grad()
def compute_throughput(model, batch_size=128, resolution=224):
torch.cuda.empty_cache()
warmup_iters = 3
num_iters = 30
model.eval()
model.to('cuda')
timing = []
inputs = torch.randn(batch_size, 3, resolution, resolution, device='cuda')
for _ in range(warmup_iters):
model... |
class Adam(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False, use_gc=False, gc_conv_only=False, gc_loc=False):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
rai... |
def mriAdjointOp(rawdata, coilsens, mask):
return np.sum((ifft2c((rawdata * mask)) * np.conj(coilsens)), axis=0) |
def get_module_names(path_dir, exclude=None):
if (exclude is None):
exclude = _default_exclude
'Search a given `path_dir` and return all the modules contained inside except those in `exclude`'
files = sorted(path_dir.glob('*'), key=(lambda x: (x.is_dir(), x.name)), reverse=True)
res = [f'{path_d... |
class TreeLSTM_IO(object):
def __init__(self, hidden_tensor, order_tensor, order_count, dists_tensor, commitments_tensor, dropout_mask):
self.hidden = hidden_tensor
self.order = order_tensor
self.order_count = order_count
self.dists = dists_tensor
self.commitments = commitmen... |
class MetaTrainer(nn.Module):
def __init__(self, args, experiment_id, is_pretrained, new_words=False):
super(MetaTrainer, self).__init__()
self.update_lr = args.update_lr
self.meta_lr = args.meta_lr
self.n_way = args.n_way
self.k_spt = args.k_spt
self.k_qry = args.k_q... |
.parametrize('image', np.array([[[1, 1], [1, 1]], [[0, 0], [0, 0]]]))
def test_mse(image):
results = imed_metrics.mse(image, image)
assert (results == 0.0) |
def xyxy_to_xywh(xyxy_box):
(xmin, ymin, xmax, ymax) = xyxy_box
TO_REMOVE = 1
xywh_box = (xmin, ymin, ((xmax - xmin) + TO_REMOVE), ((ymax - ymin) + TO_REMOVE))
return xywh_box |
def conv_block_3(in_dim, out_dim, act_fn):
model = nn.Sequential(conv_block(in_dim, out_dim, act_fn), conv_block(out_dim, out_dim, act_fn), nn.Conv2d(out_dim, out_dim, kernel_size=3, stride=1, padding=1), nn.BatchNorm2d(out_dim))
return model |
def get_tl_line_values_from_file_contents(content, CRLF=True, LTRB=True, withTranscription=False, withConfidence=False, imWidth=0, imHeight=0, sort_by_confidences=True):
pointsList = []
transcriptionsList = []
confidencesList = []
lines = content.split(('\r\n' if CRLF else '\n'))
for line in lines:
... |
def _add_category_id_to_contiguous_id_maps_to_metadata(merged_categories: _MergedCategoriesT) -> None:
merged_categories_per_dataset = {}
for (contiguous_cat_id, cat_id) in enumerate(sorted(merged_categories.keys())):
for cat in merged_categories[cat_id]:
if (cat.dataset_name not in merged_c... |
class PruningCriterion():
def __init__(self, modules, config, pattern):
self.scores = {}
self.modules = modules
self.config = config
self.pattern = pattern
self.low_memory_usage = config['low_memory_usage']
def on_step_begin(self):
pass
def on_before_optimizer... |
class DeepLabV3(SegmentationModel):
def __init__(self, task, encoder_name: str='resnet34', encoder_depth: int=5, encoder_weights: Optional[str]='imagenet', decoder_channels: int=256, in_channels: int=3, classes: int=1, activation: Optional[str]=None, upsampling: int=8, aux_params: Optional[dict]=None):
supe... |
def read_facet_specific_relevances(data_path, run_path, dataset, facet, method_name):
gold_fname = os.path.join(data_path, 'test-pid2anns-{:s}-{:s}.json'.format(dataset, facet))
ranked_fname = os.path.join(run_path, 'test-pid2pool-{:s}-{:s}-{:s}-ranked.json'.format(dataset, method_name, facet))
with codecs.... |
class LaikagoPose(object):
abduction_angle_0 = attr.ib(type=float, default=0)
hip_angle_0 = attr.ib(type=float, default=0)
knee_angle_0 = attr.ib(type=float, default=0)
abduction_angle_1 = attr.ib(type=float, default=0)
hip_angle_1 = attr.ib(type=float, default=0)
knee_angle_1 = attr.ib(type=flo... |
class GenerationRunner(BaseRunner):
def __init__(self, model: PromptForGeneration, config: CfgNode=None, train_dataloader: Optional[PromptDataLoader]=None, valid_dataloader: Optional[PromptDataLoader]=None, test_dataloader: Optional[PromptDataLoader]=None):
super().__init__(model=model, config=config, train... |
def update_config(config_file):
exp_config = None
with open(config_file) as f:
exp_config = edict(yaml.load(f, Loader=yaml.SafeLoader))
for (k, v) in exp_config.items():
if (k in config):
if isinstance(v, dict):
if (k == 'TRAIN'):
... |
def parse_args():
parser = argparse.ArgumentParser(description='Simple example of a training script.')
parser.add_argument('--dataset_name', type=str, default=None, help='The name of the Dataset (from the HuggingFace hub) to train on (could be your own, possibly private, dataset). It can also be a path pointing... |
def train_fine(epoch):
coarse_model.eval()
fine_model.train()
train_fine_loss = 0
for (batch_idx, data) in enumerate(train_loader):
(rgb, depth) = (torch.tensor(data['image'].cuda(), requires_grad=True), torch.tensor(data['depth'].cuda(), requires_grad=True))
fine_optimizer.zero_grad()
... |
def add_entry(data, model_key, row, headers):
ep = row[headers[EPOCH]]
tep = row[headers[TOTAL_EPOCHS]]
f1 = [row[headers[TEST_F1_NAME]], 'f1']
acc = [row[headers[TEST_ACC_NAME]], 'acc']
pc = [row[headers[TEST_PR_NAME]], 'precision']
rc = [row[headers[TEST_RC_NAME]], 'recall']
entries = [acc... |
def get_cot_prompt(data: dict, backbone: str):
if (backbone == 'gpt4'):
system_message = math_prompt.GPT4_COT_SYSTEM
user_message = math_prompt.GPT4_COT_USER
assistant_message = math_prompt.GPT4_COT_ASSISTANT
elif (backbone == 'chatgpt'):
system_message = math_prompt.TURBO_COT_SY... |
class DiscriminatorMnistSN(object):
def __init__(self, z_dim=100, size=28):
self.name = 'DiscriminatorMnistSN'
self.z_dim = z_dim
self.size = size
def __call__(self, inputs, y, is_training=True, reuse=False):
with tf.variable_scope(self.name) as scope:
if reuse:
... |
def get_event_given_entity_id(source_data, entity_id, id_pos=1):
events = filter((lambda x: (x[id_pos] == entity_id)), source_data)
return events |
class NetworkOnly():
def __init__(self, policy, env, max_depth_dict):
self.policy = policy
self.env = env
self.stop_index = env.programs_library['STOP']['index']
self.max_depth_dict = max_depth_dict
self.clean_sub_executions = True
def play(self, task_index):
prog... |
def getDrivingMetas(root, data_type='clean'):
Metas = []
imgDir = (('driving/frames_' + data_type) + 'pass')
dispDir = 'driving/disparity'
focalLengthDirs = os.listdir(osp.join(root, dispDir))
for focalLengthDir in focalLengthDirs:
wardDirs = os.listdir(osp.join(root, dispDir, focalLengthDir... |
class Cell(nn.Module):
def __init__(self, steps, block_multiplier, prev_prev_fmultiplier, prev_fmultiplier_down, prev_fmultiplier_same, prev_fmultiplier_up, filter_multiplier):
super(Cell, self).__init__()
self.C_in = (block_multiplier * filter_multiplier)
self.C_out = filter_multiplier
... |
def get_jitters(f0_contour, p_floor=0.0001, p_ceil=0.02, max_p_factor=1.3):
local_absolute_jitter = get_local_absolute_jitter(f0_contour, p_floor, p_ceil, max_p_factor)
local_jitter = get_local_jitter(f0_contour, p_floor, p_ceil, max_p_factor)
rap_jitter = get_rap_jitter(f0_contour, p_floor, p_ceil, max_p_f... |
def model(dataloaders_with_covariates):
dataset = dataloaders_with_covariates['train'].dataset
net = TemporalFusionTransformer.from_dataset(dataset, learning_rate=0.15, hidden_size=4, attention_head_size=1, dropout=0.2, hidden_continuous_size=2, loss=PoissonLoss(), output_size=1, log_interval=5, log_val_interva... |
class StringIndex(Table):
def __init__(self, df: 'SparkDataFrame', col_name: str) -> None:
super().__init__(df)
cols = df.columns
invalidInputError((len(cols) >= 2), 'StringIndex should have >= 2 columns: col_name, id and other columns')
invalidInputError(('id' in cols), 'id should b... |
def generate_unroll(env: envs.Env, env_state: envs.State, policy: Policy, key: PRNGKey, unroll_length: int, extra_fields: Sequence[str]=()) -> Tuple[(envs.State, Transition)]:
def f(carry, unused_t):
(state, current_key) = carry
(current_key, next_key) = jax.random.split(current_key)
(nstate... |
class AdamP(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, delta=0.1, wd_ratio=0.1, nesterov=False):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, delta=delta, wd_ratio=wd_ratio, nesterov=nesterov)
super(AdamP, self).__init__... |
class DocumentIterator(torchtext.data.Iterator):
def __init__(self, dataset, batch_size, device=None, batch_size_fn=None, train=True, shuffle=None, sort_within_batch=None):
super(DocumentIterator, self).__init__(dataset, batch_size, device=device, batch_size_fn=batch_size_fn, train=train, repeat=False, shuf... |
class BenchmarkVINFModel(VINFModel):
def __init__(self, loader, criterion, optimizer, epochs, base, subspace, flow, prior_log_sigma=3.0, lr=0.1, temperature=1.0, num_samples=45000, *args, **kwargs):
super(BenchmarkVINFModel, self).__init__(base, subspace, flow, prior_log_sigma=prior_log_sigma)
self.... |
def get_max_min_notes(piano_roll_dict):
max_note = 0
min_note = .0
for dataset in piano_roll_dict:
unrolled = unroll(piano_roll_dict[dataset])
max_note = max(np.max(unrolled), max_note)
min_note = min(np.min(unrolled), min_note)
return (max_note, min_note) |
class SoftError(torchmetrics.Metric):
full_state_update = False
def __init__(self):
super().__init__()
self.add_state('correct', default=torch.tensor(0.0), dist_reduce_fx='sum')
self.add_state('total', default=torch.tensor(0.0), dist_reduce_fx='sum')
def update(self, preds: torch.Ten... |
def conv2d_biprec(input, weight, bias=None, stride=1, padding=0, dilation=1, groups=1, num_bits_grad=None):
out1 = F.conv2d(input.detach(), weight, bias, stride, padding, dilation, groups)
out2 = F.conv2d(input, weight.detach(), (bias.detach() if (bias is not None) else None), stride, padding, dilation, groups)... |
def test_mit_init():
path = 'PATH_THAT_DO_NOT_EXIST'
model = MixVisionTransformer(pretrained=None, init_cfg=None)
assert (model.init_cfg is None)
model.init_weights()
model = MixVisionTransformer(pretrained=None, init_cfg=dict(type='Pretrained', checkpoint=path))
assert (model.init_cfg == dict(t... |
class TabNet(BaseTabularModelWithoutAttention):
def __init__(self, column_idx: Dict[(str, int)], cat_embed_input: Optional[List[Tuple[(str, int, int)]]]=None, cat_embed_dropout: float=0.1, use_cat_bias: bool=False, cat_embed_activation: Optional[str]=None, continuous_cols: Optional[List[str]]=None, cont_norm_layer:... |
class DummyIntegerProblem(IntegerProblem):
def __init__(self):
super(DummyIntegerProblem, self).__init__()
def number_of_objectives(self) -> int:
return 2
def number_of_constraints(self) -> int:
return 0
def evaluate(self, solution: IntegerSolution) -> IntegerSolution:
re... |
def count_parameters(model, trainable_only=True, is_dict=False):
if is_dict:
return sum((np.prod(list(model[k].size())) for k in model))
if trainable_only:
return sum((p.numel() for p in model.parameters() if p.requires_grad))
else:
return sum((p.numel() for p in model.parameters())) |
def remove_duplicate_anns_by_id(annotation_list):
if (annotation_list is None):
return
ann_by_id = dict()
for ann in annotation_list:
if (ann['id'] in ann_by_id):
ann['delete'] = True
else:
ann_by_id[ann['id']] = ann
annotation_list = [ann for ann in annot... |
class UnpackLayerConv3d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, r=2, d=8):
super().__init__()
self.conv = Conv2D(in_channels, ((out_channels * (r ** 2)) // d), kernel_size, 1)
self.unpack = nn.PixelShuffle(r)
self.conv3d = nn.Conv3d(1, d, kernel_size=(3... |
def download_pretrained_models(method, file_ids):
save_path_root = f'./experiments/pretrained_models/{method}'
os.makedirs(save_path_root, exist_ok=True)
for (file_name, file_id) in file_ids.items():
save_path = osp.abspath(osp.join(save_path_root, file_name))
if osp.exists(save_path):
... |
class Encoding(nn.Module):
def __init__(self, channels, num_codes):
super(Encoding, self).__init__()
(self.channels, self.num_codes) = (channels, num_codes)
std = (1.0 / ((num_codes * channels) ** 0.5))
self.codewords = nn.Parameter(torch.empty(num_codes, channels, dtype=torch.float)... |
def invert(mapper):
inverted_map = defaultdict(list)
for (key, val) in mapper.items():
inverted_map[val].append(key)
return inverted_map |
def test_active_set_finance_without_subprocess_intercept(dataset_finance):
warnings.filterwarnings('ignore', category=ConvergenceWarning)
(X, y) = (dataset_finance[0], dataset_finance[1])
n_samples = X.shape[0]
primary = Regression(loss='square', penalty='l1', fit_intercept=True, lambda_1=(0.1 / n_sampl... |
def create_random_map(height, width, corridor_radius, iterations, obstacle_number, obstacle_extra_radius, map_type: str, indoor_prob: float, seed: int):
np.random.seed(seed)
if (map_type == 'mixed'):
if (np.random.random() <= indoor_prob):
map_type = 'indoor'
else:
map_ty... |
def add_sub_symbol(bert_tokens: List[str], chinese_word_set: set()):
if (not chinese_word_set):
return bert_tokens
max_word_len = max([len(w) for w in chinese_word_set])
bert_word = bert_tokens
(start, end) = (0, len(bert_word))
while (start < end):
single_word = True
if is_c... |
def get_object_ids(data_root, ann_file, object_names):
coco = COCO(os.path.join(data_root, 'annotations', ann_file))
object_ids_map = {cat['name']: cat['id'] for cat in coco.dataset['categories']}
return [object_ids_map[object_name] for object_name in object_names] |
class HansProcessor(DataProcessor):
def get_example_from_tensor_dict(self, tensor_dict):
return InputExample(tensor_dict['idx'].numpy(), tensor_dict['premise'].numpy().decode('utf-8'), tensor_dict['hypothesis'].numpy().decode('utf-8'), str(tensor_dict['label'].numpy()))
def get_train_examples(self, data... |
def evaluate(pred_root, gt_root, trimap_root, verbose, nproc):
images = sorted(mmcv.scandir(pred_root))
gt_files_num = len(list(mmcv.scandir(gt_root)))
if (gt_files_num == 50):
pattern = re.compile('(.+)_(?:\\d+)(.png)')
pairs = []
for img in images:
pred_alpha_path = osp.join(pred_r... |
def item_from_space(space: Space) -> Item:
return Item(x_len=(space.x2 - space.x1), y_len=(space.y2 - space.y1), z_len=(space.z2 - space.z1)) |
class DepthWiseConvOp(nn.Module):
def __init__(self, C_in, C_out, kernel_size, act_op, affine=True):
super(DepthWiseConvOp, self).__init__()
padding = PADDING_OPS[kernel_size]
kernel_size = KERNEL_SIZE_OPS[kernel_size]
activation = ACTIVATION_OPS[act_op]
if (not activation):
... |
def compute_used_samples(update_state_gate):
batch_size = update_state_gate.shape[0]
steps = 0.0
for idx in range(batch_size):
for idt in range(update_state_gate.shape[1]):
steps += update_state_gate[(idx, idt)]
return (steps / batch_size) |
def partial_repr(t):
args = (((t.func,) + t.args) + tuple([f'{k}={v}' for (k, v) in t.keywords.items()]))
reprs = ', '.join([link_type(o) for o in args])
return f'<code>partial(</code>{reprs}<code>)</code>' |
def test_empty_book():
book = OrderBook(FakeExchangeAgent(), SYMBOL)
assert (book.get_l1_bid_data() == None)
assert (book.get_l1_ask_data() == None)
assert (book.get_l2_bid_data() == [])
assert (book.get_l2_ask_data() == [])
assert (book.get_l3_bid_data() == [])
assert (book.get_l3_ask_data(... |
class VGGBackbone(nn.Module):
def __init__(self, cfg, extra_args=[], norm_layers=[]):
super().__init__()
self.channels = []
self.layers = nn.ModuleList()
self.in_channels = 3
self.extra_args = list(reversed(extra_args))
self.total_layer_count = 0
self.state_di... |
class _LazyModule(ModuleType):
def __init__(self, name, module_file, import_structure, module_spec=None, extra_objects=None):
super().__init__(name)
self._modules = set(import_structure.keys())
self._class_to_module = {}
for (key, values) in import_structure.items():
for ... |
def text_to_html_table(items):
html_code = '<table border="1" class="dataframe">\n'
html_code += ' <thead>\n <tr style="text-align: left;">\n'
for i in items[0]:
html_code += f''' <th>{i}</th>
'''
html_code += ' </tr>\n </thead>\n <tbody>\n'
for line in items[1:]:
html_cod... |
def decode_rerank_scores(args):
if ((args.max_tokens is None) and (args.batch_size is None)):
args.batch_size = 1
logger.info(args)
use_cuda = (torch.cuda.is_available() and (not args.cpu))
logger.info('loading model(s) from {}'.format(args.path))
(models, _model_args, task) = checkpoint_uti... |
class FP16Optimizer(_FP16OptimizerMixin, optim.FairseqOptimizer):
def __init__(self, cfg: DictConfig, params, fp32_optimizer, fp32_params, **kwargs):
super().__init__(cfg.optimizer)
self.fp16_params = params
self.fp32_optimizer = fp32_optimizer
self.fp32_params = fp32_params
... |
class NATSpeechToSpeechDataset(FairseqDataset):
def __init__(self, split: str, is_train_split: bool, cfg: NATS2SDataConfig, src_audio_paths: List[str], src_n_frames: List[int], tgt_audio_paths: Optional[List[str]]=None, tgt_n_frames: Optional[List[int]]=None, tgt_texts: Optional[List[str]]=None, ids: Optional[List[... |
def calculate_fid(dataset_name, generated_dir, target_size=256):
real_dir = os.path.join('EvalImages', ((dataset_name + '_real_images_') + str(target_size)))
fid = fid_score.calculate_fid_given_paths([real_dir, generated_dir], target_size, 'cuda', 2048)
torch.cuda.empty_cache()
return fid |
def xresnet152(pretrained=False, **kwargs):
model = XResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['xresnet152']))
return model |
class ConvTransformerEncoder(FairseqEncoder):
def __init__(self, args):
super().__init__(None)
self.dropout = args.dropout
self.embed_scale = (1.0 if args.no_scale_embedding else math.sqrt(args.encoder_embed_dim))
self.padding_idx = 1
self.in_channels = 1
self.input_d... |
def data_type_dict():
return {'float16': tf.float16, 'float32': tf.float32, 'float64': tf.float64, 'uint8': tf.uint8, 'int8': tf.int8, 'int16': tf.int16, 'int32': tf.int32, 'int64': tf.int64, 'bool': tf.bool} |
def ucf101_root():
with get_tmp_dir() as tmp_dir:
ucf_dir = os.path.join(tmp_dir, 'UCF-101')
video_dir = os.path.join(ucf_dir, 'video')
annotations = os.path.join(ucf_dir, 'annotations')
os.makedirs(ucf_dir)
os.makedirs(video_dir)
os.makedirs(annotations)
fold... |
class ParametricConcurrent(nn.Sequential):
def __init__(self, axis=1):
super(ParametricConcurrent, self).__init__()
self.axis = axis
def forward(self, x, **kwargs):
out = []
for module in self._modules.values():
out.append(module(x, **kwargs))
out = torch.cat(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.