code stringlengths 101 5.91M |
|---|
def false_negative_edges(true_adj, pred_adj, abs_tol=0.5):
diff = remove_diag((true_adj - pred_adj))
return num_incorrect(diff, abs_tol) |
class MMBTModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class WeightedSumAndMax(nn.Module):
def __init__(self, in_feats):
super(WeightedSumAndMax, self).__init__()
self.weight_and_sum = WeightAndSum(in_feats)
self.out_dim = (2 * in_feats)
def forward(self, bg, feats):
h_g_sum = self.weight_and_sum(bg, feats)
with bg.local_scop... |
class TFDistilBertForMaskedLM():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
class Processor(object):
def __init__(self, vocab_file, max_seq_length):
self.tokenizer = tokenization.FullTokenizer(vocab_file=vocab_file)
self.idx_to_word = self.inverse_vocab(self.tokenizer.vocab)
self.max_seq_length = max_seq_length
def inverse_vocab(vocab):
idx_to_word = {}
... |
def test_and_exchange_map(tester, model, distributed):
results = tester(model=model, distributed=distributed)
if is_main_process():
(map_results, raw_results) = results[0]
bbox_map = map_results.results['bbox']['AP']
segm_map = map_results.results['segm']['AP']
else:
bbox_map... |
class GPTJForQuestionAnswering(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def gpt_generate_causal_events(db_base_name, gpt, pred_data, source_data, inference_type: str='type', top_k: int=5, num_threads: int=16):
msg_head = 'Now I give you an effect event, and you give me three to four cause events.\n\n'
def _process_one_type_or_time(idx, type_or_date, text):
try:
... |
def reset():
global _running_timer
_total_times.clear()
_start_times.clear()
_timer_stack.clear()
_running_timer = None |
def create_model(opt):
model = None
print(opt.model)
if (opt.model == 'shiftnet'):
assert ((opt.dataset_mode == 'aligned') or (opt.dataset_mode == 'aligned_resized'))
from models.shift_net.shiftnet_model import ShiftNetModel
model = ShiftNetModel()
elif (opt.model == 'res_shiftne... |
def evaluate(model, dataset, data):
batch = dataset.get_batch(data)
tot_loss = 0
tot_cnt = 0
while True:
try:
batchInput = dataset.next_batch(batch)
(global_step, loss) = model.eval(batchInput)
slens = batchInput.slens
tot_cnt += len(slens)
... |
def parse_cmd_options(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--batch_size', type=int, default=None, help='number of instances in one mini-batch.')
parser.add_argument('--input_image_size', type=int, default=None, help='resolution of input image, usually 32 for CIFAR and 224 for Image... |
def WideResNet28x20(num_classes=10, activation='relu', dropRate=0.0, return_feature_map=False):
return WideResNet(28, num_classes, 20, activation=activation, dropRate=dropRate, return_feature_map=return_feature_map) |
def makedirs(path):
try:
os.makedirs(path)
except OSError as exc:
if (exc.errno != errno.EEXIST):
raise |
class BatchNorm(nn.Module):
def __init__(self, input_size, momentum=0.9, eps=1e-05):
super().__init__()
self.momentum = momentum
self.eps = eps
self.log_gamma = nn.Parameter(torch.zeros(input_size))
self.beta = nn.Parameter(torch.zeros(input_size))
self.register_buffe... |
def pre_transform(data_ori):
data = data_ori.clone()
(data.edge_index, data.edge_type, data.input) = (standard_edge_index, standard_edge_type, standard_node_fea)
return data |
def create_dir(path):
if (not os.path.exists(path)):
try:
os.makedirs(path)
except OSError as exc:
if (exc.errno != errno.EEXIST):
raise |
def recreate_dirs(*dirs):
for d in dirs:
if os.path.exists(d):
shutil.rmtree(d)
os.makedirs(d) |
def loss_calculation(semantic, target):
bs = semantic.size()[0]
pix_num = (480 * 640)
target = target.view(bs, (- 1)).view((- 1)).contiguous()
semantic = semantic.view(bs, 22, pix_num).transpose(1, 2).contiguous().view((bs * pix_num), 22).contiguous()
semantic_loss = CEloss(semantic, target)
ret... |
def format_results(results_df, config_list, param_list):
config_df = pd.DataFrame.from_dict(config_list)
keep = list(set([list(hyper_option.option.keys())[0] for hyper_option in param_list]))
keep.append(ConfigKW.PATH_OUTPUT)
config_df = config_df[keep]
results_df = config_df.set_index(ConfigKW.PATH... |
def make_custom_seris_splitter(preset_names):
legendNote = None
if (preset_names == 'default'):
def custom_series_splitter(x):
params = x['flat_params']
if (params['her_failed_goal_option'] is None):
ret = 'Distance Reward'
elif (params['her_failed_goa... |
class TestLookaheadSwap(QiskitTestCase):
def test_lookahead_swap_doesnt_modify_mapped_circuit(self):
qr = QuantumRegister(3, name='q')
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[2])
circuit.cx(qr[0], qr[1])
original_dag = circuit_to_dag(circuit)
coupling_map = ... |
def unpack_tracking_results(download_path, output_path=None):
if (output_path is None):
output_path = env_settings().results_path
if (not os.path.exists(output_path)):
os.makedirs(output_path)
trackers = os.listdir(download_path)
for t in trackers:
runfiles = os.listdir(os.path.j... |
def search(query_ids: np.ndarray, query_embeds: np.ndarray, corpus_ids: np.ndarray, index: faiss.IndexPQ, topk: int):
(topk_scores, topk_idx) = index.search(query_embeds, topk)
topk_ids = np.vstack([corpus_ids[x] for x in topk_idx])
assert (len(query_ids) == len(topk_scores) == len(topk_ids))
return (to... |
class SkipBlock(nn.Module):
def __init__(self, in_channel, out_channel, kernel_size, bias, pad, act_fun):
super(SkipBlock, self).__init__()
self.op = nn.Sequential(conv(in_f=in_channel, out_f=out_channel, kernel_size=kernel_size, bias=bias, pad=pad), bn(num_features=out_channel), act(act_fun=act_fun... |
def qualification_loss(x_minus, x_plus, y_minus, y_plus, a, b, c, confidence=(- 0.1)):
alpha1 = torch.sigmoid(y_minus)
loss1 = ts.tanh_lower(alpha1, a, ((b * y_minus) + c), x_minus, x_plus, plot=False, num=0)
valid = (loss1 <= 0)
loss1 = torch.clamp(loss1, min=confidence)
alpha2 = torch.sigmoid((y_m... |
def update_datasets(self_adaptation=False):
if (cfg.db_name == 'AwA2'):
cfg.data_root = './data/AwA2/'
cfg.attr_dims = 85
cfg.nseen = 40
elif (cfg.db_name == 'CUB'):
cfg.data_root = './data/CUB/'
cfg.attr_dims = 312
cfg.nseen = 150
elif (cfg.db_name == 'SUN'):... |
class GroupedBatchSampler(BatchSampler):
def __init__(self, sampler, group_ids, batch_size, drop_uneven=False):
if (not isinstance(sampler, Sampler)):
raise ValueError('sampler should be an instance of torch.utils.dataset.Sampler, but got sampler={}'.format(sampler))
self.sampler = sampl... |
def update_q(critic: Model, target_value: Model, batch: Batch, discount: float) -> Tuple[(Model, InfoDict)]:
next_v = target_value(batch.next_observations)
target_q = (batch.rewards + ((discount * batch.masks) * next_v))
def critic_loss_fn(critic_params: Params) -> Tuple[(jnp.ndarray, InfoDict)]:
(q... |
_module
class Tusimple(nn.Module):
def __init__(self, cfg):
super(Tusimple, self).__init__()
self.cfg = cfg
exp_dir = os.path.join(self.cfg.work_dir, 'output')
if (not os.path.exists(exp_dir)):
os.mkdir(exp_dir)
self.out_path = os.path.join(exp_dir, 'coord_output'... |
_materialize('core')
class ConstPad(Pad):
def __init__(self, *padding_list):
super().__init__(padding_list, 'constant') |
class OnlineItemSimilarity():
def __init__(self, item_size):
self.item_size = item_size
self.item_embeddings = None
self.cuda_condition = torch.cuda.is_available()
self.device = torch.device(('cuda' if self.cuda_condition else 'cpu'))
self.total_item_list = torch.tensor([i fo... |
class Block(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, expand_ratio=1, se_ratio=0.0, drop_rate=0.0):
super(Block, self).__init__()
self.stride = stride
self.drop_rate = drop_rate
self.expand_ratio = expand_ratio
channels = (expand_ratio * i... |
class ConvNet(nn.Module):
def __init__(self, input_size=(1, 257, 1091)):
super(ConvNet, self).__init__()
self.features = nn.Sequential(nn.Conv2d(1, 32, kernel_size=(3, 3), padding=(2, 2), dilation=(2, 2)), nn.BatchNorm2d(32), nn.ReLU(), nn.Conv2d(32, 32, kernel_size=(3, 3), padding=(2, 2), dilation=... |
def mahalanobis_metric(p, S, args):
mu_S = torch.mean(S, dim=0, keepdim=True)
cov_S = torch.matmul((S - mu_S).t(), (S - mu_S))
I = torch.eye(p.shape[1], p.shape[1])
if args.CUDA:
I = Variable(I).cuda()
covi_S = (cov_S + (args.cov_gamma * I)).inverse()
mahalanobis_distances = (p - mu_S).m... |
def parse_json(embeddings):
embeddings.sort_index(inplace=True)
X = np.zeros((len(embeddings), (3 * 768)))
for i in range(len(embeddings)):
A = np.array(embeddings.loc[(i, 'emb_A')])
B = np.array(embeddings.loc[(i, 'emb_B')])
P = np.array(embeddings.loc[(i, 'emb_P')])
X[i] = ... |
def row_accuracy(row, model):
y = np.array([row['A'], row['B'], row['N']])
pred = np.array([row[(model + '-A')], row[(model + '-B')], row[(model + '-N')]])
return y[np.argmax(pred)] |
def get_dtype_and_ctype(type_obj: Any) -> Tuple[(np.dtype, Any)]:
type_str = None
if isinstance(type_obj, str):
type_str = type_obj
elif hasattr(type_obj, '__name__'):
type_str = type_obj.__name__
elif hasattr(type_obj, 'name'):
type_str = type_obj.name
else:
raise Ru... |
def pad_all_cases(x, y, model_params, min_len_before=7, max_len_before=9, min_len_after=7, max_len_after=9, targetlength=9):
total_x = []
total_y = []
total_len_x = []
totle_len_before_x = []
for l_before in range(min_len_before, (max_len_before + 1)):
for l_after in range(min_len_after, (ma... |
def retry_with_exponential_backoff(errors: tuple, initial_delay: float=30, exponential_base: float=2, jitter: bool=True, max_retries: int=5):
def decorator(func):
(func)
def wrapper(*args, **kwargs):
num_retries = 0
delay = initial_delay
while True:
... |
class MetaSingletonHash(type):
def __call__(*args, **kwargs):
cls = args[0]
try:
cache = cls._cache
except:
cache = dict()
cls._cache = cache
obj = type.__call__(*args, **kwargs)
key = (cls.__name__, obj.__hash__())
return cache.set... |
def evaluate_2nd_item_task_fastgcnnew(valid_batch_index, model, sess, valid_data, is_training):
(evaluate_loss, evaluate_pearson) = (0.0, 0.0)
(valid_target_item, valid_k_shot_user, valid_second_order_items, valid_third_order_users, valid_oracle_item_ebd, valid_mask_num_second_order_item, valid_mask_num_third_o... |
class ReusableHyperOptimizer(PathOptimizer):
suboptimizer = HyperOptimizer
set_surface_order = False
def __init__(self, *, directory=None, overwrite=False, hash_method='a', cache_only=False, **opt_kwargs):
self._suboptimizers = {}
self._suboptimizer_kwargs = opt_kwargs
if (directory ... |
def _train():
arg_parser = train_argparser()
process_configs(target=__train, arg_parser=arg_parser) |
class Path():
def __init__(self, x_list, y_list, yaw_list, direction_list, cost):
self.x_list = x_list
self.y_list = y_list
self.yaw_list = yaw_list
self.direction_list = direction_list
self.cost = cost |
def _build_man_feature_extractor(feature_extractor_config, is_training, reuse_weights=None):
depth_multiplier = feature_extractor_config.depth_multiplier
min_depth = feature_extractor_config.min_depth
conv_hyperparams = hyperparams_builder.build(feature_extractor_config.conv_hyperparams, is_training)
re... |
.no_cover
.mujoco
.timeout(300)
def test_te_ppo_metaworld_mt10():
assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'tf/te_ppo_metaworld_mt10.py')), '--n_epochs', '1', '--batch_size_per_task', '100'], check=False).returncode == 0) |
def init_args():
parser = argparse.ArgumentParser(description='Convert cartesian coordinate system to site-center NEU.')
parser.add_argument('-x0', metavar='<x0>', dest='x0', type=float, help='topocentric X coordinate.')
parser.add_argument('-y0', metavar='<y0>', dest='y0', type=float, help='topocentric Y c... |
class NeuralProcessImg(nn.Module):
def __init__(self, img_size, r_dim, z_dim, h_dim):
super(NeuralProcessImg, self).__init__()
self.img_size = img_size
(self.num_channels, self.height, self.width) = img_size
self.r_dim = r_dim
self.z_dim = z_dim
self.h_dim = h_dim
... |
def parse_args():
parser = argparse.ArgumentParser('Official evaluation script for SQuAD version 2.0.')
parser.add_argument('data_file', metavar='data.json', help='Input data JSON file.')
parser.add_argument('pred_file', metavar='pred.json', help='Model predictions.')
parser.add_argument('--out-file', '... |
class ImagePipelineOutput(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch'])
def from_pretrained(cls, *args, **kwargs):
requires_backends(cl... |
def main():
parser = argparse.ArgumentParser('Save data from SQL to disk')
parser.add_argument('dest', help='Location to save the data to')
parser.add_argument('--format', default='text', help='Format to save data in')
parser.add_argument('--arch', type=int, help='Architecture of data to pull', required... |
def to_bh(data, bins, cumulative=False):
h1 = bh.Histogram(bh.axis.Variable(bins))
h1.fill(data)
if cumulative:
h1[:] = (np.sum(h1.values()) - np.cumsum(h1))
return h1 |
def padded_sequence_accuracy(logits, labels):
with tf.compat.v1.variable_scope('padded_sequence_accuracy', values=[logits, labels]):
(logits, labels) = _pad_tensors_to_same_length(logits, labels)
weights = tf.cast(tf.not_equal(labels, 0), dtype=tf.float32)
outputs = tf.cast(tf.argmax(input=l... |
def get_original_source_tweet(source_tweet_json: dict):
if ('retweeted_status' in source_tweet_json):
return source_tweet_json['retweeted_status'] |
def reset():
if (Logger.CURRENT is not Logger.DEFAULT):
Logger.CURRENT.close()
Logger.CURRENT = Logger.DEFAULT
log('Reset logger') |
class EncoderLayer(nn.Module):
def __init__(self, attention, d_model, d_ff=None, dropout=0.1, activation='relu'):
super(EncoderLayer, self).__init__()
d_ff = (d_ff or (4 * d_model))
self.attention = attention
self.conv1 = nn.Conv1d(in_channels=d_model, out_channels=d_ff, kernel_size=... |
_tokenizers
class SqueezeBertTokenizationTest(BertTokenizationTest):
tokenizer_class = SqueezeBertTokenizer
rust_tokenizer_class = SqueezeBertTokenizerFast
test_rust_tokenizer = True
def get_rust_tokenizer(self, **kwargs):
return SqueezeBertTokenizerFast.from_pretrained(self.tmpdirname, **kwargs... |
def calc_all_metrics(pred):
res = {}
ic = pred.groupby(level='datetime').apply((lambda x: robust_zscore(x.label).corr(robust_zscore(x.score))))
raw_ic = pred.groupby(level='datetime').apply((lambda x: x.label.corr(x.score)))
rank_ic = pred.groupby(level='datetime').apply((lambda x: x.label.corr(x.score,... |
class StartPage(tk.Frame):
def __init__(self, parent, controller):
global start_page
tk.Frame.__init__(self, parent)
start_page = self
self.target_image = ''
self.controller = controller
self.pil_image = None
self.opencv_image_r_g_b = None
self.top = t... |
def _get_model(model_src, model_config=None):
model_src = model_src.lower()
model_config = (model_config or {})
if (model_src == 'onnx'):
return Onnx(**model_config)
if (model_src == 'huggingface'):
return Huggingface(**model_config)
if (model_src == 'sbert'):
return SBERT(**... |
class FlowCutterOptimizer(PathOptimizer):
def __init__(self, max_time=10, seed=None, executable='flow_cutter_pace17'):
self.max_time = max_time
self.seed = seed
self.executable = executable
def run_flowcutter(self, file, max_time=None):
if (max_time is None):
max_time... |
class MultiDatasetFastRCNNOutputLayers(CustomFastRCNNOutputLayers):
def __init__(self, cfg, num_classes_list, input_shape: ShapeSpec, **kwargs):
super().__init__(cfg, input_shape, **kwargs)
del self.cls_score
input_size = ((input_shape.channels * (input_shape.width or 1)) * (input_shape.heig... |
def draw_demo_img_corners(img, projectpts, color=(0, 255, 0), nV=9, thickness=2):
vertices = []
for i in range(nV):
x = projectpts[i][0]
y = projectpts[i][1]
coordinates = (int(x), int(y))
vertices.append(coordinates)
cv2.circle(img, coordinates, 2, color, (- 1))
cv2.... |
def pd2(base_directory: Path) -> GermanClarinCorpus:
return GermanClarinCorpus('all.PD2.4.cmdi.16693.', base_directory) |
def train_epoch(model, training_data, optimizer, ema, device, opt, writer, epoch):
model.train()
total_loss = 0
n_word_total = 0
n_word_correct = 0
torch.autograd.set_detect_anomaly(True)
for (batch_idx, batch) in tqdm(enumerate(training_data), mininterval=2, desc=' Training =>', total=len(trai... |
class Adapter(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.input_dim = config.input_dim
self.down_sample_size = (self.input_dim // config.reduction_factor)
self.activation = Activations(config.non_linearity.lower())
self.down_sa... |
class MVTecAD(Dataset):
def __init__(self, image_list, label_list, transform):
self.image_list = image_list
self.label_list = label_list
self.transform = transform
def __getitem__(self, index):
image = Image.open(self.image_list[index])
label = self.label_list[index]
... |
_module()
class SemiPSPHead(SemiBaseDecodeHead):
def __init__(self, pool_scales=(1, 2, 3, 6), **kwargs):
super(SemiPSPHead, self).__init__(**kwargs)
assert isinstance(pool_scales, (list, tuple))
self.pool_scales = pool_scales
self.psp_modules = PPM(self.pool_scales, self.in_channels,... |
_config
def model_lifelong_finetune_std_taskonomy():
cfg = {'learner': {'model': 'LifelongSidetuneNetwork', 'model_kwargs': {'base_class': 'GenericSidetuneNetwork', 'base_kwargs': {'n_channels_in': 3, 'n_channels_out': 8, 'base_class': 'TaskonomyEncoder', 'base_kwargs': {'eval_only': False, 'normalize_outputs': Fal... |
def amp_context(amp_config=None):
if (amp_config is not None):
(yield autocast(**amp_config))
else:
(yield None) |
class ASPP(nn.Module):
def __init__(self, inplanes, output_stride):
super(ASPP, self).__init__()
self.inplanes = inplanes
self.outplanes = output_stride
mid_planes = 16
dilations = [1, 2, 6]
self.aspp1 = _ASPPModule(inplanes, mid_planes, 1, padding=0, dilation=dilatio... |
def calculate_disp_diff(disp_map, ref_disp_map):
(ref_heigth, ref_width) = ref_disp_map.shape[:2]
disp_map = cv2.resize(disp_map, (ref_width, ref_heigth), cv2.INTER_CUBIC)
return np.abs((ref_disp_map - disp_map)) |
def test_digits_stochastic():
model = MaxCoverageSelection(100, optimizer='stochastic', random_state=0)
model.fit(X_digits)
assert_array_equal(model.ranking, digits_stochastic_ranking)
assert_array_almost_equal(model.gains, digits_stochastic_gains, 4)
assert_array_almost_equal(model.subset, X_digits... |
def load_config(custom_config, default_config=CONFIG, prefix='CONFIG'):
if ('is_default' in default_config):
default_config.is_default = False
for key in custom_config.keys():
full_key = '.'.join([prefix, key])
if (key not in default_config):
raise NotImplementedError('Unknow... |
_module()
class Posterize(object):
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), f'The prob should be in range [0,1], got {prob} instead.'
self.bits = int(bits)
self.prob = prob
def __call__... |
class Contrast(object):
def __init__(self, var):
self.var = var
def __call__(self, img):
gs = Grayscale()(img)
gs.fill_(gs.mean())
alpha = random.uniform(0, self.var)
return img.lerp(gs, alpha) |
class PanguFileSystem(AbstractFileSystem):
PANGU_BLOCK_SIZE = ((1024 * 1024) * 64)
FILE_TYPE_NORMAL = 0
FILE_TYPE_LOGFILE = 2
FILE_TYPE_RAIDFILE = 3
FLAG_GENERIC_READ = 1
FLAG_SEQUENTIAL_READ = 4
FLAG_SEQUENTIAL_WRITE = 8
def _to_exception(cls, err, path):
if (err < 0):
... |
def get_input_encoding(inputs, initializer=None, scope=None):
with tf.variable_scope(scope, 'Encoding', initializer=initializer):
(_, _, max_sentence_length, embedding_size) = inputs.get_shape().as_list()
positional_mask = tf.get_variable(name='positional_mask', shape=[max_sentence_length, embedding... |
class Hyperparams(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value |
def _RowwiseUnsortedSegmentSum(values, indices, n):
(batch, k) = tf.unstack(tf.shape(indices), num=2)
indices_flat = (tf.reshape(indices, [(- 1)]) + (tf.div(tf.range((batch * k)), k) * n))
ret_flat = tf.unsorted_segment_sum(tf.reshape(values, [(- 1)]), indices_flat, (batch * n))
return tf.reshape(ret_fl... |
def fully_connected(input_, output_dim, name='fc'):
shape = input_.shape
return conv3d(input_, output_dim, kernal=list(shape[1:4]), strides=(1, 1, 1), padding='VALID', name=name) |
def get_1x_lr_params(model):
b = [model.resnet_features]
for i in range(len(b)):
for k in b[i].parameters():
if k.requires_grad:
(yield k) |
_grad()
def evaluate(data_loader_query, data_loader_gallery, encoder, device, log_writer=None, rank=[1, 5, 10]):
encoder.eval()
recall_list = []
query_features = []
query_labels = []
for (images, targets) in tqdm(data_loader_query, total=len(data_loader_query), desc='query'):
images = images... |
def resnext50_32x4d(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
kwargs['groups'] = 32
kwargs['width_per_group'] = 4
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) |
class Non_local(nn.Module):
def __init__(self, in_channels, reduc_ratio=2):
super(Non_local, self).__init__()
self.in_channels = in_channels
self.inter_channels = (reduc_ratio // reduc_ratio)
self.g = nn.Sequential(nn.Conv2d(in_channels=self.in_channels, out_channels=self.inter_chann... |
class AdMapAccessPythonTest(unittest.TestCase):
def test_interface(self):
self.assertTrue(ad.map.access.init('test_files/TPK.adm.txt'))
lanes = ad.map.lane.getLanes()
self.assertEqual(len(lanes), 141)
mapMatching = ad.map.match.AdMapMatching()
geoPoint = ad.map.point.GeoPoint... |
(version='2.0')
def get_node_mapping(fp32_model, fp32_onnx_path):
def check_data(op_type, data, module_dict):
for (name, value) in module_dict.items():
if (value.shape == data.shape):
if (value == data).all():
module_dict.pop(name)
return n... |
def set_object_pose(position, orientation):
bpy.context.object.location = position
bpy.context.object.rotation_quaternion = orientation |
class LogitBijection(ElementwiseBijection):
_EPS = 1e-07
def _F(self, x):
return (torch.log(x) - torch.log((1 - x)))
def _F_inv(self, z):
return torch.sigmoid(z)
def _log_dF(self, x):
x_clamped = x.clamp(self._EPS, (1 - self._EPS))
return ((- torch.log(x_clamped)) - torch... |
class UniversalDependenciesRawDatasetReader(UniversalDependenciesDatasetReader):
def __init__(self, language):
super().__init__()
self.tokenizer = SpacyWordSplitter(language=language, pos_tags=True)
def load(self, file_path):
file_path = cached_path(file_path)
counter = 1
... |
def get_candidate_representation(candidate_desc, tokenizer, max_seq_length, candidate_title=None, title_tag=ENT_TITLE_TAG):
cls_token = tokenizer.cls_token
sep_token = tokenizer.sep_token
cand_tokens = tokenizer.tokenize(candidate_desc)
if (candidate_title is not None):
title_tokens = tokenizer.... |
class _Transition(nn.Sequential):
def __init__(self, num_input_features, num_output_features, downsample=True):
super(_Transition, self).__init__()
self.add_module('norm', nn.BatchNorm2d(num_input_features))
self.add_module('relu', nn.ReLU(inplace=True))
self.add_module('conv', nn.Co... |
def random_adjust_brightness(img, brightness_factor):
if (not _is_pil_image(img)):
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
if (random.random() < PROB_THRESHOLD):
return img
enhancer = ImageEnhance.Brightness(img)
img = enhancer.enhance(brightness_factor)
... |
def _upgrade_state_dict(state):
from fairseq import models, registry, tasks
if ('optimizer_history' not in state):
state['optimizer_history'] = [{'criterion_name': 'CrossEntropyCriterion', 'best_loss': state['best_loss']}]
state['last_optimizer_state'] = state['optimizer']
del state['opt... |
def parse_args(args):
parser = argparse.ArgumentParser()
parser.add_argument('--config', type=str, required=True, help='Path to configuration file')
parser.add_argument('--device', type=str, required=True, default='cpu', help='Training device')
(parsed_args, errors) = parser.parse_known_args(args[1:])
... |
class TestGraphOptmizationFP32(unittest.TestCase):
_random()
def test_graph_optimization_without_yaml_without_precisions(self):
x = tf.compat.v1.placeholder(tf.float32, [1, 56, 56, 16], name='input')
top_relu = tf.nn.relu(x)
paddings = tf.constant([[0, 0], [1, 1], [1, 1], [0, 0]])
... |
class make_type_selector():
def __init__(self, pattern):
self.pattern = pattern
def __call__(self, X_df):
renamer = get_renamer(X_df)
_X_df = X_df.rename(columns=renamer)
reverse_renamer = {new_name: name for (name, new_name) in renamer.items()}
selected_columns = make_co... |
class DeconvBlock(torch.nn.Module):
def __init__(self, fin, fout):
super(DeconvBlock, self).__init__()
self.conv = torch.nn.Conv2d(fin, fout, kernel_size=4, stride=2, padding=1, bias=False)
self.bn = torch.nn.BatchNorm2d(fout)
self.act = torch.nn.LeakyReLU(0.2, inplace=False)
def... |
(argument('-q', '--quiet', action='store_true', help='only display numeric ids'), argument('-s', '--start_date', help='start date and time for report. Many formats accepted (optional)', type=str), argument('-e', '--end_date', help='end date and time for report. Many formats accepted (optional)', type=str), argument('-c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.