code stringlengths 101 5.91M |
|---|
(name='x_boundary')
def boundary_domain():
points = geo.sample_boundary(100, param_ranges=time_range)
constraints = sc.Variables({'u': 0})
return (points, constraints) |
class RendezvousManager(metaclass=ABCMeta):
def __init__(self):
self._lock = Lock()
self._alive_nodes = set()
self._released_workers = []
self._waiting_nodes: Dict[(int, int)] = {}
self._rdzv_nodes = {}
self._lastcall_time = 0
self._rdzv_params = RendezvousPar... |
class BackgroundConsumer(Thread):
def __init__(self, queue, source, max_len):
Thread.__init__(self)
self._queue = queue
self._source = source
self._max_len = max_len
self.count = 0
def run(self):
try:
self._source_iter = iter(self._source)
... |
def iou_masks(mask1: Tensor, mask2: Tensor, n: int):
k = ((mask1 >= 0) & (mask1 < n))
inds = ((n * mask1[k].to(torch.int64)) + mask2[k])
mat = torch.bincount(inds, minlength=(n ** 2)).reshape(n, n)
iu = (torch.diag(mat) / (((mat.sum(1) + mat.sum(0)) - torch.diag(mat)) + 1e-06))
return iu.mean().item... |
def patch_norm_fp32(module):
if isinstance(module, (nn.modules.batchnorm._BatchNorm, nn.GroupNorm)):
module.float()
module.forward = patch_forward_method(module.forward, torch.half, torch.float)
for child in module.children():
patch_norm_fp32(child)
return module |
def collate(samples):
(graphs, labels, gt_adjs) = map(list, zip(*samples))
batched_graph = dgl.batch(graphs)
return (batched_graph, torch.cat(tuple(labels), 0), gt_adjs) |
class SplitBias(nn.Module):
def __init__(self, module):
super(SplitBias, self).__init__()
self.module = module
self.add_bias = AddBias(module.bias.data)
self.module.bias = None
def forward(self, input):
x = self.module(input)
x = self.add_bias(x)
return x |
def run_experiment(config):
exp_dir = ((((os.getcwd() + '/data/') + EXP_NAME) + '/') + config.get('exp_name', ''))
logger.configure(dir=exp_dir, format_strs=['stdout', 'log', 'csv'], snapshot_mode='last')
json.dump(config, open((exp_dir + '/params.json'), 'w'), indent=2, sort_keys=True, cls=ClassEncoder)
... |
_module()
class Collect3D(object):
def __init__(self, keys, meta_keys=('filename', 'ori_shape', 'img_shape', 'lidar2img', 'pad_shape', 'scale_factor', 'flip', 'cam_intrinsic', 'pcd_horizontal_flip', 'pcd_vertical_flip', 'box_mode_3d', 'box_type_3d', 'img_norm_cfg', 'rect', 'Trv2c', 'P2', 'pcd_trans', 'sample_idx', ... |
def main(args):
misc.init_distributed_mode(args)
print('job dir: {}'.format(os.path.dirname(os.path.realpath(__file__))))
print('{}'.format(args).replace(', ', ',\n'))
device = torch.device(args.device)
seed = (args.seed + misc.get_rank())
torch.manual_seed(seed)
np.random.seed(seed)
cud... |
def search_absorbe_bn(model, prev=None, remove_bn=True, verbose=False):
with torch.no_grad():
for m in model.children():
if (is_bn(m) and is_absorbing(prev)):
absorb_bn(prev, m, remove_bn=remove_bn, verbose=verbose)
search_absorbe_bn(m, remove_bn=remove_bn, verbose=ve... |
class DMCPInvertedResidual(USInvertedResidual):
def __init__(self, inplanes, outplanes, stride, t, expand):
super(DMCPInvertedResidual, self).__init__(inplanes, outplanes, stride, t, expand)
global Alpha
self.alpha1 = (Alpha((inplanes * t)) if (t != 1) else None)
self.alpha2 = (Alpha... |
def ProcessReplaceIndexDescriptor(segment, parent_node_name, affix, edge_attributes=None):
dot_graph = []
label = 'ReplaceIndex({0}, {1})'.format(segment['arguments'][1], segment['arguments'][2])
style = None
if (edge_attributes is not None):
if ('label' in edge_attributes):
label = ... |
def read_e2e_files(path, tokenizer, lowdata_token=None):
file_dict = {}
with open(path, 'r') as f:
for line in f:
(src, tgt) = line.strip().split('||')
if (lowdata_token is None):
src = ' {} {}'.format(src, tokenizer.bos_token)
else:
sr... |
def _replace_relu(module):
reassign = {}
for (name, mod) in module.named_children():
_replace_relu(mod)
if ((type(mod) == nn.ReLU) or (type(mod) == nn.ReLU6)):
reassign[name] = nn.ReLU(inplace=False)
for (key, value) in reassign.items():
module._modules[key] = value |
def test_neither_x0_nor_initial_solutions_provided(archive_fixture):
(archive, _) = archive_fixture
sigma_g = 0.05
with pytest.raises(ValueError):
GradientOperatorEmitter(archive, sigma=1.0, sigma_g=sigma_g) |
def evaluate(trainer, datamodule, cfg, stage, is_eval_train=False):
test_res = dict()
try:
trainer.lightning_module.stage = cfg.stage
eval_dataloader = datamodule.eval_dataloader(cfg.evaluation.is_eval_on_test)
ckpt_path = cfg.evaluation[stage].ckpt_path
if (isinstance(datamodule... |
class _LRSchedulerStep(object):
def __init__(self, optimizer, last_step=(- 1)):
if (not isinstance(optimizer, Optimizer)):
raise TypeError('{} is not an Optimizer'.format(type(optimizer).__name__))
self.optimizer = optimizer
if (last_step == (- 1)):
for group in optim... |
_checkable
class TransformerLike(EstimatorLikeFit1, Protocol):
def fit(self, X: List[str], y: Optional[str]=None, **fit_params: Any) -> None:
pass
def transform(self, X: DataLike) -> DataLike:
return X
def fit_transform(self, X: DataLike, y: Optional[DataLike]=None) -> DataLike:
retu... |
def keys_mapping_old_tea(checkpoint, k_new, replace_dict=[]):
k_old = checkpoint.keys()
for i in k_old:
if ('iSQRT' in i):
i_new = i.replace('iSQRT.', 'TCP.')
i_candidates = [i_new.replace('att_module.conv_1', 'TCP_att.TCA.g1'), i_new.replace('att_module.conv_2', 'TCP_att.TCA.g2'... |
def sklearn_logistic_regression(dataname, train_embeds, train_labels, valid_embeds, valid_labels, test_embeds, test_labels, max_iter=None, tol=0.001, alpha=0.0001):
if (not isinstance(train_embeds, np.ndarray)):
train_embeds = train_embeds.asnumpy()
if (not isinstance(valid_embeds, np.ndarray)):
... |
def create_model(existing='', is_twohundred=False, is_halffeatures=True):
if (len(existing) == 0):
print('Loading base model (DenseNet)..')
if is_twohundred:
base_model = applications.DenseNet201(input_shape=(None, None, 3), include_top=False)
else:
base_model = appli... |
def require_datasets(test_case):
if (not _datasets_available):
return unittest.skip('test requires `datasets`')(test_case)
else:
return test_case |
def compute_error_rate(hyp_wrd_path, ref_wrd_path, unit='word'):
tokenize_line = {'word': (lambda x: re.sub(' \\(.*\\)$', '', x.rstrip()).split()), 'char': (lambda x: list(re.sub(' \\(.*\\)$', '', x.rstrip())))}.get(unit)
if (tokenize_line is None):
raise ValueError(f'{unit} not supported')
inds = [... |
class FastFocalLoss(nn.Module):
def __init__(self):
super(FastFocalLoss, self).__init__()
def forward(self, out, target, ind, mask, cat):
mask = mask.float()
gt = torch.pow((1 - target), 4)
neg_loss = ((torch.log((1 - out)) * torch.pow(out, 2)) * gt)
neg_loss = neg_loss.s... |
def compute_integrated_gradients(inp, baseline, net, target, n_steps=100):
path = [(baseline + (a * (inp - baseline))) for a in np.linspace(0, 1, n_steps)]
grads = [compute_gradient(func, x, net=net, target=target) for x in path]
ig = ((inp - baseline) * torch.cat(grads[:(- 1)]).mean(dim=0, keepdims=True))
... |
class EnvironmentCommand(BaseDiffusersCLICommand):
def register_subcommand(parser: ArgumentParser):
download_parser = parser.add_parser('env')
download_parser.set_defaults(func=info_command_factory)
def run(self):
hub_version = huggingface_hub.__version__
pt_version = 'not instal... |
class JavaValue(object):
def jvm_class_constructor(self):
name = ('create' + self.__class__.__name__)
print(('creating: ' + name))
return name
def __init__(self, jvalue, bigdl_type, *args):
self.value = (jvalue if jvalue else callBigDlFunc(bigdl_type, self.jvm_class_constructor()... |
def WriteToFile(file_path, locations, scales, descriptors, attention, orientations=None):
serialized_data = SerializeToString(locations, scales, descriptors, attention, orientations)
with tf.gfile.FastGFile(file_path, 'w') as f:
f.write(serialized_data) |
def test_amateur_draft(bref_get_monkeypatch: Callable, sample_html: str, sample_processed_result: pd.DataFrame) -> None:
expected_url = _URL.format(year=2019, draft_round=1)
bref_get_monkeypatch(sample_html, expected_url)
result = amateur_draft(2019, 1)
assert (result is not None)
assert (not result... |
def _check_spark_version(sc, report_warn):
version_info = _get_bigdl_verion_conf()
(c_major, c_feature, c_maintenance) = _split_full_version(version_info['spark_version'])
(r_major, r_feature, r_maintenance) = _split_full_version(sc.version)
error_message = ('\n The compile time spark version is ... |
def expand_dim(x: ty.T, /, num: ty.U[(int, ty.S[int])], dim: ty.U[(int, ty.S[int])]=0, insert: bool=False) -> ty.T:
if isinstance(num, int):
if isinstance(dim, int):
(num, dim) = ([num], [dim])
else:
num = ([num] * len(dim))
elif (len(num) != len(dim)):
raise Valu... |
class PR(ExplainerMixin):
available_explanations = ['perf']
explainer_type = 'perf'
def __init__(self, model, feature_names=None, feature_types=None):
self.model = model
self.feature_names = feature_names
self.feature_types = feature_types
def explain_perf(self, X, y, name=None):... |
def nms(dets, thresh, force_cpu=False):
if (dets.shape[0] == 0):
return []
if force_cpu:
return cpu_nms(dets, thresh)
return gpu_nms(dets, thresh) |
class ProcessorMixin(PushToHubMixin):
attributes = ['feature_extractor', 'tokenizer']
feature_extractor_class = None
tokenizer_class = None
_auto_class = None
def __init__(self, *args, **kwargs):
for key in kwargs:
if (key not in self.attributes):
raise TypeError(... |
def normalize_angle_deg(angle):
import math
while (angle < 0):
angle += 360
angle = math.fmod(angle, 360.0)
return angle |
def generate(prompt, topic, affect, knob):
knob /= 100
print('Recieved request\n', 'Prompt: ', prompt, 'topic: ', topic, 'affect: ', affect, 'knob: ', knob)
if ((prompt == 'Enter prefix') or (prompt == '')):
return ('', False)
emit('word', {'value': 'Generating...'}, broadcast=True)
result =... |
class Speedometer(object):
def __init__(self, batch_size, frequent=50):
self.batch_size = batch_size
self.frequent = frequent
self.init = False
self.tic = 0
self.last_count = 0
def __call__(self, param):
count = param.nbatch
if (self.last_count > count):
... |
class ZDT1Modified(FloatProblem):
def __init__(self, number_of_variables: int=30):
super(ZDT1Modified, self).__init__()
self.number_of_variables = number_of_variables
self.number_of_objectives = 2
self.number_of_constraints = 0
self.obj_directions = [self.MINIMIZE, self.MINIM... |
class Angrop():
def __init__(self, binary, input, job, ropchain, bad_chars):
self.binary = binary
self.input = input
self.job = job
self.logger = job.logger
self.ropchain = ropchain
self.bad_chars = bad_chars
def run(self, timeout):
from os.path import abs... |
.dataclass
class FlaxImagePipelineOutput(BaseOutput):
images: Union[(List[PIL.Image.Image], np.ndarray)] |
class Entry(object):
def __init__(self, value, new_value_type):
self.value = value
self.new_value_type = new_value_type
def update(self, new_value):
if self.new_value_type:
assert isinstance(new_value, self.new_value_type), f'{new_value}, {self.new_value_type}'
self.v... |
def simxUnpackInts(intsPackedInString):
b = []
for i in range(int((len(intsPackedInString) / 4))):
b.append(struct.unpack('<i', intsPackedInString[(4 * i):(4 * (i + 1))])[0])
return b |
def make_output_directory(output_dir, model_name, multiple_model_mode):
if multiple_model_mode:
prediction_dir = os.path.join(output_dir, 'predictions', model_name)
else:
prediction_dir = os.path.join(output_dir, 'predictions')
os.makedirs(prediction_dir, exist_ok=True)
return prediction... |
def main():
args = parse_args()
handler = DistributedDataParallelKwargs(find_unused_parameters=True)
accelerator = Accelerator(kwargs_handlers=[handler])
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO)
logger.info(ac... |
def load_test_data(args, logger, processor, task_name, label_list, tokenizer, output_mode, k=None):
if (task_name == 'vua'):
eval_examples = processor.get_test_examples(args.data_dir)
elif (task_name == 'trofi'):
eval_examples = processor.get_test_examples(args.data_dir, k)
else:
rai... |
class Videodatasets_RGBD(Dataset):
def __init__(self, dataset_root, ground_truth1, typ1, ground_truth2, typ2, sample_duration=16, phase='train'):
def get_data_list_and_label(data_df, typ):
T = 0
return [(lambda arr: ('/'.join(arr[T].split('/')[1:]), int(arr[1]), int(arr[2])))(i[:(- 1... |
def WideResNet(nbfilters, nbblocks, dropout, weight_decay, nb_classes, batchnorm_training=True, use_bias=True):
if (K.image_data_format() == 'channels_last'):
input_model = Input(shape=(32, 32, 3))
channel_axis = (- 1)
elif (K.image_data_format() == 'channels_first'):
input_model = Input... |
class CTCTrainer(Trainer):
def training_step(self, model: nn.Module, inputs: Dict[(str, Union[(torch.Tensor, Any)])]) -> torch.Tensor:
model.train()
inputs = self._prepare_inputs(inputs)
if self.use_amp:
with autocast():
loss = self.compute_loss(model, inputs)
... |
('Correlation')
def _correlation_grad_cc(op, grad):
return correlation_grad_module.correlation_grad(grad, op.inputs[0], op.inputs[1], stride=op.get_attr('stride'), max_displacement=op.get_attr('max_displacement')) |
class PSPModule(nn.Module):
def __init__(self, features, out_features=1024, sizes=(1, 2, 4, 8)):
super().__init__()
self.stages = []
self.stages = nn.ModuleList([C(features, features, 3, 1, groups=features) for size in sizes])
self.project = CBR((features * (len(sizes) + 1)), out_fea... |
(name='left_boundary2')
class LeftBoundary2(sc.SampleDomain):
def sampling(self, *args, **kwargs):
return (Line.sample_boundary(100, sieve=sp.Eq(x, 0)), {'d_y': 0}) |
def _wrapper_count_operators(model: nn.Module, inputs: list, mode: str, **kwargs) -> typing.DefaultDict[(str, float)]:
supported_ops = {k: (lambda *args, **kwargs: {}) for k in _IGNORED_OPS}
supported_ops.update(kwargs.pop('supported_ops', {}))
kwargs['supported_ops'] = supported_ops
assert (len(inputs)... |
def gaussian_noise(tensor, mean=0, stddev=0.1):
noise = torch.nn.init.normal(torch.Tensor(tensor.size()), 0, 0.1)
return Variable((tensor + noise)) |
def add_preds(df_county, NUM_DAYS_LIST=[1, 2, 3], verbose=False, cached_dir=None, outcomes=['Deaths', 'Cases'], discard=False, d=datetime.datetime.today(), add_predict_interval=True, interval_target_days=[], expanded_shared_time_truncation=0.1, expanded_shared_max_days=365, force_predict=False):
print('adding preds... |
(inp1=arrays(shape=(3, 2, 10), dtype=np.float, elements=hypothesis.strategies.floats((- 100), 100)), inp2=arrays(shape=(3, 2, 10), dtype=np.float, elements=hypothesis.strategies.floats((- 100), 100)), intersection_temperature=floats(1e-05, 1.0), approximation_mode=sampled_from(['clipping', 'clipping_forward']), box_typ... |
def main():
global args, config, best_mota
args = parser.parse_args()
with open(args.config) as f:
config = yaml.load(f, Loader=yaml.FullLoader)
config = EasyDict(config['common'])
config.save_path = os.path.dirname(args.config)
model = build_model(config)
model.cuda()
optimizer ... |
def self_disc_net(args, data=None):
model = self_D_net(args)
model.D.load_state_dict(data)
return model |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--audio-dirs', nargs='+', default=['-'], required=True, help='input directories with audio files')
parser.add_argument('--labels', required=True, help='aggregated input labels with format <ID LABEL> per line', type=argparse.FileType('r', en... |
def test_kernel_tuning(random_data):
(X, Y) = random_data
param_grid = {'kernel': ['poly'], 'c': [[0.1], [0.1, 0.2]], 'degree': [[2], [2, 3]]}
kernel_reg = GridSearchCV(KCCA(latent_dimensions=1), param_grid=param_grid, cv=2, verbose=True).fit([X, Y])
assert hasattr(kernel_reg, 'best_estimator_') |
class Trainer(object):
def __init__(self, args):
self.args = args
filehandler = logging.FileHandler(args.logging_file)
streamhandler = logging.StreamHandler()
self.logger = logging.getLogger('')
self.logger.setLevel(logging.INFO)
self.logger.addHandler(filehandler)
... |
def test_categorical_from_structure(X):
structure = ((), (0,), (1, 3), ())
distributions = _from_structure(X, structure=structure)
model = BayesianNetwork(distributions, structure=structure)
assert isinstance(model.distributions[0], Categorical)
assert isinstance(model.distributions[1], ConditionalC... |
class FireReset(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
assert (env.unwrapped.get_action_meanings()[1] == 'FIRE'), 'Only use fire reset wrapper for suitable environment!'
assert (len(env.unwrapped.get_action_meanings()) >= 3), 'Only use fire reset wrapper for suitable en... |
def loss(logits, labels):
labels = tf.cast(labels, tf.int64)
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=labels, logits=logits, name='cross_entropy_per_example')
cross_entropy_mean = tf.reduce_mean(cross_entropy, name='cross_entropy')
tf.add_to_collection('losses', cross_entrop... |
def test():
print('Loading toy dataset from JSON...')
loader = DatasetLoader()
gtDataset = loader.read_json('data/toydata/gt.json')
print('>> {}'.format(gtDataset.phrases))
gtBoxList = gtDataset.boxes
print('Loading toy predictions from JSON...')
predDataset = loader.read_json('data/toydata/... |
def get_bboxes_scores(result):
bboxes = result['bbox'][0]
gt_bbox = result['gt_bbox'][0]
bbox_lengths = result['bbox'][1][0]
gt_lengths = result['gt_bbox'][1][0]
bbox_list = []
gt_box_list = []
for i in range(len(bbox_lengths)):
num = bbox_lengths[i]
for j in range(num):
... |
class ECAPA_TDNN(nn.Module):
def __init__(self, C):
super(ECAPA_TDNN, self).__init__()
self.torchfbank = torch.nn.Sequential(PreEmphasis(), torchaudio.transforms.MelSpectrogram(sample_rate=16000, n_fft=512, win_length=400, hop_length=160, f_min=20, f_max=7600, window_fn=torch.hamming_window, n_mels=... |
class GC_Block(nn.Module):
def __init__(self, in_features, p_dropout, output_nodes=48, bias=False):
super(GC_Block, self).__init__()
self.in_features = in_features
self.out_features = in_features
self.gc1 = GraphConvolution(in_features, in_features, output_nodes=output_nodes, bias=bi... |
def mahalanobis_metric(p, S, L, U, pos_U, neg_U, args, encoder=None):
if (encoder is not None):
p = encoder(p)
S = encoder(S)
neg_index = (L == 0).nonzero()
pos_index = (L == 1).nonzero()
neg_index = neg_index.expand(neg_index.size(0), S.data.size(1))
pos_index = pos_index.expand(pos... |
def batch_broadcast(tens_list: Sequence[Tensor], num_nonbatch: Sequence[int]):
assert (not isinstance(tens_list, Tensor))
assert (len(tens_list) == len(num_nonbatch))
assert all(((i >= 0) for i in num_nonbatch))
assert all(((t.ndim >= nnb) for (t, nnb) in zip(tens_list, num_nonbatch)))
if (len(tens_... |
def tensor2plotable(tensor) -> np.ndarray:
if isinstance(tensor, np.ndarray):
return tensor
elif isinstance(tensor, torch.Tensor):
return tensor.detach().cpu().numpy()
else:
raise TypeError(f'tensor should be an instance of Tensor, given {type(tensor)}') |
def train(model_path: str, train_dataset_path: str, pretrained_vectors: str='', lr: float=0.1, epochs: int=5) -> fasttext.FastText:
model = fasttext.train_supervised(input=train_dataset_path, pretrained_vectors=pretrained_vectors, dim=300, lr=lr, epoch=epochs, wordNgrams=3)
model.save_model(model_path)
retu... |
class TFEncoderLayer(BaseModule):
def __init__(self, d_model=512, d_inner=256, n_head=8, d_k=64, d_v=64, dropout=0.1, qkv_bias=False, act_cfg=dict(type='mmcv.GELU'), operation_order=None):
super().__init__()
self.attn = MultiHeadAttention(n_head, d_model, d_k, d_v, qkv_bias=qkv_bias, dropout=dropout... |
class XLNetLMHeadModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def save_progress(text_encoder, placeholder_token_id, accelerator, config, save_path):
learned_embeds = accelerator.unwrap_model(text_encoder).get_input_embeddings().weight[placeholder_token_id]
learned_embeds_dict = {config.placeholder_token: learned_embeds.detach().cpu()}
torch.save(learned_embeds_dict, s... |
def rsinc1_dt_csc(t):
e = 0.01
r = torch.zeros_like(t)
a = torch.abs(t)
s = (a < e)
c = (s == 0)
t2 = (t[s] ** 2)
r[s] = ((t2 * ((t2 * (((4 * t2) / 675) + (2 / 63))) + (2 / 15))) + (1 / 3))
r[c] = (((1 / sin(t[c])) - ((t[c] * cos(t[c])) / (sin(t[c]) * sin(t[c])))) / sin(t[c]))
return... |
def test_run_exception_in_completed_event_is_caught(run):
observer = run.observers[0]
observer2 = mock.Mock(priority=20)
run.observers.append(observer2)
observer.completed_event.side_effect = TypeError
run()
assert observer.completed_event.called
assert observer2.completed_event.called |
_task('audio_pretraining', dataclass=AudioPretrainingConfig)
class AudioPretrainingTask(FairseqTask):
cfg: AudioPretrainingConfig
def setup_task(cls, cfg: AudioPretrainingConfig, **kwargs):
return cls(cfg)
def load_dataset(self, split: str, task_cfg: FairseqDataclass=None, **kwargs):
data_pa... |
def make_multiple_dataset_real(dir, max_dataset_size=float('inf')):
subdir = ['faces/celebahq/real-tfr-1024-resized128', 'faces/celebahq/real-tfr-1024-resized128', 'faces/celebahq/real-tfr-1024-resized128', 'faceforensics_aligned/Deepfakes/original', 'faceforensics_aligned/Face2Face/original', 'faceforensics_aligne... |
def save_image_array_as_png(image, output_path):
image_pil = Image.fromarray(np.uint8(image)).convert('RGB')
with tf.gfile.Open(output_path, 'w') as fid:
image_pil.save(fid, 'PNG') |
def test_baseline_realnvp_config():
config = get_config(dataset='mnist', model='realnvp', use_baseline=True)
true_config = {'schema_type': 'multiscale-realnvp', 'use_cond_affine': False, 'pure_cond_affine': False, 'g_hidden_channels': [64, 64, 64, 64, 64, 64, 64, 64], 'num_u_channels': 0, 'early_stopping': True... |
class ConvertBCHWtoCBHW(nn.Module):
def forward(self, vid: torch.Tensor) -> torch.Tensor:
return vid.permute(1, 0, 2, 3) |
def batch_mae_frame_float(gen_frames, gt_frames):
if (gen_frames.ndim == 3):
axis = (1, 2)
elif (gen_frames.ndim == 4):
axis = (1, 2, 3)
x = np.float32(gen_frames)
y = np.float32(gt_frames)
mae = np.sum(np.absolute((x - y)), axis=axis, dtype=np.float32)
return np.mean(mae) |
def sensor_callback(sensor_data, sensor_queue, sensor_name):
sensor_queue.put((sensor_data.frame, sensor_name)) |
class Search():
def __init__(self, forward_predictor: ForwardPredictor, forward_enumerator: ForwardEnumerator, value_heuristic: ValueHeuristic, action_enumerator: ActionEnumerator, random_state_enumerator: RandomStateEnumerator, random_state_predictor: RandomStatePredictor, opponent_action_enumerator: OpponentActio... |
def _assess_dimension_(spectrum, unscaled_vhat, rank, n_samples, n_features, alpha=1, beta=1):
if (rank > len(spectrum)):
raise ValueError('The tested rank cannot exceed the rank of the dataset')
pu = ((- rank) * np.log(2.0))
for i in range(rank):
pu += (gammaln(((n_features - i) / 2.0)) - (... |
def false_negative_rate(test=None, reference=None, confusion_matrix=None, nan_for_nonexisting=True, **kwargs):
return (1 - sensitivity(test, reference, confusion_matrix, nan_for_nonexisting)) |
class Dense(Model):
def initialize(self, outsize, usebias=True, batch_norm=False, activation=(- 1)):
self.fclayer = L.fcLayer(outsize, usebias=usebias)
self.batch_norm = batch_norm
self.activation_ = activation
if batch_norm:
self.bn = L.batch_norm()
if (activatio... |
def wrap(text, cols):
lines = []
while (len(text) > cols):
end = text.rfind(' ', 0, (cols + 1))
if (end == (- 1)):
end = cols
(line, text) = (text[:end], text[end:])
lines.append(line)
return lines |
def test_watershed_nodams():
nodam_watershed_result = np.array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4])
nodam_watershed = morpho.watershed(landscape, dams=False)
assert_array_equal(nodam_watershed, nodam_watershed_result) |
class SimulatedAnnealing(Algorithm[(S, R)], threading.Thread):
def __init__(self, problem: Problem[S], mutation: Mutation, termination_criterion: TerminationCriterion, solution_generator: Generator=store.default_generator):
super(SimulatedAnnealing, self).__init__()
self.problem = problem
se... |
def main():
parser = ArgumentParser(usage='python parse_trace_json.py trace_1.json')
parser.add_argument('json_files', nargs='*')
parser.add_argument('--verbose', '-v', action='store_true')
args = parser.parse_args()
kernel_start_times = []
for json_file in args.json_files:
with open(jso... |
def simxRemoveUI(clientID, uiHandle, operationMode):
return c_RemoveUI(clientID, uiHandle, operationMode) |
def load_result(path):
fullpath = os.path.join(path, 'rollout.json')
if (not os.path.exists(fullpath)):
return None
results = json.load(open(fullpath, 'rb'))
score = (results['score'] * 100)
return score |
def save_model(args, model, is_best):
print('Saving model...')
model_name = 'match_{}_cycle_{}_trans_{}_coseg_{}_task_{}.pth.tar'.format(args.w_match, args.w_cycle, args.w_trans, args.w_coseg, args.w_task)
model_path = os.path.join(args.result_model_dir, model_name)
torch.save(model.state_dict(), model_... |
class BackendTestCase(QiskitTestCase):
backend_cls = None
circuit = ReferenceCircuits.bell()
def setUp(self):
super().setUp()
self.backend = self._get_backend()
def setUpClass(cls):
if (cls is BackendTestCase):
raise SkipTest('Skipping base class tests')
super... |
class DemoFeatures(AbstractFeatures):
def __init__(self, kdl_kin, config):
self.config = config
self.kdl_kin = kdl_kin
self.features = RobotFeatures(self.config, self.kdl_kin)
def compute(self, world, state):
if (state.reference is not None):
ee = pm.fromMatrix(self.k... |
class LayerNormalization(Layer):
def __init__(self, hidden_size, bigdl_type='float'):
super(LayerNormalization, self).__init__(None, bigdl_type, hidden_size) |
class GPT2LMHeadModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def get_acc_from_qid_dicts(qid2preds, qid2targets):
qids = qid2preds.keys()
preds = np.asarray([int(qid2preds[ele]) for ele in qids])
targets = np.asarray([int(qid2targets[ele]) for ele in qids])
acc = (sum((preds == targets)) / float(len(preds)))
return acc |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.