code stringlengths 101 5.91M |
|---|
def test_random_multi_image():
shap.image_plot([np.random.randn(3, 20, 20) for i in range(3)], np.random.randn(3, 20, 20), show=False) |
def set_cycles(args):
scene = bpy.context.scene
scene.render.engine = 'CYCLES'
cycles = scene.cycles
cycles.use_progressive_refine = True
cycles.samples = args.n_samples
cycles.max_bounces = 8
cycles.caustics_reflective = True
cycles.caustics_refractive = False
cycles.diffuse_bounces... |
class NetworkImageNet(nn.Module):
def __init__(self, C, N, auxiliary, genotype, num_classes):
super(NetworkImageNet, self).__init__()
self._C = C
self._layerN = N
layer_channels = ((((([C] * N) + [(C * 2)]) + ([(C * 2)] * N)) + [(C * 4)]) + ([(C * 4)] * N))
layer_reductions =... |
def create_argparser():
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--project_name', type=str, default='sub-encoder', help='Name of a wandb project, checkpoints are saved under this directory')
parser.add_argument('--experiment_id', type=str,... |
def log_config_to_file(cfg, pre='cfg', logger=None):
for (key, val) in cfg.items():
if isinstance(cfg[key], EasyDict):
print_log(f'{pre}.{key} = edict()', logger=logger)
log_config_to_file(cfg[key], pre=((pre + '.') + key), logger=logger)
continue
print_log(f'{pre... |
def to_torch_imgs(img: np.ndarray, mean: Tensor, std: Tensor) -> Tensor:
t_img: Tensor = torch.from_numpy(np.transpose(img, (2, 0, 1)))
t_img -= mean
t_img /= std
return t_img |
class OuterProductOperation(pm.SingleStateTransformation):
map_entry = pm.PatternNode(nodes.MapEntry)
def expressions(cls):
return [sdutil.node_path_graph(cls.map_entry)]
def can_be_applied(self, graph: dace.SDFGState, expr_index: int, sdfg: dace.SDFG, permissive: bool=False):
map_entry = se... |
def extmodtest(A: dace.float32[(W, H)], result: dace.float32[1]):
tmp = np.ndarray([H, W], dace.float32)
external_module.transpose(A, tmp)
with dace.tasklet:
(a << tmp[(1, 2)])
(b >> result[0])
b = a |
def compute_model(E, name):
if (not isinstance(E, ell_generic.EllipticCurve_generic)):
raise TypeError('not an elliptic curve')
if (name == 'minimal'):
from sage.rings.number_field.number_field_base import NumberField
if (not isinstance(E.base_field(), NumberField)):
raise Va... |
def register_Ns3YansWifiPhy_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('SetChannel', 'void', [param('ns3::Ptr< ns3::YansWifiChannel > const', 'channel')])
cls.add_method('StartTx', 'void', [param('ns3::Ptr< ns3::Packet... |
def main(args):
set_random_seed(args.seed)
env_config = parse_config_file(args.env_config_file)
environment = GymEnvironment(env_config['name'], ctrl_cost_weight=env_config['action_cost'], seed=args.seed)
reward_model = environment.env.reward_model()
if (args.exploration == 'optimistic'):
dy... |
class CosPlace(nn.Module):
def __init__(self, in_dim, out_dim):
super().__init__()
self.gem = GeM()
self.fc = nn.Linear(in_dim, out_dim)
def forward(self, x):
x = F.normalize(x, p=2, dim=1)
x = self.gem(x)
x = x.flatten(1)
x = self.fc(x)
x = F.norm... |
class SimpleTrainer(TrainerBase):
def __init__(self, model, data_loader, optimizer):
super().__init__()
model.train()
self.model = model
self.data_loader = data_loader
self._data_loader_iter = iter(data_loader)
self.optimizer = optimizer
def run_step(self):
... |
class TemplatePlaceholderType(CType):
def __init__(self, name, optional=False):
self.name = name
self.optional = optional
def declaration_code(self, entity_code, for_display=0, dll_linkage=None, pyrex=0):
if entity_code:
return ((self.name + ' ') + entity_code)
else:
... |
def cross_attn_mask_generation(from_mask, to_mask, mutual=True, head_num=None, name=None):
with tf.name_scope((name or 'attention_mask_generation')):
(bs, slf) = get_shape_list(from_mask, 2)[:2]
slt = get_shape_list(to_mask, 2)[1]
if mutual:
res_mask = tf.cast((tf.expand_dims(tf.... |
def get_data_collator(tokenizer, return_tensors='pt', do_padding=False, max_length=1024):
def data_collator(features):
if (not do_padding):
try:
batch = {k: torch.tensor([f[k] for f in features]) for k in features[0].keys()}
except Exception:
batch = t... |
def make_objective(eps: goos.Shape, stage: str, params: Options):
solver = 'local_direct'
sim_left_x = (- params.wg_len)
sim_right_x = (params.coupler_len + params.buffer_len)
pml_thick = (params.dx * 10)
sim_z_center = ((((params.wg_thickness / 2) + params.beam_dist) - params.box_size) / 2)
sim... |
class IndexedArray(IndexedMeta[Content], Content):
def __init__(self, index, content, *, parameters=None):
if (not (isinstance(index, Index) and (index.dtype in (np.dtype(np.int32), np.dtype(np.uint32), np.dtype(np.int64))))):
raise TypeError("{} 'index' must be an Index with dtype in (int32, ui... |
class TextureLoss(tnn.Module):
def __init__(self, pos_weight=10):
super(TextureLoss, self).__init__()
self.loss = tnn.CrossEntropyLoss(weight=torch.Tensor([1, pos_weight]), ignore_index=2, reduction='none')
def forward(self, preds, targs):
loss = self.loss(preds, targs)
loss = to... |
def test_demo_start_subprocess_patched():
from returnn.util.basic import get_patch_atfork_lib
from subprocess import check_call
env = os.environ.copy()
env['LD_PRELOAD'] = get_patch_atfork_lib()
print('LD_PRELOAD:', get_patch_atfork_lib())
check_call([sys.executable, __file__, 'patched_check_dem... |
class FunctionFieldCompletion(Map):
def __init__(self, field, place, name=None, prec=None, gen_name=None):
if (name is None):
name = 's'
if (gen_name is None):
gen_name = 'a'
(k, from_k, to_k) = place.residue_field(name=gen_name)
self._place = place
se... |
def compute_huber_loss(y: torch.Tensor, target: torch.Tensor, beta: float=1.0) -> torch.Tensor:
diff = (target - y)
cond = (diff.detach().abs() < beta)
return torch.where(cond, (0.5 * (diff ** 2)), (beta * (diff.abs() - (0.5 * beta)))) |
class CLIPTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
def __init__(self, vocab_file, merges_file, error... |
class BasicBlockIR(nn.Module):
def __init__(self, c1, c2, s) -> None:
super().__init__()
if (c1 == c2):
self.shortcut_layer = nn.MaxPool2d(1, s)
else:
self.shortcut_layer = nn.Sequential(nn.Conv2d(c1, c2, 1, s, bias=False), nn.BatchNorm2d(c2))
self.res_layer =... |
def main():
args = parse_args()
os.makedirs(args.out_dir, exist_ok=True)
global_setup(args)
if args.pool:
_main_parallel(args)
else:
_main_sequential(args)
print('finished rendering') |
def setEduCovered(n, eduIds, eduCovered):
if (n._id in eduIds):
eduCovered.append(n)
for m in n.nodelist:
setEduCovered(m, eduIds, eduCovered) |
.parametrize('observation_size', [4])
.parametrize('action_size', [2])
def test_transition(observation_size: int, action_size: int) -> None:
transition = Transition(observation=np.random.random(observation_size).astype(np.float32), action=np.random.random(action_size).astype(np.float32), reward=np.random.random(1).... |
class TernaryEnsemble(Ensemble):
def __init__(self, M, N, p_pos=0.33, p_neg=0.33):
self.M = M
self.N = N
self.p_pos = p_pos
self.p_neg = p_neg
self.repr_init()
self.p_zero = (1 - (self.p_pos + self.p_neg))
def generate(self):
p = [self.p_neg, self.p_zero, ... |
class ProductProjectiveSpaces_finite_field(ProductProjectiveSpaces_field):
def _point(self, *args, **kwds):
return ProductProjectiveSpaces_point_finite_field(*args, **kwds)
def __iter__(self):
iters = [iter(T) for T in self._components]
L = []
for x in iters:
L.append... |
def add_present_time_to_history(current_time: List[Dict[(str, Any)]], history: History) -> History:
for annotation in current_time:
token = annotation['instance_token']
if (token in history):
history[token].append(annotation)
else:
history[token] = [annotation]
re... |
def set_pox_opts(components, info_level, logfile_opts, log_format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'):
info_level = info_level.upper()
pox_opts = ('%s log.level --%s log --file=%s --format="%s" &' % (components, info_level, logfile_opts, log_format))
return pox_opts |
def finetune_net_one_epoch(run_manager, args, epoch, warmup_epochs=0, warmup_lr=0, subnet_settings=None):
dynamic_net = run_manager.net
dynamic_net.train()
run_manager.run_config.train_loader.sampler.set_epoch(epoch)
MyRandomResizedCrop.EPOCH = epoch
nBatch = len(run_manager.run_config.train_loader)... |
_module()
class STDCHead(FCNHead):
def __init__(self, boundary_threshold=0.1, **kwargs):
super(STDCHead, self).__init__(**kwargs)
self.boundary_threshold = boundary_threshold
self.register_buffer('laplacian_kernel', torch.tensor([(- 1), (- 1), (- 1), (- 1), 8, (- 1), (- 1), (- 1), (- 1)], dt... |
def get_state_embedding_network_args(env, embedding_dim):
network_args = dict(name='state_embedding_network', input_shape=env.observation_space.shape, output_dim=embedding_dim, conv_filters=(16, 32), conv_filter_sizes=(8, 4), conv_strides=(4, 2), conv_pads=('VALID', 'VALID'), hidden_sizes=(256,), hidden_nonlinearit... |
def accuracy(logit, y):
pred = tf.argmax(logit, 1)
true = tf.argmax(y, 1)
return tf.reduce_mean(tf.to_float(tf.equal(pred, true))) |
class Device(object):
def __init__(self, name, protocol, state, disk={}, memory={}):
self._validate_inputs(name, protocol, state, disk, memory)
self.name = name
self.state = state
self.protocol = protocol
self.memory = memory
self.disk = disk
self._init_state(... |
def update_learning_rate_att(optimizer, cur_lr, new_lr):
if (cur_lr != new_lr):
ratio = _get_lr_change_ratio(cur_lr, new_lr)
if (ratio > cfg.SOLVER.LOG_LR_CHANGE_THRESHOLD):
logger.info('Changing learning rate %.6f -> %.6f', cur_lr, new_lr)
param_keys = []
for (ind, param... |
def convert(data, quantity, per):
if ((per == 'atom') or (per is None)):
return quantity
if (per in ['structure', 'cell', 'struc', 'molecule', 'mol']):
return (quantity * data.aux['n_atoms'])
if (per in ['cat', 'sub', 'non_O', 'cation']):
return ((quantity * data.aux['n_atoms']) / da... |
_to_string
class Undefined(object):
__slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name', '_undefined_exception')
def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):
self._undefined_hint = hint
self._undefined_obj = obj
self._undefined_name = name
... |
class StateD(nn.Module):
def __init__(self, opt):
super(StateD, self).__init__()
self.opt = opt
self.state_dim = opt.state_dim
self.state_fc = nn.Sequential(nn.Linear(self.state_dim, 32), nn.ReLU(), nn.Linear(32, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32), nn.R... |
def group_connectivity(timeseries, subject_list, atlas_name, kind, save=True, save_path=root_folder):
if (kind == 'lasso'):
covariance_estimator = GraphLassoCV(verbose=1)
connectivity_matrices = []
for (i, ts) in enumerate(timeseries):
covariance_estimator.fit(ts)
con... |
_converter_regitstry('sAR')
def sAR_t_converter(reg: sAR_reg):
(n, c, h, w) = (reg[f'res0_{d}'] for d in 'nchw')
opd0 = dict(address=reg.opd0_addr, dtype=(reg.opd0_prec, reg.opd0_sign), shape=(n, c, h, w), stride=tuple((reg[f'opd0_{d}_str'] for d in 'nchw')), layout=reg.opd0_str, is_const=reg.opd0_const)
re... |
def index_(tokenized_sentences, vocab_size):
freqflag = 0
freq_dist = nltk.FreqDist(itertools.chain(*tokenized_sentences))
vocabflag = freqflag
vocab = freq_dist.most_common(vocab_size)
vocabflag = vocab_size
index2word = ((['_'] + [UNK]) + [x[0] for x in vocab])
vocabflag += 1
word2inde... |
class TaskType(str, enum.Enum):
SEQ_CLS = 'SEQ_CLS'
SEQ_2_SEQ_LM = 'SEQ_2_SEQ_LM'
CAUSAL_LM = 'CAUSAL_LM'
TOKEN_CLS = 'TOKEN_CLS'
QUESTION_ANS = 'QUESTION_ANS' |
def test_parameters():
array = ak.with_parameter([1, 2, 3], 'name', 'Bob Dylan')
assert (not ak.almost_equal(array, [1, 2, 3]))
assert ak.almost_equal(array, [1, 2, 3], check_parameters=False)
array_other = ak.with_parameter(array, 'name', 'Emmy Noether')
assert (not ak.almost_equal(array, array_oth... |
class OpioidOverdoseLabeler(TimeHorizonEventLabeler):
def __init__(self, ontology: extension_datasets.Ontology, time_horizon: TimeHorizon):
self.time_horizon: TimeHorizon = time_horizon
icd9_codes: List[str] = ['E850.0', 'E850.1', 'E850.2', '965.00', '965.01', '965.02', '965.09']
icd10_codes... |
def freeze_pos_embeddings(student, args):
if (args.student_type == 'roberta'):
student.roberta.embeddings.position_embeddings.weight.requires_grad = False
elif (args.student_type == 'gpt2'):
student.transformer.wpe.weight.requires_grad = False |
def array2hexstring(array, dtype, pad_to_nbits, prefix='0x', reverse=False):
if (pad_to_nbits < 4):
pad_to_nbits = 4
if ((type(array) != np.ndarray) or (array.dtype != np.float32)):
array = np.asarray(array, dtype=np.float32)
assert (array.ndim == 1), 'The given array is not one-dimensional.... |
class SwinConfig(PretrainedConfig):
model_type = 'swin'
def __init__(self, image_size=224, patch_size=4, num_channels=3, embed_dim=96, depths=[2, 2, 6, 2], num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4.0, qkv_bias=True, hidden_dropout_prob=0.0, attention_probs_dropout_prob=0.0, drop_path_rate=0.1, hidden... |
def program_to_strs(program, mode):
if (mode == 'chain'):
if (not programs.is_chain(program)):
return None
elif (mode == 'prefix'):
program = programs.list_to_prefix(program)
elif (mode == 'postfix'):
program = programs.list_to_postfix(program)
for f in program:
... |
def build_dataset(dataset_list, is_train=True, local_rank=0):
if (not isinstance(dataset_list, (list, tuple))):
raise RuntimeError('dataset_list should be a list of strings, got {}'.format(dataset_list))
for dataset_name in dataset_list:
assert contains(dataset_name), 'Unknown dataset name: {}'.... |
def advance_past_constituents(gold_sequence, cur_index):
count = 0
while (cur_index < len(gold_sequence)):
if isinstance(gold_sequence[cur_index], OpenConstituent):
count = (count + 1)
elif isinstance(gold_sequence[cur_index], CloseConstituent):
count = (count - 1)
... |
def test_option_option_axis1():
a1 = ak.from_json('[[0.0, 1.1], null, [2.2, 3.3]]')
a2 = ak.from_json('[[4.4, 5.5, 6.6], null, [7.7, 8.8, 9.9]]')
a1 = ak.to_regular(a1, axis=1)
a2 = ak.to_regular(a2, axis=1)
c = ak.concatenate([a1, a2], axis=1)
assert (c.to_list() == [[0.0, 1.1, 4.4, 5.5, 6.6], ... |
class TestCohereWindowService():
def setup_class(cls):
cls.path: str = tempfile.mkdtemp()
cache_path: str = os.path.join(cls.path, 'cache')
ensure_directory_exists(cache_path)
with SqliteDict(os.path.join(cache_path, 'cohere.sqlite')) as cache:
for (request, response) in ... |
class CategoricalBoW(dist.Multinomial):
def log_prob(self, value):
if self._validate_args:
self._validate_sample(value)
(logits, value) = dist.util.broadcast_all(self.logits, value)
logits = logits.clone(memory_format=torch.contiguous_format)
logits[((value == 0) & (logit... |
def When(p, t, ctx=None):
p = _to_probe(p, ctx)
t = _to_tactic(t, ctx)
return Tactic(Z3_tactic_when(t.ctx.ref(), p.probe, t.tactic), t.ctx) |
def plot_model(model, to_file='model.png', show_shapes=False, show_layer_names=True, rankdir='TB'):
dot = model_to_dot(model, show_shapes, show_layer_names, rankdir)
(_, extension) = os.path.splitext(to_file)
if (not extension):
extension = 'png'
else:
extension = extension[1:]
dot.w... |
('The requests and results cannot be unpicked after the modules moved')
class TestAI21WindowService():
def setup_method(self):
auth = Authentication(api_key='DUMMY_API_KEY')
service = TokenizerService(RemoteService('DUMMY_URL'), auth)
self.window_service = WindowServiceFactory.get_window_ser... |
.parametrize('statement_type,value,new_value', [(stmt.IntPrimitiveStatement, 42, 23), (stmt.FloatPrimitiveStatement, 2.1, 1.2), (stmt.StringPrimitiveStatement, 'foo', 'bar'), (stmt.BytesPrimitiveStatement, b'foo', b'bar'), (stmt.BooleanPrimitiveStatement, True, False), (stmt.ComplexPrimitiveStatement, (4 + 1j), (1 + 4j... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input_dir', default='./input')
parser.add_argument('--ckpt', required=True)
parser.add_argument('--mode', default='val', choices=['val', 'vis', 'test'])
args = parser.parse_args()
device = ('cuda' if torch.cuda.is_available() ... |
def test_MemoryArray_init():
tl = Timeline()
ma = MemoryArray('ma', tl, num_memories=10)
assert (len(ma.memories) == 10)
for m in ma.memories:
assert (type(m) == Memory) |
def load_and_cache_examples(args, task, tokenizer, evaluate=False):
if ((args.local_rank not in [(- 1), 0]) and (not evaluate)):
torch.distributed.barrier()
processor = processors[task]()
output_mode = output_modes[task]
cached_features_file = os.path.join(args.data_dir, 'cached_{}_{}_{}_{}'.for... |
def inference(image, background_enhance, face_upsample, upscale, codeformer_fidelity):
try:
has_aligned = False
only_center_face = False
draw_box = False
detection_model = 'retinaface_resnet50'
print('Inp:', image, background_enhance, face_upsample, upscale, codeformer_fideli... |
_utils.test(arch=archs_support_ndarray_ad, default_fp=ti.f64)
def test_ad_sum_local_atomic():
N = 10
a = ti.ndarray(ti.f32, shape=N, needs_grad=True)
b = ti.ndarray(ti.i32, shape=N)
p = ti.ndarray(ti.f32, shape=N, needs_grad=True)
def compute_sum(a: ti.types.ndarray(), b: ti.types.ndarray(), p: ti.t... |
def _load_shared_obj(name):
paths = []
try:
paths += [ctu.find_library(name)]
except FileNotFoundError:
pass
try:
paths += [ctu.find_library(('lib' + name))]
except FileNotFoundError:
pass
dll = (ct.windll if (platform.system() == 'Windows') else ct.cdll)
for ... |
class EmitGemmGroupedInstance():
def __init__(self, operation_suffix=''):
self.operation_suffix = operation_suffix
self.includes = ['cutlass/cutlass.h', 'cutlass/numeric_types.h', 'cutlass/arch/arch.h', 'cutlass/arch/mma.h', 'cutlass/layout/matrix.h', 'cutlass/gemm/kernel/gemm_grouped.h', 'cutlass/g... |
class DistilBertTokenizerFast(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 |
def main():
parser = argparse.ArgumentParser(description='Export Matcha-TTS to ONNX')
parser.add_argument('checkpoint_path', type=str, help='Path to the model checkpoint')
parser.add_argument('output', type=str, help='Path to output `.onnx` file')
parser.add_argument('--n-timesteps', type=int, default=... |
def test_invalid_pdf_pars():
source = {'binning': [2, (- 0.5), 1.5], 'bindata': {'data': [55.0], 'bkg': [50.0], 'bkgerr': [7.0], 'sig': [10.0]}}
pdf = pyhf.simplemodels.uncorrelated_background(source['bindata']['sig'], source['bindata']['bkg'], source['bindata']['bkgerr'])
pars = (pdf.config.suggested_init(... |
def eval_step(apply_fn, state, batch):
logits = apply_fn(state.variables, batch['image'], training=False, mutable=False)
return compute_metrics(logits, batch['label']) |
def is_traceable(data):
return isinstance(data, (type(None), type(Ellipsis), list, tuple, dict, set, int, bool, str, float, slice, torch.device, torch.Size, torch.Tensor, torch.dtype, torch.memory_format)) |
class irreducible_character_basis(generic_character):
def __init__(self, Sym, pfix):
SFA_generic.__init__(self, Sym, basis_name='irreducible symmetric group character', prefix=pfix, graded=False)
self._other = Sym.Schur()
self._p = Sym.powersum()
self.module_morphism(self._self_to_po... |
def optimize(onnx_model_path: Path) -> Path:
from onnxruntime import InferenceSession, SessionOptions
opt_model_path = generate_identified_filename(onnx_model_path, '-optimized')
sess_option = SessionOptions()
sess_option.optimized_model_filepath = opt_model_path.as_posix()
_ = InferenceSession(onnx... |
class Ego4DDataModule(BaseDataModule):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def dataset_cls(self):
return Ego4DDataset
def dataset_cls_no_false(self):
return Ego4DDataset
def dataset_name(self):
return 'ego4d' |
class Generator(BaseGenerator):
def __init__(self, config, mode, X=None):
super(Generator, self).__init__(config, mode)
self.build_generator(X=X)
def generate_random_X(self, shape):
return (np.random.rand(*shape) + 1.0) |
class KitchenTopLeftBurnerV0(KitchenBase):
TASK_ELEMENTS = ['top left burner']
def __init__(self, delta=0, **kwargs):
super(KitchenTopLeftBurnerV0, self).__init__(**kwargs)
self.step_to_primitive_name = {0: 'lift', 1: 'angled_x_y_grasp', 2: 'rotate_about_y_axis', 3: 'no_op', 4: 'no_op'}
... |
def export_gephi():
G_times = canVote_loader.load_canVote_temporarl_edgelist('datasets/canVote_processed/canVote_edgelist.txt')
MP_dict = load_mp()
labels = list(range(2006, 2020, 1))
print(len(MP_dict))
for i in range(len(G_times)):
G = G_times[i]
count = 0
for node in G.nod... |
class dataloader_val(Dataset):
def __init__(self, ImagePth, valtxtfile, transform=None):
self.ImagePth = ImagePth
self.valtxtfile = valtxtfile
self.transform = transform
imagelist = []
labelList = []
imgname = []
classId = []
with open(self.valtxtfile)... |
class NefPartition(SageObject, Hashable):
def __init__(self, data, Delta_polar, check=True):
if (check and (not Delta_polar.is_reflexive())):
raise ValueError('nef-partitions can be constructed for reflexive polytopes ony!')
self._vertex_to_part = tuple((int(el) for el in data))
... |
.parametrize('embedding_size,cross_num,hidden_size,sparse_feature_num,cross_parameterization', [(8, 2, (32,), 2, 'vector'), (8, 1, (32,), 2, 'matrix')])
def test_DCN(embedding_size, cross_num, hidden_size, sparse_feature_num, cross_parameterization):
model_name = 'DCN'
sample_size = SAMPLE_SIZE
(x, y, featu... |
class MultiProcessInitLogger():
def __init__(self, app_name):
date_str = datetime.datetime.now().strftime('%Y%m%d-%H%M%S')
self.log_name = ((app_name + '-') + date_str)
def __call__(self, *args):
init_logger(self.log_name) |
def cyclotomic_to_gamma(cyclo_up, cyclo_down):
dico = defaultdict(int)
for d in cyclo_up:
dico[d] += 1
for d in cyclo_down:
dico[d] -= 1
resu = defaultdict(int)
for n in dico:
for d in divisors(n):
resu[d] += (moebius((n / d)) * dico[n])
return {d: resu[d] for... |
class Region(object):
def __init__(self, drClass, rx1drClass, beaconProps=BeaconProperties()):
if (not issubclass(drClass, DataRate)):
raise TypeError('Invalid data rate implementation')
self._drClass = drClass
if (not issubclass(rx1drClass, Rx1DrOffset)):
raise TypeE... |
def test_gmm_wrong_num_modes_format_1():
with pytest.raises(FisherVectorException):
learn_gmm([np.zeros((5, 10)), np.zeros((4, 10))], n_modes='not_valid') |
def count_permutation_trials(per_doc1, per_doc2, base_diff, n_trials):
(metrics, bases) = zip(*base_diff.items())
ops = [(operator.le if (base < 0) else operator.ge) for base in bases]
better = ([0] * len(metrics))
for _ in range(n_trials):
result = _permutation_trial(per_doc1, per_doc2)
... |
def view_model_param(net_params):
model = DGNNet(net_params)
total_param = 0
print('MODEL DETAILS:\n')
for param in model.parameters():
total_param += np.prod(list(param.data.size()))
print('DGN Total parameters:', total_param)
return total_param |
def get_relations_by_type(data_dir):
with open(os.path.join(data_dir, 'raw.kb')) as f:
triples = list(f.readlines())
with open(os.path.join(data_dir, 'train.triples')) as f:
triples += list(f.readlines())
triples = list(set(triples))
query_answers = dict()
theta_1_to_M = 1.5
for ... |
def main(argv=None):
gen_dim = FLAGS.gen_dimension
generator_dims = [(64 * gen_dim), ((64 * gen_dim) // 2), ((64 * gen_dim) // 4), ((64 * gen_dim) // 8), 3]
discriminator_dims = [3, 64, (64 * 2), (64 * 4), (64 * 8), 1]
(crop_image_size, resized_image_size) = map(int, FLAGS.image_size.split(','))
if ... |
def test_get_tasks_for_collaborator(assigner):
tasks = assigner.get_tasks_for_collaborator('one', 2)
assert (tasks == default_tasks)
assert (len(tasks) == 3)
assert isinstance(tasks[0], TrainTask)
assert isinstance(tasks[1], ValidateTask) |
class FrameSecondMeter(object):
def __init__(self):
self.st = time.time()
self.fps = None
self.ed = None
self.frame_n = 0
def add_frame_n(self, frame_n):
self.frame_n += frame_n
def end(self):
self.ed = time.time()
self.fps = (self.frame_n / (self.ed -... |
_method
def ith_to_zero_rotation_matrix(v, i, ring=None):
if (ring is not None):
v = vector(ring, v)
dim = len(v)
i = (i % dim)
j = ((i - 1) % dim)
(a, b) = (v[j], v[i])
if (b == 0):
return identity_matrix(dim, sparse=True)
from sage.misc.functional import sqrt
norm = sqr... |
def world_gen(coordinate={}, master={}, config_file=None):
world = {}
for (axis_name, axis) in master.iteritems():
if ((axis['sequence'] is not None) and (coordinate[axis_name] in axis['sequence'])):
for i in world:
if (i in axis['sequence'][coordinate[axis_name]]):
... |
class MultiMetricStats():
def __init__(self, metric, n_jobs=1, batch_eval=False):
self.metric = _dictify(metric)
self.n_jobs = n_jobs
self.batch_eval = batch_eval
self.ids = []
self.metrics = {}
def append(self, ids, *args, **kwargs):
self.ids.extend(ids)
... |
def train_one_epoch(context, args, model, optimizer, scheduler, loader, loss, temp, decoder=None, transform=None):
model.train()
train_loss = 0
optimizer.zero_grad()
for (i, data) in enumerate(loader):
if (transform is not None):
(x, y, z) = data
z = z.to(args.device)
... |
def collect_occluded_linemod_testlist(rootpath, outname):
path = (rootpath + 'RGB-D/rgb_noseg/')
imgs = [f for f in os.listdir(path) if (f.endswith('.jpg') or f.endswith('.png'))]
imgs.sort()
allf = open(outname, 'w')
for i in imgs:
allf.write(((path + i) + '\n')) |
def _validate_weights(w, dtype=np.double):
w = _validate_vector(w, dtype=dtype)
if np.any((w < 0)):
raise ValueError('Input weights should be all non-negative')
return w |
def load_imageid(folder):
images = load_folder(folder, 'jpg')
img_ids = set()
for img in images:
img_id = int(img.split('/')[(- 1)].split('.')[0].split('_')[(- 1)])
img_ids.add(img_id)
return img_ids |
def hsl_to_hsv(color):
(hi, si, li) = [float(d) for d in color]
ho = hi
si *= ((li / 100.0) if (li <= 50.0) else (1.0 - (li / 100.0)))
vo = (li + si)
so = (((200.0 * si) / vo) if vo else 0.0)
return (ho, so, vo) |
class DataFrameTracedOps(DFIterDataPipe):
def __init__(self, source_datapipe, output_var):
self.source_datapipe = source_datapipe
self.output_var = output_var
def __iter__(self):
for item in self.source_datapipe:
(yield self.output_var.calculate_me(item)) |
class Mish(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return (x * torch.tanh(F.softplus(x))) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.