code stringlengths 101 5.91M |
|---|
def ter_ref_files_gen(b_reduced, param, three_ref_only=False):
out = ''
for (iter, entry) in enumerate(b_reduced.entries):
id_str = ('id' + str((iter + 1)))
for (i, lex) in enumerate(entry.lexs):
sent_clean = ' '.join(re.split('(\\W)', lex.lex))
sent_clean = ' '.join(sent... |
def _parse_eq_to_pure_multiplication(a_term, shape_a, b_term, shape_b, out):
desired_a = ''
desired_b = ''
new_shape_a = []
new_shape_b = []
for ix in out:
if (ix in a_term):
desired_a += ix
new_shape_a.append(shape_a[a_term.index(ix)])
else:
new_s... |
class BasicFuseMotion(nn.Module):
def __init__(self, args):
super(BasicFuseMotion, self).__init__()
cor_planes = args.motion_feature_dim
out_planes = args.query_latent_dim
self.normf1 = nn.InstanceNorm2d(128)
self.normf2 = nn.InstanceNorm2d(128)
self.convf1 = nn.Conv2... |
def run_experiment(experiment, configs, args, mods=None, **kwargs):
if ('explogger_kwargs' not in kwargs):
kwargs['explogger_kwargs'] = dict(folder_format='{experiment_name}_%Y%m%d-%H%M%S')
if ('explogger_freq' not in kwargs):
kwargs['explogger_freq'] = 1
if ('resume_save_types' not in kwarg... |
class HierarchicalDataset():
def __init__(self, dataset_directory, dataset_name, batch_size):
self.seed = 33
self.batch_size = batch_size
self.dataset_directory = dataset_directory
self.dataset_name = dataset_name
assert os.path.exists(dataset_directory), '[-] Dataset path {}... |
class MyGroupNorm(nn.GroupNorm):
def __init__(self, num_channels, eps=1e-05, affine=True, num_groups=8):
super(MyGroupNorm, self).__init__(num_groups, num_channels, eps, affine) |
class BaselineClassifierAlgorithm(SklearnAlgorithm):
algorithm_name = 'Baseline Classifier'
algorithm_short_name = 'Baseline'
def __init__(self, params):
super(BaselineClassifierAlgorithm, self).__init__(params)
logger.debug('BaselineClassifierAlgorithm.__init__')
self.library_versio... |
def get_atom_feature_dims():
return list(map(len, [allowable_features['possible_atomic_num_list'], allowable_features['possible_chirality_list'], allowable_features['possible_degree_list'], allowable_features['possible_formal_charge_list'], allowable_features['possible_numH_list'], allowable_features['possible_numb... |
class TFBartPretrainedModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def get_out_bins(start, end, id_date, n_bins, time_bin_labels=get_bin_labels()):
i = 0
bins_holder = {}
for idx_bin in range(start, end):
if ((idx_bin % n_bins) == 0):
day = (int(id_date[(- 3):]) + 1)
zeros_before = ('0' * (3 - (len(str(day)) % 4)))
id_day = (zero... |
def query_yes_no(question, default='yes'):
valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
if (default is None):
prompt = ' [y/n] '
elif (default == 'yes'):
prompt = ' [Y/n] '
elif (default == 'no'):
prompt = ' [y/N] '
else:
raise ValueError(("in... |
def process_labels(labels: Optional[Dict[(str, Any)]]=None, onehot: bool=False) -> Tuple[(Optional[Union[(Dict[(str, Any)], pd.DataFrame)]], Optional[np.ndarray], Optional[np.ndarray], int)]:
if ((labels is not None) and (not isinstance(labels, (str, pd.DataFrame)))):
if onehot:
_all_labels_raw ... |
def dot_product_attention(tensor1, tensor2, with_bias=False):
dots = tf.matmul(tensor1, tensor2, transpose_b=True)
if with_bias:
bias = tf.get_variable('bias', shape=(), dtype=tf.float32)
dots += bias
return dots |
_materialize('core')
class Conv1d(UnaryOpBase):
in_dtypes = [(DType.float32,)]
out_dtypes = [(DType.float32,)]
def __init__(self, in_channels: Union[(int, z3.ExprRef)], out_channels: Union[(int, z3.ExprRef)], kernel_size: Union[(int, z3.ExprRef)], stride: Union[(int, z3.ExprRef)], padding: Union[(int, z3.Ex... |
def measure_semiorthogonality(model: nn.Module) -> Dict[(str, float)]:
with torch.no_grad():
scores = {}
for (name, m) in model.named_modules():
if hasattr(m, 'constrain_orthonormal'):
weight = m.state_dict()['conv.weight']
dim = weight.shape[0]
... |
def batch_norm_for_conv2d(inputs, is_training, bn_decay, scope, data_format, freeze_bn=False):
return batch_norm_template(inputs, is_training, scope, [0, 1, 2], bn_decay, data_format=data_format, freeze_bn=freeze_bn) |
def split_citations_iter(citation_elements):
current_citation = []
current_types = set()
last_type = None
num_auth = 0
postponed_auth = None
prev_split_reason = None
for el in citation_elements:
split_reason = split_needed(el, current_types, last_type)
if split_reason:
... |
def _read(path, encoding='utf-8', comment=';;;'):
if path:
if (isinstance(path, str) and os.path.exists(path)):
f = open(path, 'r', encoding='utf-8')
elif isinstance(path, str):
f = path.splitlines()
else:
f = path
for (i, line) in enumerate(f):
... |
def count(dic, fname):
with open(fname, 'r') as fd:
lines = fd.read().splitlines()
lines = ' '.join(lines)
words = lines.split(' ')
for w in words:
if (w in dic):
dic[w] += 1
else:
dic[w] = 1
return dic |
def test_osipkovmerritt_selfconsist_dehnencore_meanvr_directint():
pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
ras = [2.3, 5.7]
for (ra, dfh) in zip(ras[1:], osipkovmerritt_dfs_selfconsist[1:]):
tol = 1e-08
check_meanvr_directint(dfh, pot, tol, rmin=(pot._scale / 10.0), rma... |
def build_trainer(args, device_id, model, optim):
grad_accum_count = args.accum_count
n_gpu = args.world_size
if (device_id >= 0):
gpu_rank = int(args.gpu_ranks[device_id])
else:
gpu_rank = 0
n_gpu = 0
print(('gpu_rank %d' % gpu_rank))
tensorboard_log_dir = args.model_pat... |
class InfiniteGroupBatchSampler(Sampler):
def __init__(self, dataset, batch_size=1, world_size=None, rank=None, seed=0, shuffle=True):
(_rank, _world_size) = get_dist_info()
if (world_size is None):
world_size = _world_size
if (rank is None):
rank = _rank
self... |
('Please use `bigdl.orca.automl.hp` instead.')
class GridRandomRecipe(Recipe):
def __init__(self, num_rand_samples=1, look_back=2, epochs=5, training_iteration=10):
super(self.__class__, self).__init__()
self.num_samples = num_rand_samples
self.training_iteration = training_iteration
... |
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.resnet50 = resnet50.resnet50(pretrained=True, strides=(2, 2, 2, 1))
self.stage1 = nn.Sequential(self.resnet50.conv1, self.resnet50.bn1, self.resnet50.relu, self.resnet50.maxpool, self.resnet50.layer1)
self.sta... |
def pyconvresnet18(pretrained=False, **kwargs):
model = PyConvResNet(PyConvBasicBlock2, [2, 2, 2, 2], **kwargs)
if pretrained:
raise NotImplementedError('Not available the pretrained model yet!')
return model |
def _plot_poseaug(tmp_inputs_3d, tmp_inputs_2d, tmp_outputs_3d_ba, tmp_outputs_2d_ba, tmp_outputs_3d_bl, tmp_outputs_2d_bl, tmp_outputs_3d_rt, tmp_outputs_2d_rt, epoch, iter, args):
fig3d = plt.figure(figsize=(16, 8))
ax3din = fig3d.add_subplot(2, 4, 1, projection='3d')
ax3din.set_title('input 3D')
show... |
def optimizer_factory_two_groups(name: str, initial_lr1: float, initial_lr2: float, model1: Module, model2: Module, batch_size: Optional[int]=None, num_steps_per_epoch: Optional[int]=None, exclude_wd_norm: bool=False, exclude_wd_bias: bool=False, scaler: Optional[str]=None, params: DictConfig={}, scheduler: Optional[Di... |
def initNormal(mean, std, name, shape):
if name.endswith('_weight'):
return mx.nd.normal(mean, std, shape)
if name.endswith('_bias'):
return mx.nd.zeros(shape)
if name.endswith('_gamma'):
return mx.nd.ones(shape)
if name.endswith('_beta'):
return mx.nd.zeros(shape)
if... |
def wide_resnet50_2(pth_path, pretrained=False, **kwargs):
kwargs['width_per_group'] = (64 * 2)
return _resnet('wide_resnet50_2', Bottleneck, [3, 4, 6, 3], pretrained, pth_path, **kwargs) |
def inference_detector(model, img):
cfg = model.cfg
device = next(model.parameters()).device
test_pipeline = ([LoadImage()] + cfg.data.test.pipeline[1:])
test_pipeline = Compose(test_pipeline)
data = dict(img=img)
data = test_pipeline(data)
data = collate([data], samples_per_gpu=1)
if ne... |
class AverageEpochMeter(object):
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n=1):
self.sum += (val * n)
self.count += n
de... |
def katsura6():
pol1 = '1*x1+2*x2+2*x3+2*x4+2*x5+2*x6+2*x7-1;'
pol2 = '2*x4*x3+2*x5*x2+2*x6*x1+2*x7*x2-1*x6;'
pol3 = '1*x3^2+2*x4*x2+2*x5*x1+2*x6*x2+2*x7*x3-1*x5;'
pol4 = '2*x3*x2+2*x4*x1+2*x5*x2+2*x6*x3+2*x7*x4-1*x4;'
pol5 = '1*x2^2+2*x3*x1+2*x4*x2+2*x5*x3+2*x6*x4+2*x7*x5-1*x3;'
pol6 = '2*x2*x1... |
def _gen_spnasnet(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_c16_noskip'], ['ir_r3_k3_s2_e3_c24'], ['ir_r1_k5_s2_e6_c40', 'ir_r3_k3_s1_e3_c40'], ['ir_r1_k5_s2_e6_c80', 'ir_r3_k3_s1_e3_c80'], ['ir_r1_k5_s1_e6_c96', 'ir_r3_k5_s1_e3_c96'], ['ir_r4_k5_s2_e6_c192'], ['ir_r1_k... |
class RandomRotation():
def __init__(self, axis=None, max_theta=180, max_theta2=None):
self.axis = axis
self.max_theta = max_theta
self.max_theta2 = max_theta2
def _M(self, axis, theta):
return expm(np.cross(np.eye(3), ((axis / norm(axis)) * theta))).astype(np.float32)
def __... |
class DatasetGen(object):
def __init__(self, args):
super(DatasetGen, self).__init__()
self.seed = args.seed
self.sbatch = args.sbatch
self.pc_valid = args.pc_valid
self.root = args.data_dir
self.num_tasks = args.ntasks
self.num_classes = 100
self.inpu... |
class FeedfreeInput(InputData):
def get_input_tensors(self):
return self._get_input_tensors()
def _get_input_tensors(self): |
def read_src_and_trg_files(src_file, trg_file, is_train, remove_title_eos=True):
tokenized_train_src = []
tokenized_train_trg = []
filtered_cnt = 0
for (line_idx, (src_line, trg_line)) in enumerate(zip(open(src_file, 'r'), open(trg_file, 'r'))):
if ((len(src_line.strip()) == 0) and is_train):
... |
class PEARL(MetaRLAlgorithm):
def __init__(self, env, inner_policy, qf, vf, num_train_tasks, num_test_tasks, latent_dim, encoder_hidden_sizes, test_env_sampler, policy_class=ContextConditionedPolicy, encoder_class=MLPEncoder, policy_lr=0.0003, qf_lr=0.0003, vf_lr=0.0003, context_lr=0.0003, policy_mean_reg_coeff=0.0... |
class DummyCVDataset_dict(DummyCVDataset):
def __init__(self, shape):
super().__init__(shape)
self.process()
def process(self):
for idx in range(0, len(self.shape)):
tensor = np.random.uniform(low=self.low[idx], high=self.high[idx], size=self.shape[idx])
tensor = ... |
class RegNet(AnyNet):
def __init__(self, *, stem_class, stem_width, block_class, depth, w_a, w_0, w_m, group_width, stride=2, bottleneck_ratio=1.0, se_ratio=0.0, activation_class=None, freeze_at=0, norm='BN', out_features=None):
(ws, ds) = generate_regnet_parameters(w_a, w_0, w_m, depth)[0:2]
ss = [... |
class GptneoxState():
def __init__(self, eval_tokens: Deque[gptneox_cpp.gptneox_token], eval_logits: Deque[List[float]], gptneox_state, gptneox_state_size: int):
self.eval_tokens = eval_tokens
self.eval_logits = eval_logits
self.gptneox_state = gptneox_state
self.gptneox_state_size =... |
class Darknet(nn.Module):
def getLossLayers(self):
loss_layers = []
for m in self.models:
if (isinstance(m, RegionLayer) or isinstance(m, YoloLayer)):
loss_layers.append(m)
return loss_layers
def __init__(self, cfgfile, use_cuda=True):
super(Darknet, s... |
def generate_extra_cols(df):
origin = df.pop('Origin')
df['USA'] = ((origin == 1) * 1.0)
df['Europe'] = ((origin == 2) * 1.0)
df['Japan'] = ((origin == 3) * 1.0)
return df |
def train_on_batch(data, model, optimizer, criterion_traj, criterion_intend, params, print_result=False, epoch=0, iter=0):
optimizer.zero_grad()
(x, pred_traj, y_traj, pred_intent, y_intent, pred_start_pos) = get_prediction_on_batch(data, model, device)
loss_traj = criterion_traj(pred_traj, y_traj)
loss... |
class TerminateOnNaNCallback(Callback):
def __init__(self):
self.stop = False
def on_batch_end(self, last_loss, epoch, num_batch, **kwargs: Any) -> None:
if self.stop:
return True
if torch.isnan(last_loss):
print(f'Epoch/Batch ({epoch}/{num_batch}): Invalid loss, ... |
_sentencepiece
_tokenizers
class XLMRobertaTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = XLMRobertaTokenizer
rust_tokenizer_class = XLMRobertaTokenizerFast
test_rust_tokenizer = True
def setUp(self):
super().setUp()
tokenizer = XLMRobertaTokenizer(SAMPLE_VO... |
class BertJapaneseTokenizer(BertTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
pretrained_init_configuration = PRETRAINED_INIT_CONFIGURATION
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_low... |
def get_model(mode):
if (mode == 'flow'):
return Model_flow
else:
raise ValueError('Mode {} not found.'.format(mode)) |
class TinyImagenetFederatedTask(FederatedTask):
def __init__(self, params: Params):
super(TinyImagenetFederatedTask, self).__init__(params)
self.means = (0.485, 0.456, 0.406)
self.lvars = (0.229, 0.224, 0.225)
self.normalize = transforms.Normalize(self.means, self.lvars)
self... |
(for_each_device=True)
def cupy_launch(strFunction, strKernel):
return cupy.cuda.compile_with_cache(strKernel).get_function(strFunction) |
class ConvBlock(nn.Module):
def __init__(self, dimension, layer_num, in_channels, out_channels, kernel_size, stride=1, padding='SAME', dilation=1, bias=True, norm='batch', activation='relu', last_activation='relu', mode='conv'):
super(ConvBlock, self).__init__()
conv_block = []
if (dimension... |
def register_loader(loader_class):
name = loader_class.__name__.lower()[:(- len('Loader'))]
class _Wrapped(loader_class):
def __init__(self, shuffle_sequences: Optional[bool]=None, shuffle_sequence_items: Optional[bool]=None, shuffle: Optional[bool]=None, sequence_size: Optional[int]=None, image_size: i... |
def build_dataset(image_set, args):
assert (image_set in ['train', 'val', 'fewshot']), "image_set must be 'train', 'val' or 'fewshot'."
if (image_set == 'train'):
if (args.dataset_file == 'coco'):
root = Path('data/coco')
img_folder = (root / 'train2017')
ann_file = (... |
def _empty_box_results():
return OrderedDict({'box': OrderedDict([('AP', (- 1)), ('AP50', (- 1)), ('AP75', (- 1)), ('APs', (- 1)), ('APm', (- 1)), ('APl', (- 1)), ('CorLoc', (- 1))])}) |
def evaluate_metrics(prediction_file: Union[(str, Path, List[Dict[(str, str)]])], reference_file: Union[(str, Path, List[Dict[(str, str)]])], nb_reference_captions: int=5) -> Dict[(str, Dict[(str, Union[(float, Dict[(str, float)])])])]:
prediction_file = check_and_read_csv(prediction_file)
reference_file = chec... |
class Dataset_ETT_minute(Dataset):
def __init__(self, root_path, flag='train', size=None, features='S', data_path='ETTm1.csv', target='OT', scale=True, timeenc=0, freq='t'):
if (size == None):
self.seq_len = ((24 * 4) * 4)
self.label_len = (24 * 4)
self.pred_len = (24 * 4... |
class DictCIFAR100(DictDataset):
def __init__(self, root: str, train: bool=True, transform: Optional[Callable]=None, target_transform: Optional[Callable]=None, download: bool=False) -> None:
dataset = CIFAR100(root, train, transform, target_transform, download)
super().__init__(dataset) |
def trim_rule(qrule, dataset):
if (type(qrule) != QuantClassAssociationRule):
raise Exception('type of qrule must be QuantClassAssociationRule')
if (type(dataset) != pandas.DataFrame):
raise Exception('type of dataset must be: pandas.DataFrame')
(correctly_covered_by_r, _, _) = find_correctl... |
_model
def dla60_res2net(pretrained=False, **kwargs):
model_kwargs = dict(levels=(1, 1, 1, 2, 3, 1), channels=(16, 32, 128, 256, 512, 1024), block=DlaBottle2neck, cardinality=1, base_width=28, **kwargs)
return _create_dla('dla60_res2net', pretrained, **model_kwargs) |
class DefaultWorker(Worker):
def __init__(self, *, seed, max_path_length, worker_number):
super().__init__(seed=seed, max_path_length=max_path_length, worker_number=worker_number)
self.agent = None
self.env = None
self._observations = []
self._last_observations = []
s... |
class MultiProcessingHandler(logging.Handler):
def __init__(self, name, sub_handler=None):
super(MultiProcessingHandler, self).__init__()
if (sub_handler is None):
sub_handler = logging.StreamHandler()
self.sub_handler = sub_handler
self.setLevel(self.sub_handler.level)
... |
def _quantize_language_model(data_dir, arch, extra_flags=None, run_validation=False):
train_parser = options.get_training_parser()
train_args = options.parse_args_and_arch(train_parser, (['--task', 'language_modeling', data_dir, '--arch', arch, '--optimizer', 'adam', '--lr', '0.0001', '--criterion', 'adaptive_l... |
def _create_losses(input_queue, create_model_fn, train_config):
detection_model = create_model_fn()
(images, _, groundtruth_boxes_list, groundtruth_classes_list, groundtruth_masks_list, groundtruth_keypoints_list) = get_inputs(input_queue, detection_model.num_classes, train_config.merge_multiple_label_boxes)
... |
class DropoutContext(object):
def __init__(self):
self.dropout = 0
self.mask = None
self.scale = 1
self.reuse_mask = True |
def load(model_class, dir_path, opt, reset_params=False):
epoch_path = os.path.realpath(dir_path)
optimizer_path = os.path.join(epoch_path, 'optimizer.pth.tar')
logger.info(('Loading %s' % epoch_path))
gnn_config = json.load(open((epoch_path + '/gnn_config.json')))
model = model_class.from_pretraine... |
class AttentionBuilder(BaseAttentionBuilder):
def __init__(self):
super(AttentionBuilder, self).__init__(AttentionRegistry) |
def bitstr2float(bitstr):
byte_arr = bytearray((int(bitstr[i:(i + 8)], 2) for i in range(0, len(bitstr), 8)))
return struct.unpack('>f', byte_arr)[0] |
class RoIAlignFunction(Function):
def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0, aligned=True):
(out_h, out_w) = _pair(out_size)
assert (isinstance(out_h, int) and isinstance(out_w, int))
ctx.spatial_scale = spatial_scale
ctx.sample_num = sample_num
c... |
def _test_mean_and_cov(approx, var_param):
(mean, cov) = approx.mean_and_cov(var_param)
second_moments = (np.outer(mean, mean) + cov)
samples = approx.sample(var_param, MC_SAMPLES)
samples_outer = np.einsum('ij,ik->ijk', samples, samples)
mean_p_values = stats.ttest_1samp(samples, mean, axis=0)[1]
... |
def unpad_input(hidden_states, attention_mask):
seqlens_in_batch = attention_mask.sum(dim=(- 1), dtype=torch.int32)
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
max_seqlen_in_batch = seqlens_in_batch.max().item()
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dty... |
class DecodeLayer(nn.Module):
def __init__(self, vocabs, inference_layers, embed_dim, ff_embed_dim, num_heads, conc_size, rel_size, dropout):
super(DecodeLayer, self).__init__()
self.inference_layers = inference_layers
self.arc_generator = ArcGenerator(vocabs, embed_dim, ff_embed_dim, num_he... |
def main(argv=sys.argv):
if (len(argv) < 2):
sys.stderr.write(('Google Mock Class Generator v%s\n\n' % '.'.join(map(str, _VERSION))))
sys.stderr.write(__doc__)
return 1
global _INDENT
try:
_INDENT = int(os.environ['INDENT'])
except KeyError:
pass
except:
... |
class SingleDataset(BaseDataset):
def modify_commandline_options(parser, is_train):
parser = BaseDataset.modify_commandline_options(parser, is_train)
parser.add_argument('--meta_path', type=str, default=None, help='the path to the meta file')
return parser
def __init__(self, opt):
... |
def trace_torch(frame, event, arg):
if (event != 'line'):
return trace_torch
global prev_line
global prev_filename
func_filename = frame.f_code.co_filename
func_line_no = frame.f_lineno
if ('torch' not in func_filename):
return trace_torch
if (func_filename != prev_filename):... |
class ConvBnRelu(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size: int, stride: int=1, padding: int=0, dilation: int=1, groups: int=1, bias: bool=True, add_relu: bool=True, interpolate: bool=False):
super(ConvBnRelu, self).__init__()
self.conv = nn.Conv2d(in_channels=i... |
class NTXent(nn.Module):
def __init__(self, temperature=0.07):
super(NTXent, self).__init__()
self.loss = nn.LogSoftmax(dim=1)
self.tau = temperature
def forward(self, audio_embeds, text_embeds, labels):
n = audio_embeds.shape[0]
a2t = (util.cos_sim(audio_embeds, text_emb... |
class CachedProcessPoolExecutor():
def __init__(self):
self._pool = None
self._n_workers = (- 1)
def __call__(self, n_workers=None):
if (n_workers != self._n_workers):
from concurrent.futures import ProcessPoolExecutor
self.shutdown()
self._pool = Proc... |
class CiderMetric(Metric):
def __init__(self, n_gram=4, sigma=6.0, tokenize=True):
self.n_gram = n_gram
self.sigma = sigma
self.tokenize = tokenize
def evaluate_example(self, summary, reference):
if self.tokenize:
if isinstance(reference, str):
referen... |
def savgol_smooth(y, box_pts):
if ((box_pts % 2) == 0):
box_pts += 1
y_smooth = scipy.signal.savgol_filter(y, box_pts, 2)
return y_smooth |
def _load_dataset(frames_dataset_class, features_dataset_class, dataset_path: str, selected_video_names):
frames_dataset = frames_dataset_class(dataset_path)
video_names = _resolve_video_names(frames_dataset, selected_video_names)
raw_features_dataset = features_dataset_class(dataset_path, video_names)
... |
class TomWorld(CostarWorld):
def __init__(self, data_root='', fake=True, load_dataset=False, lfd=None, *args, **kwargs):
if (not fake):
raise NotImplementedError('Not quite set up yet')
else:
observe = None
super(TomWorld, self).__init__(None, *args, namespace='/tom',... |
class RandomWindowSoccerNetClipSampler(SoccerNetClipSampler):
def __init__(self, data_source: SoccerNet, windows_per_video: int=50, window_duration: float=32.0, sample_edges: bool=False, shuffle: bool=False) -> None:
super().__init__(data_source, shuffle=shuffle)
assert ((windows_per_video % 2) == 0... |
def h36m_numbers(coords3d_true, coords3d_pred, activity_name, procrustes=False, joint_validity_mask=None):
if (joint_validity_mask is None):
joint_validity_mask = np.full_like(coords3d_true[(..., 0)], fill_value=True, dtype=np.bool)
coords3d_true = tfu3d.root_relative(coords3d_true)
coords3d_pred = ... |
def clean(input_file, output_file):
lines = open(input_file, 'r').readlines()
writer = open(output_file, 'w')
for line in lines:
parts = line[:(- 1)].split(' ')
tag = parts[0].split(':')[0]
class_num = class_name_to_num[tag]
sentence = get_only_chars(' '.join(parts[1:]))
... |
def notears_standard(data, loss, loss_grad, c=0.25, r=10.0, e=1e-08, rnd_W_init=False, output_all_progress=False, verbose=False):
n = np.shape(data)[0]
d = np.shape(data)[1]
data = np.array(data).astype(dtype=np.float64)
cov = np.cov(data.T)
if rnd_W_init:
W = np.random.randn(d, d)
else:... |
class Experts(nn.Module):
def __init__(self, n_source, fdim, num_classes):
super().__init__()
self.linears = nn.ModuleList([nn.Linear(fdim, num_classes) for _ in range(n_source)])
self.softmax = nn.Softmax(dim=1)
def forward(self, i, x):
x = self.linears[i](x)
x = self.so... |
def get_root():
root = os.path.realpath(os.path.abspath(os.getcwd()))
setup_py = os.path.join(root, 'setup.py')
versioneer_py = os.path.join(root, 'versioneer.py')
if (not (os.path.exists(setup_py) or os.path.exists(versioneer_py))):
root = os.path.dirname(os.path.realpath(os.path.abspath(sys.ar... |
def gen_learner_wide(data: ImageDataBunch, gen_loss, arch=models.resnet101, nf_factor: int=2) -> Learner:
return unet_learner_wide(data, arch=arch, wd=0.001, blur=True, norm_type=NormType.Spectral, self_attention=True, y_range=((- 3.0), 3.0), loss_func=gen_loss, nf_factor=nf_factor) |
class _CounterfactualExpV2SchemaConstants():
TEST_DATA = 'test_data'
CFS_LIST = 'cfs_list'
LOCAL_IMPORTANCE = _CommonSchemaConstants.LOCAL_IMPORTANCE
SUMMARY_IMPORTANCE = _CommonSchemaConstants.SUMMARY_IMPORTANCE
METADATA = _CommonSchemaConstants.METADATA
MODEL_TYPE = 'model_type'
DATA_INTER... |
class Server():
def __init__(self, *args, **kwargs):
rospy.Subscriber('/map_collector/points', Float32MultiArray, callback=self.read_points)
plt.ion()
plt.show()
self.points = None
def read_points(self, msg):
points = list(msg.data)
numPoints = int((len(points) / ... |
def add_flops_counter_hook_function(module):
if isinstance(module, torch.nn.Conv2d):
if hasattr(module, '__flops_handle__'):
return
handle = module.register_forward_hook(conv_flops_counter_hook)
module.__flops_handle__ = handle
elif isinstance(module, torch.nn.Linear):
... |
class SPADEDistillerModules(BaseSPADEDistillerModules):
def __init__(self, opt):
super(SPADEDistillerModules, self).__init__(opt)
def profile(self, input_semantics, config=None):
raise NotImplementedError('The distiller is only for training!!!')
def calc_distill_loss(self, Tacts, Sacts):
... |
def _gen_mobilenet_v3(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
if ('small' in variant):
num_features = 1024
if ('minimal' in variant):
act_layer = resolve_act_layer(kwargs, 'relu')
arch_def = [['ds_r1_k3_s2_e1_c16'], ['ir_r1_k3_s2_e4.5_c24', 'ir_r1_k3_s1_... |
_loss
def quality_focal_loss_with_prob(pred, target, beta=2.0):
assert (len(target) == 2), 'target for QFL must be a tuple of two elements,\n including category label and quality label, respectively'
(label, score) = target
pred_sigmoid = pred
scale_factor = pred_sigmoid
zerolabel = scale_fac... |
def test_grasp_dataset():
dataset = '102'
batch_size = 10
num_batches_to_traverse = 10
grasp_dataset_object = GraspDataset(dataset=dataset)
(feature_op_dicts, features_complete_list, time_ordered_feature_name_dict, num_samples_in_dataset) = grasp_dataset_object.get_training_dictionaries(batch_size=b... |
def package_shortname(long_name, family):
if long_name.startswith('CABGA'):
if (family == 'MachXO'):
return ('B' + long_name[5:])
else:
return ('BG' + long_name[5:])
elif long_name.startswith('CSBGA'):
if (family == 'MachXO'):
return ('M' + long_name[5... |
def main(args):
(model, _, _) = load_model_and_preprocess('blip_diffusion', 'base', device='cpu', is_eval=True)
save_blip_diffusion_model(model.state_dict(), args) |
class DeprecatedMID():
InitMT = 2
InitMTResults = 3
ReqDataLength = 10
DataLength = 11
ReqGPSStatus = 166
GPSStatus = 167
SetSyncInSettings = 214
SetSyncOutSettings = 216
SetOutputSkipFactor = 212
SetObjectAlignment = 224
SetHeading = 130
SetLeverArmGPS = 104
SetMagne... |
_model
def regnetx_320(pretrained=False, **kwargs):
return _create_regnet('regnetx_320', pretrained, **kwargs) |
def run_pdfminer(pdf_path, output_xml_path):
subprocess.run(['pdf2txt.py', '-t', 'xml', pdf_path, '-o', output_xml_path]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.