code stringlengths 101 5.91M |
|---|
def area(boxlist, scope=None):
with tf.name_scope(scope, 'Area'):
(y_min, x_min, y_max, x_max) = tf.split(value=boxlist.get(), num_or_size_splits=4, axis=1)
return tf.squeeze(((y_max - y_min) * (x_max - x_min)), [1]) |
def _para_get_metric(metric: RougeStrEvaluation, key, note):
current_metrics = metric.get_metric(reset=True, note=note)
current_best_cp_A = [x for x in current_metrics.keys() if x.endswith('_A')]
assert (len(current_best_cp_A) == 1)
current_best_cp_A = current_best_cp_A[0]
cp_A_val = current_metrics... |
class MixtureNLLLoss(nn.Module):
def __init__(self, component_distribution: Union[(str, List[str])], eps: float=1e-06, reduction: str='mean') -> None:
super(MixtureNLLLoss, self).__init__()
self.reduction = reduction
loss_dict = {'gaussian': GaussianNLLLoss, 'laplace': LaplaceNLLLoss, 'von_m... |
def mapping(path, dest):
(node_forward, node_backward) = ({}, {})
(edge_forward, edge_backward) = ({}, {})
(node_count, edge_count) = (0, 0)
(max_nodes, max_edges, max_degree) = (0, 0, 0)
(min_nodes, min_edges) = (float('inf'), float('inf'))
for filename in tqdm(os.listdir(path)):
if fil... |
def dynamic_import_scheduler(module):
model_class = dynamic_import(module, SCHEDULER_DICT)
assert issubclass(model_class, SchedulerInterface), f'{module} does not implement SchedulerInterface'
return model_class |
class Bottleneck(nn.Module):
def __init__(self, inplanes, expansion=4, growthRate=12, dropRate=0):
super(Bottleneck, self).__init__()
planes = (expansion * growthRate)
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.c... |
def plot_mse(args):
all_results = {'method': [], 'mse': [], 'num_nonzero': [], 'seed': []}
for seed in args.seeds:
for method in args.methods:
if (method not in ['spinn', 'ridge_nn']):
res_file = os.path.join(args.result_folder, (args.file_template % (seed, method)))
... |
class Conv3x3GNReLU(nn.Module):
def __init__(self, in_channels, out_channels, upsample=False):
super().__init__()
self.upsample = upsample
self.block = nn.Sequential(nn.Conv2d(in_channels, out_channels, (3, 3), stride=1, padding=1, bias=False), nn.GroupNorm(32, out_channels), nn.ReLU(inplace... |
def _get_transform_summary(transform):
if isinstance(transform, AffineTransform):
return f'{type(transform).__name__}({transform.loc}, {transform.scale})'
raise NotImplementedError |
def handle_evaluate(args):
tester = Tester(args)
print('Experiment {} instantiated. Evaluation starting...'.format(args.checkname))
tester.test() |
def get_cifar10_loaders(data_route, batch_size, num_workers):
tfm_train = T.Compose([T.RandomCrop(32, padding=4), T.RandomHorizontalFlip(), T.ToTensor(), cifar_nm])
tfm_test = T.Compose([T.ToTensor(), cifar_nm])
train_set = dts.CIFAR10(data_route, train=True, download=True, transform=tfm_train)
test_set... |
class ExpCfg():
dataset: DATASET = MISSING
savedir: str = run_data_root
data_root: str = (ROOT / 'data')
batch_size: int = 32
val_batch_size: int = 32
data_loader_workers: int = 4
prefetch_factor: int = 4
disable_logs: bool = False
module: GeneralModule = MISSING
max_epochs: int ... |
def read_uiuc_coref(filename, gold_text):
mentions = {}
clusters = defaultdict((lambda : []))
unmatched_mentions = []
text = [[]]
sentence = 0
word = 0
prev = ['', '']
last_sentence = []
for line in open(filename):
for token in line.split():
if (re.match('^[*]+$',... |
def sepreresnet272bn_cifar10(num_classes=10, **kwargs):
return get_sepreresnet_cifar(num_classes=num_classes, blocks=272, bottleneck=True, model_name='sepreresnet272bn_cifar10', **kwargs) |
class BaseParser(abc.ABC):
selector: Optional[str]
follower: Optional[str]
content: bytes
def _raw_urls(self) -> List[Union[(Dict[(str, str)], str)]]:
return []
def entries(self) -> List:
def urls(self) -> List[str]:
urls = [(d if isinstance(d, str) else d['url']) for d in self._... |
class Facebook(BaseData):
def __init__(self, data_root: Optional[str]=None) -> None:
super().__init__('facebook', data_root)
self._content = {'num_classes': 4, 'num_vertices': 22470, 'num_edges': 85501, 'dim_features': 8189, 'features': {'upon': [{'filename': 'features.pkl', 'md5': '046eec1b67fb5bf5... |
class TFRSModel(tf.keras.Model):
def __init__(self, tfrs_model: tfrs.Model) -> None:
super().__init__()
log4Error.invalidInputError(isinstance(tfrs_model, tfrs.Model), ('FriesianTFRSModel only support tfrs.Model, but got ' + tfrs_model.__class__.__name__))
log4Error.invalidInputError((not tf... |
class Target():
def __init__(self, imagePath, saliencyPath, fixationPath, imageState=LoadState.unloaded, imageType=InputType.image, saliencyState=LoadState.unloaded, saliencyType=InputType.saliencyMapMatlab, fixationState=LoadState.unloaded, fixationType=InputType.fixationMapMatlab):
self.image = ImageConta... |
def build_reading_dict(lexicon):
reading_dict = defaultdict(list)
for (i, word) in enumerate(lexicon):
tokens = word[0].split('/')
if (len(tokens) < 3):
continue
display = tokens[0]
reading = tokens[1]
if (reading == ''):
reading = display
... |
class Ply(object):
def __init__(self, points, colors):
self.__points = points
self.__colors = colors
def write(self, filename):
lines = self.__getLinesForHeader()
fd = open(filename, 'w')
for line in lines:
fd.write(('%s\n' % line))
self.__writePoints(... |
class ConvRes(nn.Module):
def __init__(self, input_size=(1, 257, 1091)):
super(ConvRes, self).__init__()
self.features = nn.Sequential(nn.Conv2d(1, 16, kernel_size=(3, 3), padding=(2, 2), dilation=(1, 1)), nn.BatchNorm2d(16), nn.ReLU(), nn.MaxPool2d(kernel_size=2), nn.Conv2d(16, 32, kernel_size=(3, ... |
def get_inst_num(FILENAME):
annot_name = FILENAME.replace('JPEGImages', 'Annotations').replace('.jpg', '.xml')
res = np.zeros([20], np.float32)
tree = ET.parse(annot_name)
root = tree.getroot()
for child in root:
if (child.tag == 'object'):
for c in child:
if (c.t... |
def dissl_resnet50_dNone_e100_m2(pretrained=True, **kwargs):
return _dissl(base='resnet50', dim=None, sffx='_e100_m2', pretrained=pretrained, **kwargs) |
def add_clouds_texture(name: str='Clouds Texture', size: float=0.25, depth: int=2, nabla: float=0.025, brightness: float=1.0, contrast: float=1.0) -> bpy.types.CloudsTexture:
tex = bpy.data.textures.new(name, type='CLOUDS')
tex.noise_scale = size
tex.noise_depth = depth
tex.nabla = nabla
tex.intensi... |
def lightgbm_eval_metric_f1(preds, dtrain):
target = dtrain.get_label()
weight = dtrain.get_weight()
unique_targets = np.unique(target)
if (len(unique_targets) > 2):
cols = len(unique_targets)
rows = int((preds.shape[0] / len(unique_targets)))
preds = np.reshape(preds, (rows, col... |
def load_model(model_path, cuda):
model = torch.load(os.path.join(model_path, 'model.bin'), map_location=cuda)
model.planing_model.device = cuda
return model |
.parametrize('input_dim, output_dim, hidden_sizes, std_hidden_sizes', different_std_settings)
def test_std_adaptive_network_output_values(input_dim, output_dim, hidden_sizes, std_hidden_sizes):
module = GaussianMLPIndependentStdModule(input_dim=input_dim, output_dim=output_dim, hidden_sizes=hidden_sizes, std_hidden... |
def get_prf(res):
if (res['TP'] == 0):
if ((res['FP'] == 0) and (res['FN'] == 0)):
precision = 1.0
recall = 1.0
f1 = 1.0
else:
precision = 0.0
recall = 0.0
f1 = 0.0
else:
precision = ((1.0 * res['TP']) / (res['TP'] +... |
def _child_names(tree):
names = []
for child in tree:
if isinstance(child, Tree):
names.append(Nonterminal(child._label))
else:
names.append(child)
return names |
def _maybe_create_keypoints_keep_instance_predicate(cfg: CfgNode) -> Optional[InstancePredicate]:
min_num_keypoints = cfg.MODEL.ROI_KEYPOINT_HEAD.MIN_KEYPOINTS_PER_IMAGE
def has_sufficient_num_keypoints(instance: Instance) -> bool:
num_kpts = sum(((np.array(ann['keypoints'][2::3]) > 0).sum() for ann in ... |
class RODDecode_Dil(nn.Module):
def __init__(self):
super(RODDecode_Dil, self).__init__()
self.convt1 = nn.ConvTranspose3d(in_channels=256, out_channels=128, kernel_size=(4, 6, 6), stride=(2, 2, 2), padding=(1, 2, 2))
self.convt2 = nn.ConvTranspose3d(in_channels=128, out_channels=64, kernel_... |
def inference_model(config_name, checkpoint, args, logger=None):
cfg = Config.fromfile(config_name)
if args.aug:
if (('flip' in cfg.data.test.pipeline[1]) and ('img_scale' in cfg.data.test.pipeline[1])):
cfg.data.test.pipeline[1].img_ratios = [0.5, 0.75, 1.0, 1.25, 1.5, 1.75]
cfg... |
class Network(nn.Module):
def __init__(self, img_ch, net_ch):
super().__init__()
self.from_rgb = nn.Sequential(nn.Conv2d(img_ch, (net_ch // 2), 1, 1, 0), nn.Conv2d((net_ch // 2), net_ch, 1, 1, 0))
self.to_rgb = nn.Sequential(nn.Conv2d(net_ch, (net_ch // 2), 1, 1, 0), nn.Conv2d((net_ch // 2),... |
def make_empty_instances(h, w):
instances = Instances((h, w))
instances.gt_boxes = Boxes(torch.rand(0, 4))
instances.gt_classes = torch.tensor([]).to(dtype=torch.int64)
instances.gt_masks = BitMasks(torch.rand(0, h, w))
return instances |
def _binary_round(x):
g = tf.get_default_graph()
with ops.name_scope('BinaryRound') as name:
with g.gradient_override_map({'Round': 'Identity'}):
return tf.round(x, name=name) |
class ChannelBasedDecoder(Decoder):
def __init__(self, list_genome, channels, repeats=None):
super().__init__(list_genome)
self._model = None
self._genome = self.get_effective_genome(list_genome)
self._channels = channels[:len(self._genome)]
if (repeats is not None):
... |
class CamRender(Render):
def __init__(self, width=1600, height=1200, name='Cam Renderer', program_files=['simple.fs', 'simple.vs'], color_size=1, ms_rate=1, egl=False):
Render.__init__(self, width, height, name, program_files, color_size, ms_rate=ms_rate, egl=egl)
self.camera = None
if (not ... |
def build_dataloaders(cfg, settings):
transform_joint = tfm.Transform(tfm.ToGrayscale(probability=0.05), tfm.RandomHorizontalFlip(probability=0.5))
transform_train = tfm.Transform(tfm.ToTensorAndJitter(0.2), tfm.RandomHorizontalFlip_Norm(probability=0.5), tfm.Normalize(mean=cfg.DATA.MEAN, std=cfg.DATA.STD))
... |
def read_tracks(filename):
with open(filename) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
track_dict = dict()
track_id = None
for (i, row) in enumerate(list(csv_reader)):
if (i == 0):
assert (row[KeyEnum.track_id] == Key.track_id)
... |
def Catfish(Node_List, args):
if (args.catfish is None):
pass
else:
Node_List[0].model = Node.init_model(args.catfish)
Node_List[0].optimizer = Node.init_optimizer(Node_List[0].model, args) |
def l1(arr1, arr2):
return (sum([np.abs((a1 - a2)) for (a1, a2) in zip(arr1, arr2)]) / len(arr1)) |
class feat_classifier(nn.Module):
def __init__(self, class_num, bottleneck_dim=256, type='linear'):
super(feat_classifier, self).__init__()
self.type = type
if (type == 'wn'):
self.fc = weightNorm(nn.Linear(bottleneck_dim, class_num), name='weight')
self.fc.apply(init... |
def _is_ci_fork_pull_request():
if os.getenv('TRAVIS'):
if os.getenv('TRAVIS_PULL_REQUEST_BRANCH'):
return True
elif os.getenv('APPVEYOR'):
if os.getenv('APPVEYOR_PULL_REQUEST_NUMBER'):
return True
return False |
def OpenVINOModel(model, device='CPU'):
from .core.model import OpenVINOModel
return OpenVINOModel(model, device) |
def _context_for_ohem():
import sys
from os.path import dirname
sys.path.insert(0, dirname(dirname(dirname(__file__))))
from test_forward import _get_detector_cfg
model = _get_detector_cfg('faster_rcnn/faster_rcnn_r50_fpn_ohem_1x_coco.py')
model['pretrained'] = None
from mmdet.models import ... |
class Level3(torch.nn.Module):
def __init__(self):
super().__init__()
self.layer2 = Level2()
def forward(self, x, y=None):
return self.layer2(x, y) |
('/upload', methods=['POST'])
def upload():
if (request.method == 'POST'):
if ('file' not in request.files):
return jsonify('Need to pass argument filename to request! (empty)')
file = request.files['file']
file_dir = ''.join(random.choices((string.ascii_uppercase + string.digits... |
class Focal_Binary_Loss():
def __init__(self, gamma_indct):
self.gamma_indct = gamma_indct
def robust_pow(self, num_base, num_pow):
return (np.sign(num_base) * (np.abs(num_base) ** num_pow))
def focal_binary_object(self, pred, dtrain):
gamma_indct = self.gamma_indct
label = d... |
class RadarStackedHourglass(nn.Module):
def __init__(self, stacked_num=1):
super(RadarStackedHourglass, self).__init__()
self.stacked_num = stacked_num
self.conv1a = nn.Conv3d(in_channels=2, out_channels=32, kernel_size=(9, 5, 5), stride=(1, 1, 1), padding=(4, 2, 2))
self.conv1b = nn... |
.parametrize('a_val, b_val, x_val, y_val, vector', [(1.0, 1.0, 1.0, 1.0, [10.0, 20.0]), (5.0, 10.0, (- 2.0), 5.0, [0.0, (- 1.0)]), (0.0, 0.0, 1.1, 0.02, [0.0, 0.0]), ((- 2.2), (- 1.5), (- 12.3), 34.8, [2.2, 5.3]), ((- 1.5), 0.0, (- 0.002), 4.93, [0.1, (- 0.02)])])
def test_hessian_vector_product_2x2(a_val, b_val, x_val... |
def _itr_file(input, pattern):
print('Search Patterm:', pattern)
ptn = re.compile(pattern)
for (root, dir, files) in os.walk(input):
for fn in files:
abs_fn = os.path.normpath(os.path.join(root, fn))
m = ptn.match(abs_fn)
if m:
lang = m.groups()
... |
def create_summary_metadata(description, metadata):
ln_proto = LabelToNames()
if ('label_to_names' in metadata):
ln_proto.label_to_names.update(metadata['label_to_names'])
return SummaryMetadata(summary_description=description, plugin_data=SummaryMetadata.PluginData(plugin_name=PLUGIN_NAME, content=... |
class RetriBertTokenizerFast(BertTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
slow_tokenizer_class = RetriBert... |
class WIKIDATA5MLoader():
def __init__(self, path, download=False, download_path=None):
self.path = path
self.download = download
self.download_path = download_path
self.entity_list = list()
self.relation_list = list()
if (self.download == True):
downloade... |
def get_all_answers(data_dir, filtered_by=None):
answers = dict()
files = {filename[:(- 4)] for filename in os.listdir(data_dir)}
for f in files:
answers[f] = get_answers_for_doc((f + '.txt'), data_dir, filtered_by=filtered_by)
return answers |
class UpSample(nn.Sequential):
def __init__(self, skip_input, output_features):
super(UpSample, self).__init__()
self.convA = nn.Conv2d(skip_input, output_features, kernel_size=3, stride=1, padding=1)
self.leakyreluA = nn.LeakyReLU(0.2)
self.convB = nn.Conv2d(output_features, output_... |
def train(cfg, local_rank, distributed):
model = build_detection_model(cfg)
device = torch.device(cfg.MODEL.DEVICE)
model.to(device)
optimizer = make_optimizer(cfg, model)
scheduler = make_lr_scheduler(cfg, optimizer)
use_mixed_precision = (cfg.DTYPE == 'float16')
amp_opt_level = ('O1' if us... |
def to_tree_str(sentence):
words = word_tokenize(sentence.lower())
(enc_input, enc_length) = prepare_input(words)
selections = model.encoder.forward(enc_input, enc_length, return_select_masks=True)[2]
selections = ([s[0].max(0)[1] for s in selections] + [0])
tokens = words.copy()
for i in select... |
class LatentVariable(nn.Module):
def __init__(self, variable_config):
super(LatentVariable, self).__init__()
self.approx_post = self.prior = None
self.variable_config = variable_config
self.inference_procedure = None
self.detach = True
def infer(self, input):
rais... |
class DTN(object):
def __init__(self):
if FLAGS.leaky_relu:
self.active = tf.nn.leaky_relu
else:
self.active = tf.nn.relu
if FLAGS.CDC:
self.conv = Conv2d_cd
else:
self.conv = tf.layers.conv2d
def forward(self, face, depth, IR, trai... |
def run_test(folder_path, override_dict, test_path, snapshot_iter, is_large, save_img_data):
print(('Folder path: %s' % folder_path))
with open(os.path.join(folder_path, 'PARAM.p'), 'rb') as f:
opt0 = pickle.load(f)
opt = recursive_merge_dicts(opt0, override_dict)
vp = Pipeline(None, opt, model_... |
def validate_graph_node(graph_def, node_names):
if (len(node_names) == 0):
return False
all_node_name = [node.name for node in graph_def.node]
for user_name in node_names:
if (user_name not in all_node_name):
logger.warn(str("Node name {} specified in yaml doesn't exist in the mo... |
('/ner', methods=['GET', 'POST'])
def ner():
sentence = request.values.get('sentence')
words = tokenize_toolkit.run(sentence)
ner_result = ner_toolkit.run(words)
return jsonify({'words': words, 'ner_result': [{'mention': words[entity['start']:entity['end']], 'start': entity['start'], 'end': entity['end'... |
def compile_files(raw_dir, raw_files, prefix):
src_fpath = os.path.join(raw_dir, f'raw-{prefix}.src')
trg_fpath = os.path.join(raw_dir, f'raw-{prefix}.trg')
if (os.path.isfile(src_fpath) and os.path.isfile(trg_fpath)):
sys.stderr.write(f'''Merged files found, skip the merging process.
''')
r... |
def _test_cg_gpr(config: ConfigDense, model: GPR, Xnew: tf.Tensor) -> tf.Tensor:
(X, y) = model.data
Kff = model.kernel(X, full_cov=True)
max_rank = (config.num_cond // (2 if (config.num_cond > 1) else 1))
preconditioner = get_default_preconditioner(Kff, diag=model.likelihood.variance, max_rank=max_rank... |
_model
def ssl_resnext101_32x16d(pretrained=True, **kwargs):
model = ResNet(Bottleneck, [3, 4, 23, 3], cardinality=32, base_width=16, **kwargs)
model.default_cfg = default_cfgs['ssl_resnext101_32x16d']
if pretrained:
load_pretrained(model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.ge... |
def test_eval_empty_globals():
assert ('__builtins__' in m.eval_empty_globals(None))
g = {}
assert ('__builtins__' in m.eval_empty_globals(g))
assert ('__builtins__' in g) |
class QuantMeasure(nn.Module):
def __init__(self, num_bits=8, shape_measure=(1,), flatten_dims=_DEFAULT_FLATTEN, inplace=False, dequantize=True, stochastic=False, momentum=0.1, measure=False, per_ch_input=False, reduce_dim=0, cal_qparams=False):
super(QuantMeasure, self).__init__()
self.register_buf... |
def mobilenetv2_100(pretrained=False, **kwargs):
model = _gen_mobilenet_v2('mobilenetv2_100', 1.0, pretrained=pretrained, **kwargs)
return model |
def _get_possible_module_path(paths):
ret = []
for p in paths:
p = Path(p)
for path in p.glob('*'):
if ((path.suffix in ['py', '.so']) or path.is_dir()):
if path.stem.isidentifier():
ret.append(path)
return ret |
class AutoModelForSeq2SeqLMWithValueHead(PreTrainedModelWrapper):
transformers_parent_class = AutoModelForSeq2SeqLM
lm_head_namings = ['lm_head', 'embed_out', 'output_projection']
supported_args = ('summary_dropout_prob', 'v_head_initializer_range', 'v_head_init_strategy')
def __init__(self, pretrained_... |
class E_senet(nn.Module):
def __init__(self, original_model, num_features=2048):
super(E_senet, self).__init__()
self.base = nn.Sequential(*list(original_model.children())[:(- 3)])
def forward(self, x):
x_block0 = nn.Sequential(*list(self.base[0].children())[:(- 1)])(x)
x0 = self... |
def activate_user(trace):
conn = getDb()
with closing(conn.cursor()) as cur:
sql = 'update users set inactive = 0 where activate_trace = %s'
cur.execute(sql, (trace,))
conn.commit()
return (cur.rowcount == 1) |
class ResidualBlock(nn.Module):
def __init__(self, in_features=64, norm_layer=nn.BatchNorm2d):
super(ResidualBlock, self).__init__()
self.relu = nn.ReLU(True)
if (norm_layer == None):
self.block = nn.Sequential(nn.Conv2d(in_features, in_features, 3, 1, 1, bias=False), nn.ReLU(inp... |
def _erase_attention(feature, attention, drop_threshold):
(b, _, h, w) = attention.size()
pos = torch.ge(attention, drop_threshold)
mask = attention.new_ones((b, 1, h, w))
mask[pos.data] = 0.0
erased_feature = (feature * mask)
return erased_feature |
def norm2d(planes, num_channels_per_group=32):
print('num_channels_per_group:{}'.format(num_channels_per_group))
if (num_channels_per_group > 0):
return GroupNorm2d(planes, num_channels_per_group, affine=True, track_running_stats=False)
else:
return nn.BatchNorm2d(planes) |
_UTILS.register_module()
class UniformAssigner(BaseAssigner):
def __init__(self, pos_ignore_thr: float, neg_ignore_thr: float, match_times: int=4, iou_calculator: ConfigType=dict(type='BboxOverlaps2D')):
self.match_times = match_times
self.pos_ignore_thr = pos_ignore_thr
self.neg_ignore_thr ... |
def filter_instances(ds, instance_tokens):
filtered_tokens = []
for inst_token in instance_tokens:
instance = ds.get('instance', inst_token)
agent = ds.get('agent', instance['agent_token'])
if (agent['type'] not in {'Pedestrian', 'Undefined'}):
try:
if (ds.get... |
class MetaConv2d(MetaModule):
def __init__(self, *args, **kwargs):
super().__init__()
ignore = nn.Conv2d(*args, **kwargs)
self.stride = ignore.stride
self.padding = ignore.padding
self.dilation = ignore.dilation
self.groups = ignore.groups
self.register_buffer... |
_module()
class NumClassCheckHook(Hook):
def _check_head(self, runner):
model = runner.model
dataset = runner.data_loader.dataset
if (dataset.CLASSES is None):
runner.logger.warning(f'Please set `CLASSES` in the {dataset.__class__.__name__} andcheck if it is consistent with the `... |
class Transformer_16(nn.Module):
def __init__(self):
super(Transformer_16, self).__init__()
self.name = 'Transformer_16'
self.lr = 0.0001
self.n_hosts = 16
feats = (3 * self.n_hosts)
self.n_feats = (3 * self.n_hosts)
self.n_window = 3
self.n_latent = 1... |
class Sampler(abc.ABC):
def start_worker(self):
def obtain_samples(self, itr, batch_size, whole_paths):
def shutdown_worker(self): |
def load_img_info(files, split):
assert isinstance(files, tuple)
assert isinstance(split, str)
(img_file, gt_file) = files
img = mmcv.imread(img_file, 'unchanged')
split_name = osp.basename(osp.dirname(img_file))
img_info = dict(file_name=osp.join(split_name, osp.basename(img_file)), height=img.... |
def DefineActions():
actions = []
for ii in range(len(PossiblePath)):
PosA = PossiblePath[ii][0]
PosB = PossiblePath[ii][1]
actions.append((((('BS(XXX,' + PosA) + ',') + PosB) + ')'))
actions.append((((('LI(XXX,' + PosA) + ',') + PosB) + ')'))
for ii in range(6):
Pos ... |
class WriteTSV(ResultWriter):
extension: str = 'tsv'
def write_result(self, result: dict, file: TextIO, options: dict):
print('start', 'end', 'text', sep='\t', file=file)
for segment in result['segments']:
print(round((1000 * segment['start'])), file=file, end='\t')
print... |
def cli_main():
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser)
if (args.distributed_init_method is None):
distributed_utils.infer_init_method(args)
if (args.distributed_init_method is not None):
if ((torch.cuda.device_count() > 1) and (not args.distribu... |
class DatasetFolder(data.Dataset):
def __init__(self, root, loader, extensions, transform=None, target_transform=None):
(classes, class_to_idx) = self._find_classes(root)
samples = make_dataset(root, class_to_idx, extensions)
if (len(samples) == 0):
raise RuntimeError(((('Found 0... |
class CatBoostEncoderTransformer(AutotabularPreprocessingAlgorithm):
def __init__(self, cols=None, random_state: Optional[np.random.RandomState]=None):
self.cols = cols
self.random_state = random_state
def fit(self, X: PIPELINE_DATA_DTYPE, y: Optional[PIPELINE_DATA_DTYPE]=None) -> 'CatBoostEncod... |
class SpatialAttentionBlock3d(nn.Module):
def __init__(self, in_channels):
super(SpatialAttentionBlock3d, self).__init__()
self.query = nn.Conv3d(in_channels, (in_channels // 8), kernel_size=(1, 3, 1), padding=(0, 1, 0))
self.key = nn.Conv3d(in_channels, (in_channels // 8), kernel_size=(3, 1... |
class Sign2TextTransformerEncoder(FairseqEncoder):
def __init__(self, cfg):
super().__init__(None)
self.encoder_freezing_updates = cfg.encoder_freezing_updates
self.num_updates = 0
self.dropout_module = FairseqDropout(p=cfg.dropout, module_name=self.__class__.__name__)
self.e... |
class MinibatchLayer(lasagne.layers.Layer):
def __init__(self, incoming, num_kernels, dim_per_kernel=5, theta=lasagne.init.Normal(0.05), log_weight_scale=lasagne.init.Constant(0.0), b=lasagne.init.Constant((- 1.0)), **kwargs):
super(MinibatchLayer, self).__init__(incoming, **kwargs)
self.num_kernels... |
def validate_pytorch_model(platform, device_type, model_file, input_file, mace_out_file, input_names, input_shapes, input_data_formats, output_names, output_shapes, output_data_formats, validation_threshold, input_data_types, output_data_types, log_file):
import torch
loaded_model = torch.jit.load(model_file)
... |
def pdist_torch(emb1, emb2):
(m, n) = (emb1.shape[0], emb2.shape[0])
emb1_pow = torch.pow(emb1, 2).sum(dim=1, keepdim=True).expand(m, n)
emb2_pow = torch.pow(emb2, 2).sum(dim=1, keepdim=True).expand(n, m).t()
dist_mtx = (emb1_pow + emb2_pow)
dist_mtx = dist_mtx.addmm_(emb1, emb2.t(), beta=1, alpha=(... |
class MrpcProcessor(DataProcessor):
def get_train_examples(self, data_dir):
logger.info('LOOKING AT {}'.format(os.path.join(data_dir, 'train.tsv')))
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'train.tsv')), 'train')
def get_dev_examples(self, data_dir):
return sel... |
def levi_hassner_bn(nlabels, images, pkeep, is_training):
batch_norm_params = {'is_training': is_training, 'trainable': True, 'decay': 0.9997, 'epsilon': 0.001, 'variables_collections': {'beta': None, 'gamma': None, 'moving_mean': ['moving_vars'], 'moving_variance': ['moving_vars']}}
weight_decay = 0.0005
w... |
def train_calibration(calibration_loader, model_rgb, model_depth, model_discriminator, model_estimator, optimizer_dis, optimizer_estimator, epoch, key_min):
model_rgb.eval()
model_depth.eval()
model_discriminator.train()
model_estimator.train()
for (i, pack) in enumerate(tqdm(calibration_loader), st... |
class BatchSamplerImagesSameLength(object):
def __init__(self, dataset, batch_size):
assert ((type(dataset) == CocoCaptionsIndexedImage) or (type(dataset) == CocoCaptionsIndexedImageDistill))
self.img2bpes = dataset.img2bpes
self.bpes = dataset.bpes
lengths = []
img_keys = se... |
def logging_level(level: int):
_initial = getLoggingLevel()
setLoggingLevel(level)
try:
(yield)
finally:
setLoggingLevel(_initial) |
def number_literal(number):
x_str = str(number)
if (x_str in number_mappings):
return number_mappings[x_str]
x_str_left = x_str[0]
x_str_right = x_str[1:].lstrip('0')
if (len(x_str) == 8):
x_str_left = x_str[0:2]
x_str_right = x_str[2:].lstrip('0')
if (x_str_right != ... |
def _split_data(x, y, k_idx, k, perm_indices):
assert (k > 0)
assert (k_idx >= 0)
assert (k_idx < k)
N = len(x)
partition_size = int(ceil((N / k)))
minority_start = (k_idx * partition_size)
minority_end = (minority_start + partition_size)
minority_indices = perm_indices[minority_start:mi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.