code stringlengths 101 5.91M |
|---|
def basic_gn_shortcut(model, prefix, blob_in, dim_in, dim_out, stride):
if (dim_in == dim_out):
return blob_in
return model.ConvGN(blob_in, (prefix + '_branch1'), dim_in, dim_out, kernel=1, group_gn=get_group_gn(dim_out), stride=stride, pad=0, group=1) |
class TaskRunner():
def __init__(self, data_loader, tensor_dict_split_fn_kwargs: dict=None, **kwargs):
self.data_loader = data_loader
self.feature_shape = self.data_loader.get_feature_shape()
if (tensor_dict_split_fn_kwargs is None):
tensor_dict_split_fn_kwargs = {}
self.... |
class Modelnet40Config(Config):
dataset = 'ModelNet40'
num_classes = None
dataset_task = ''
input_threads = 10
architecture = ['simple', 'resnetb', 'resnetb_strided', 'resnetb', 'resnetb', 'resnetb_strided', 'resnetb', 'resnetb', 'resnetb_strided', 'resnetb', 'resnetb', 'resnetb_strided', 'resnetb',... |
def group_normalization(x, beta, gamma, num_groups, channel_axis=1, batch_axis=0, eps=1e-05, output_stat=False):
from .function_bases import group_normalization as group_normalization_base
n_outputs = (3 if output_stat else 1)
batch_axis = _force_list(batch_axis)
no_scale = (gamma is None)
no_bias =... |
class RowStandardTableaux(Tableaux):
def __classcall_private__(cls, *args, **kwargs):
from sage.combinat.partition import _Partitions
from sage.combinat.skew_partition import SkewPartitions
if args:
n = args[0]
elif ('n' in kwargs):
n = kwargs[n]
else:... |
class CamembertTokenizer(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, bos_token='<s... |
class MaskRCNN(Detector):
def __init__(self, new_size=(416, 416), **kwargs):
super(MaskRCNN, self).__init__()
self.p = yaml.load(open('/home/code/classifiers/params.yaml', 'r'), Loader=yaml.FullLoader)['maskrcnn']['_base']
config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_... |
_ordering
class Simplex(SageObject):
def __init__(self, X):
try:
N = (int(X) + 1)
if (N < 0):
raise ValueError('the n-simplex is only defined if n > -2')
self.__tuple = tuple(range(N))
except TypeError:
self.__tuple = tuple(X)
s... |
_pydub_effect
def low_pass_filter(seg, cutoff_freq, order=5):
filter_fn = _mk_butter_filter(cutoff_freq, 'lowpass', order=order)
return seg.apply_mono_filter_to_each_channel(filter_fn) |
def add_gazebo_thruster_config(xacro_target, yaml_file=None, requested_macros=None, boiler_plate_top='', boiler_plate_bot=''):
xacro_file = open(xacro_target, 'ab')
xacro_file.write(boiler_plate_top)
if (requested_macros is None):
s = open(yaml_file, 'r')
requested_macros = yaml.safe_load(s)... |
def distance(c1, c2):
(c1r, c1g, c1b) = c1
(c2r, c2g, c2b) = c2
dr = (c1r - c2r)
dg = (c1g - c2g)
db = (c1b - c2b)
return (((dr * dr) + (dg * dg)) + (db * db)) |
def __call__(self, func):
(func)
def wrapper(*args, **kwargs):
with self:
return func(*args, **kwargs)
return wrapper |
('detection', 'lstm', LSTMParams)
class ForecastBasedLSTM(ForcastBasedNeuralAD):
def __init__(self, config: LSTMParams):
super().__init__(config)
self.config = config
self.model = LSTM(config=self.config) |
def test_suppress_validation():
X = np.array([0, np.inf])
with pytest.raises(ValueError):
assert_all_finite(X)
sklearn.set_config(assume_finite=True)
assert_all_finite(X)
sklearn.set_config(assume_finite=False)
with pytest.raises(ValueError):
assert_all_finite(X) |
def ignore_comments(lines_enum):
for (line_number, line) in lines_enum:
line = COMMENT_RE.sub('', line)
line = line.strip()
if line:
(yield (line_number, line)) |
def mock_mask_rcnn_inference(tensor_mode, patched_module, check=True):
with mock.patch('{}.mask_rcnn_inference'.format(patched_module), side_effect=Caffe2MaskRCNNInference()) as mocked_func:
(yield)
if check:
assert (mocked_func.call_count > 0) |
class ContrastiveHead(nn.Module):
def __init__(self, temperature=0.2):
super(ContrastiveHead, self).__init__()
self.criterion = nn.CrossEntropyLoss()
self.temperature = temperature
def forward(self, pos, neg):
N = pos.size(0)
logits = torch.cat((pos, neg), dim=1)
... |
class HybridSession(object):
def get_session(cls, agent, kb, lexicon, generator, manager, config=None):
if (kb.role == 'buyer'):
return BuyerHybridSession(agent, kb, lexicon, config, generator, manager)
elif (kb.role == 'seller'):
return SellerHybridSession(agent, kb, lexicon... |
def make_jobarray_configs(dataset, nb_repetitions):
(train_horses, test_horses) = get_train_test(dataset, avoid_sir_holger=avoid_sir_holger)
output_dir = os.path.join('../run_scripts', job_name)
helpers.mkdir(output_dir)
counter_config = 1
for rep in range(nb_repetitions):
for (ind, test_sub... |
def labelcolormap(N):
cmap = np.zeros((N, 3), dtype=np.uint8)
for i in range(N):
r = 0
g = 0
b = 0
id = i
for j in range(7):
str_id = uint82bin(id)
r = (r ^ (np.uint8(str_id[(- 1)]) << (7 - j)))
g = (g ^ (np.uint8(str_id[(- 2)]) << (7 -... |
def mean_percentile(image, footprint, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1):
return _apply(percentile_cy._mean, image, footprint, out=out, mask=mask, shift_x=shift_x, shift_y=shift_y, p0=p0, p1=p1) |
def test_sum():
dtypes = ['datetime64[s]', 'timedelta64[D]']
arrays = (np.arange(0, 12, dtype=dtype) for dtype in dtypes)
for array in arrays:
content = ak.contents.NumpyArray(array)
offsets = ak.index.Index64(np.array([0, 4, 8, 12], dtype=np.int64))
depth = ak.contents.ListOffsetArr... |
def plot(data, title='Figure', legends=None, axis_x=None, axis_y=None, file_path=None, file_name=None, figure_size=(16, 9), has_grid=True, limits_axis_y=None, upper_lower_data=None, limits_axis_x=None):
plots = []
colors = ['steelblue', 'indianred', 'red', 'cyan', 'magenta', 'yellow', 'black', 'gray', 'sienna',... |
def add_fast_rcnn_losses(model):
(cls_prob, loss_cls) = model.net.SoftmaxWithLoss(['cls_score', 'labels_int32'], ['cls_prob', 'loss_cls'], scale=model.GetLossScale())
loss_bbox = model.net.SmoothL1Loss(['bbox_pred', 'bbox_targets', 'bbox_inside_weights', 'bbox_outside_weights'], 'loss_bbox', scale=model.GetLoss... |
()
('--num_epochs', default=500)
('--num_train_tasks', default=100)
('--num_test_tasks', default=30)
('--encoder_hidden_size', default=200)
('--net_size', default=300)
('--num_steps_per_epoch', default=2000)
('--num_initial_steps', default=2000)
('--num_steps_prior', default=400)
('--num_extra_rl_steps_posterior', defa... |
class TestOptLGS(TestCase):
def test_quadratic_minimum(self):
lgs = OptimizerLGS()
result = lgs(f, ((), ()))
self.assertEqual(result['best'][0], 1.0)
self.assertEqual(result['best'][1], 2.0) |
def read_frequency_vocab(filename, min_freq):
filename = os.path.join(data.workspace.vocab, filename)
words = [UNK, EOS]
with open(filename, 'r', 'utf8') as fin:
for line in fin:
(freq, word) = line.rstrip('\n').split('\t')
if (word.strip() and (int(freq) >= min_freq)):
... |
def process(filename):
music = muspy.read(filename)
if (not music.tracks):
return None
music.adjust_resolution(24)
if (music.get_real_end_time() > 1200):
return None
notes = {'Piano': [], 'Guitar': [], 'Bass': [], 'Strings': [], 'Brass': [], 'Drums': []}
for track in music.tracks... |
class Model(nn.Module):
def __init__(self, input_size, output_size):
super(Model, self).__init__()
self.fc = nn.Linear(input_size, output_size)
def forward(self, input):
output = self.fc(input)
return output |
def get_default_qat_qconfig(backend='fbgemm'):
if (backend == 'fbgemm'):
qconfig = QConfig(activation=FakeQuantize.with_args(observer=MovingAverageMinMaxObserver, quant_min=0, quant_max=255, reduce_range=True), weight=default_per_channel_weight_fake_quant)
elif (backend == 'qnnpack'):
qconfig = ... |
class KeyManager():
def __init__(self, timeline, keysize, num_keys):
self.timeline = timeline
self.lower_protocols = []
self.keysize = keysize
self.num_keys = num_keys
self.keys = []
self.times = []
def send_request(self):
for p in self.lower_protocols:
... |
_module()
class SyncRandomSizeHook(Hook):
def __init__(self, ratio_range=(14, 26), img_scale=(640, 640), interval=1, device='cuda'):
warnings.warn("DeprecationWarning: SyncRandomSizeHook is deprecated. Please use Resize pipeline to achieve similar functions. Due to the multi-process dataloader, its behavior... |
class Sentence(object):
def __init__(self, sentence):
super(Sentence, self).__init__()
sent_text = sentence[0]
sent_ptags = sentence[1]
self.sent = sent_text
self.tokens = sent_text.split(' ')
self.pos = sent_ptags.split(' ')
self.phrases = {}
self.phr... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--task', required=True, choices=TASKS)
parser.add_argument('--align', required=True, choices=ALIGNS, help='the align model to use')
parser.add_argument('--aspect', required=True, help='the aspect to evaluate')
parser.add_argum... |
def create_model(weight_path):
model = smp.Unet(encoder_name='mobilenet_v2', encoder_weights=None, in_channels=3, classes=2)
model.load_state_dict(torch.load(weight_path))
return model |
def analyze_SelectStmt(node: SelectStmt, cache: dict):
limit = (node.limitCount.val.ival if node.limitCount else (- 1))
sql_dnf_predicates = convert2dnf(node.whereClause)
if (isinstance(sql_dnf_predicates, BoolExpr) and (sql_dnf_predicates.boolop == BoolExprType.OR_EXPR)):
choices = sorted(sql_dnf_p... |
class InfoGainSplitCriterion(SplitCriterion):
def __init__(self, min_branch_frac_option=0.01):
super().__init__()
self.min_branch_frac_option = min_branch_frac_option
def get_merit_of_split(self, pre_split_dist, post_split_dist):
if (self.num_subsets_greater_than_frac(post_split_dist, se... |
_grad()
def test(model, x_eval, y_eval, evaluator):
model.eval()
y_pred = model(x_eval).argmax(dim=(- 1))
return evaluator.eval({'y_true': y_eval, 'y_pred': y_pred})['acc'] |
class W2lKenLMDecoder(W2lDecoder):
def __init__(self, args, tgt_dict):
super().__init__(args, tgt_dict)
self.silence = (tgt_dict.index('<ctc_blank>') if ('<ctc_blank>' in tgt_dict.indices) else tgt_dict.bos())
self.lexicon = load_words(args.lexicon)
self.word_dict = create_word_dict(... |
def gen_testloss(args):
params = utils.load_params(args.model_dir)
ckpt_dir = os.path.join(args.model_dir, 'checkpoints')
ckpt_paths = [int(e[11:(- 3)]) for e in os.listdir(ckpt_dir) if (e[(- 3):] == '.pt')]
ckpt_paths = np.sort(ckpt_paths)
headers = ['epoch', 'step', 'loss', 'discrimn_loss_e', 'com... |
def max_pool(inputs, kernel=3):
padding = ((kernel - 1) // 2)
max = F.max_pool3d(inputs, kernel_size=kernel, stride=1, padding=padding)
keep = (inputs == max).float()
return (keep * inputs) |
def plot_edges_from_adj(adj, coordinates, emph_short_edges=True, format=None, save_to=None, set_title=True, min_weight=0.1, show=True, k_hops_is_short=1, arrows=False, horizon=(- 1), resolution=5):
graph = get_graph_from_adj(adj, coordinates, min_weight=min_weight)
print(f'#Nodes: {graph.number_of_nodes()}, #Ed... |
class CubicHeckeDataSection(Enum):
basis = 'basis'
regular_left = 'regular_left'
regular_right = 'regular_right'
split_irred = 'split_irred'
markov_tr_cfs = 'markov_tr_cfs' |
class SimpleCNN(nn.Module):
def __init__(self, in_channel, pred_dim, num_layers=5):
super(SimpleCNN, self).__init__()
chan = 64
stride = 1
self.layers = []
for layer_num in list(range(num_layers)):
if (layer_num == 0):
in_dim = in_channel
... |
.gpu
def test_memory_pool_tasklet():
def tester(A: CudaArray, B: CudaArray):
tmp = (A + 1)
with dace.tasklet(dace.Language.CPP):
(t << tmp)
(b >> B)
A[:] = B
sdfg = tester.to_sdfg()
for arr in sdfg.arrays.values():
arr.storage = dace.StorageType.GPU_Gl... |
def gen_nsml_report(acc_train, aux_out_train, acc_dev, aux_out_dev):
(ave_loss, acc_sc, acc_sa, acc_wn, acc_wc, acc_wo, acc_wvi, acc_wv, acc_lx, acc_x) = acc_train
(grad_abs_mean_mean, grad_abs_mean_sig, grad_abs_sig_mean) = aux_out_train
(ave_loss_t, acc_sc_t, acc_sa_t, acc_wn_t, acc_wc_t, acc_wo_t, acc_wv... |
def plot_dist_for_two_four_room_tasks(**kwargs):
task1 = 'LearnEightPoliciesTileCodingFeat'
task2 = 'HighVarianceLearnEightPoliciesTileCodingFeat'
save_dir = os.path.join('pdf_plots', 'Misc', 'CompareDistsFR')
d_mu1 = load_d_mu(task1)
d_mu2 = load_d_mu(task2)
state_values1 = load_state_values(ta... |
def register_Ns3LteGlobalPathlossDatabase_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteGlobalPathlossDatabase const &', 'arg0')])
cls.add_method('GetPathloss', 'double', [param('uint16_t', 'cellId'), param('uint64_t', 'imsi')])
cls.add_method('Print', 'void', []... |
def block17(net, scale=1.0, activation_fn=tf.nn.relu, scope=None, reuse=None):
with tf.variable_scope(scope, 'Block17', [net], reuse=reuse):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 192, 1, scope='Conv2d_1x1')
with tf.variable_scope('Branch_1'):
tower... |
_grad()
def test(model, predictor, data, split_edge, evaluator, batch_size):
model.eval()
h = model(data.x, data.adj_t)
pos_train_edge = split_edge['train']['edge'].to(h.device)
pos_valid_edge = split_edge['valid']['edge'].to(h.device)
neg_valid_edge = split_edge['valid']['edge_neg'].to(h.device)
... |
_numpy_output(check_dtype=True)
def test_ufunc_bitwise_and_uu(A: dace.uint32[10], B: dace.uint32[10]):
return np.bitwise_and(A, B) |
def get_logger(log_filename='multiproc_mpi.log'):
open(log_filename, 'w').close()
log_id = ('master' if (mpi_rank == 0) else ('slave%d' % mpi_comm.rank))
logger = logging.getLogger(log_id)
logger.setLevel(logging.INFO)
mh = MPIFileHandler(log_filename)
formatter = logging.Formatter(('%(asctime)s... |
def main():
args = get_args_from_command_line()
if (args.gpu_id is not None):
cfg.CONST.DEVICE = args.gpu_id
if (args.phase is not None):
cfg.NETWORK.PHASE = args.phase
if (args.weights is not None):
cfg.CONST.WEIGHTS = args.weights
if (args.data_path is not None):
cf... |
def extend_and_repeat(tensor, axis, repeat):
return jnp.repeat(jnp.expand_dims(tensor, axis), repeat, axis=axis) |
def mk_state(car, value):
return state([(num(value) if (cars[i] == car) else bound(i)) for i in range(num_cars)]) |
class Distribution(object):
PKG_INFO = 'PKG-INFO'
def __init__(self, location=None, metadata=None, project_name=None, version=None, py_version=PY_MAJOR, platform=None, precedence=EGG_DIST):
self.project_name = safe_name((project_name or 'Unknown'))
if (version is not None):
self._ver... |
_module()
class LoadPanopticAnnotations(object):
def __init__(self, reduce_zero_label=False, file_client_args=dict(backend='disk'), imdecode_backend='pillow'):
self.reduce_zero_label = reduce_zero_label
self.file_client_args = file_client_args.copy()
self.file_client = None
self.imde... |
class TestModelFromArtisDensityAbundancesAllAscii():
(autouse=True)
def setup(self, example_model_file_dir, atomic_dataset):
self.config = Configuration.from_yaml((example_model_file_dir / 'tardis_configv1_ascii_density_abund.yml'))
self.config.model.structure.filename = 'density.dat'
se... |
class Swin2SRImageProcessor(metaclass=DummyObject):
_backends = ['vision']
def __init__(self, *args, **kwargs):
requires_backends(self, ['vision']) |
def get_output(input_text, input_len=128, output_len=128):
input_ids = torch.cat([tokenizer(inp, padding='max_length', max_length=input_len, return_tensors='pt').input_ids.to('cuda') for inp in input_text])
outputs = model.generate(input_ids, max_length=output_len)
outputs = tokenizer.batch_decode(outputs, ... |
def cdd_Hrepresentation(cdd_type, ieqs, eqns, file_output=None):
ieqs = _set_to_None_if_empty(ieqs)
eqns = _set_to_None_if_empty(eqns)
(num, ambient_dim) = _common_length_of(ieqs, eqns)
ambient_dim -= 1
if (cdd_type == 'real'):
from sage.rings.real_double import RDF
base_ring = RDF
... |
def _sizeof_fmt(num):
units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB']
decimals = [0, 0, 1, 2, 2, 2]
if (num > 1):
exponent = min(int(log(num, 1024)), (len(units) - 1))
quotient = (float(num) / (1024 ** exponent))
unit = units[exponent]
num_decimals = decimals[exponent]
... |
def _read_structdesc(f):
structdesc = {}
structstart = _read_long(f)
if (structstart != 9):
raise Exception('STRUCTSTART should be 9')
structdesc['name'] = _read_string(f)
predef = _read_long(f)
structdesc['ntags'] = _read_long(f)
structdesc['nbytes'] = _read_long(f)
structdesc['... |
class LinearAttention(nn.Module):
def __init__(self, d_model, n_heads, feature_map_cfg=None, eps=1e-06, dropout=0.0):
super().__init__()
query_dims = (d_model // n_heads)
self.n_heads = n_heads
self.feature_map = (hydra.utils.instantiate(feature_map_cfg, query_dims) if (feature_map_c... |
def _restore_leading_dim(x: TensorType, leading_dim: TensorType) -> TensorType:
single_x_shape = tf.shape(x[0])
output_x_shape = tf.concat([leading_dim, single_x_shape], axis=0)
return tf.reshape(x, output_x_shape) |
def freeze_bn_func(m):
if ((m.__class__.__name__.find('BatchNorm') != (- 1)) or isinstance(m, nn.BatchNorm2d)):
m.weight.requires_grad = False
m.bias.requires_grad = False |
def sort(packed, ref, reverse=True):
assert ((isinstance(packed, tuple) or isinstance(packed, list)) and isinstance(ref, list))
packed = (([ref] + [range(len(ref))]) + list(packed))
sorted_packed = [list(t) for t in zip(*sorted(zip(*packed), reverse=reverse))]
return tuple(sorted_packed[1:]) |
def save_graph_edgelist(G, dst_dir):
nodelist = G.nodes()
node_id2idx = {k: v for (v, k) in enumerate(nodelist)}
with open(os.path.join(dst_dir, 'graph_node_id2idx.txt'), 'w') as f:
for (i, node) in enumerate(nodelist):
print(f'{node}, {i}', file=f)
with open(os.path.join(dst_dir, 'g... |
def up_stage(inputs, skip, filters, prior_fn, kernel_size=3, activation='relu', padding='SAME'):
up = UpSampling3D()(inputs)
up = tfp.layers.Convolution3DFlipout(filters, 2, activation=activation, padding=padding, kernel_prior_fn=prior_fn)(up)
up = GroupNormalization()(up)
merge = concatenate([skip, up]... |
def register_all_objects365(root):
for (key, (image_root, json_file)) in _PREDEFINED_SPLITS_OBJECTS365.items():
register_coco_instances(key, _get_builtin_metadata(key), (os.path.join(root, json_file) if ('://' not in json_file) else json_file), os.path.join(root, image_root)) |
def levenshtein_matrix(first, second, cost_ins=1, cost_del=1, cost_sub=2):
first_length = (len(first) + 1)
second_length = (len(second) + 1)
distance_matrix = [([None] * second_length) for x in range(first_length)]
backpointers = {}
distance_matrix[0][0] = 0
for i in range(1, first_length):
... |
def read_tfrecord(example, train):
features = {'image': tf.io.FixedLenFeature([], tf.string), 'class': tf.io.FixedLenFeature([], tf.int64)}
example = tf.io.parse_single_example(example, features)
image = tf.image.decode_jpeg(example['image'], channels=3)
if train:
image = augment(image)
else... |
class TestFilelist(torch.utils.data.Dataset):
def __init__(self, root, flist, transform=None, flist_reader=default_flist_reader, loader=default_loader):
self.root = root
self.imlist = flist_reader(flist)
self.transfrom = transform
self.loader = loader
def __getitem__(self, index)... |
class Rdist(Module, metaclass=abc.ABCMeta):
def __init__(self, manif: Manifold, kmax: int):
super(Rdist, self).__init__()
self.manif = manif
self.d = manif.d
self.kmax = kmax
def sample(self, size, Y, batch_idxs, sample_idxs, kmax, analytic_kl, prior) -> Tuple[(Tensor, Tensor)]:
... |
class FunctionLoader(BaseLoader):
def __init__(self, load_func):
self.load_func = load_func
def get_source(self, environment, template):
rv = self.load_func(template)
if (rv is None):
raise TemplateNotFound(template)
elif isinstance(rv, string_types):
retu... |
def assert_cache_file_is_ok(url, file_path):
cache_file_md5sum = _get_file_md5sum(file_path)
ref_md5sum = _get_reference_md5sum(url)
assert (cache_file_md5sum == ref_md5sum), 'Target URL {} appears to be downloaded to the local cache file {}, but the md5 hash of the local file does not match the reference (... |
def do_flop(cfg):
if isinstance(cfg, CfgNode):
data_loader = build_detection_test_loader(cfg, cfg.DATASETS.TEST[0])
model = build_model(cfg)
DetectionCheckpointer(model).load(cfg.MODEL.WEIGHTS)
else:
data_loader = instantiate(cfg.dataloader.test)
model = instantiate(cfg.m... |
def ref_mean_subtraction(x, rmean, t, base_axis, batch_stat):
if batch_stat:
mean = (x.mean(tuple(range(0, base_axis))) if (base_axis >= 0) else x.mean(tuple(range(0, (len(x.shape) + base_axis)))))
rmean[...] = (rmean + ((mean - rmean) / (t + 1)))
t += 1
return (x - rmean) |
def print_results(results, num_print):
print()
values = list(results.values())
num_examples = len(values[0])
start = int((num_examples / 4))
end = (start + int((num_print / 2)))
first_list = [val[start:end] for val in values]
start = int(((3 * num_examples) / 4))
end = ((start + num_prin... |
class NeuralIR_Encoder(nn.Module):
def __init__(self, word_embeddings: TextFieldEmbedder, neural_ir_model: nn.Module):
super(NeuralIR_Encoder, self).__init__()
self.word_embeddings = word_embeddings
self.neural_ir_model = neural_ir_model
def forward(self, query: Dict[(str, torch.Tensor)]... |
class SiblingsPolicy(InclusivePolicy):
def negative_examples(self, node) -> np.ndarray:
siblings = self._get_siblings(node)
negative_classes = set()
for sibling in siblings:
negative_classes.update(self._get_descendants(sibling, inclusive=True))
negative_examples = np.isi... |
class GaussianMLPTwoHeadedModule(GaussianMLPBaseModule):
def __init__(self, input_dim, output_dim, hidden_sizes=(32, 32), hidden_nonlinearity=torch.tanh, hidden_w_init=nn.init.xavier_uniform_, hidden_b_init=nn.init.zeros_, output_nonlinearity=None, output_w_init=nn.init.xavier_uniform_, output_b_init=nn.init.zeros_... |
_function_dispatch(_recursive_fill_fields_dispatcher)
def recursive_fill_fields(input, output):
newdtype = output.dtype
for field in newdtype.names:
try:
current = input[field]
except ValueError:
continue
if (current.dtype.names is not None):
recursive... |
class RichardsTests1D(BaseRichardsTest):
def get_mesh(self):
mesh = discretize.TensorMesh([np.ones(20)])
mesh.set_cell_gradient_BC('dirichlet')
print(mesh.dim)
return mesh
def get_rx_list(self, times):
locs = np.array([[5.0], [10], [15]])
rxSat = richards.receiver... |
def main(args):
keys = ['train', 'dev', 'test']
dfs = []
for k in keys:
df = pd.read_json(os.path.join(args.dataset, 'data', (k + '.jsonl')), lines=True)
df['split'] = k
dfs.append(df)
dfs = pd.concat(dfs).reset_index(drop=True)
if ('annotation_id' in dfs.columns):
df... |
def _get_treatment_role(roles: Dict[(Union[(ColumnRole, str)], Union[(str, Sequence[str])])]) -> Tuple[(Union[(TreatmentRole, str)], str)]:
treatment_role: Optional[Union[(TreatmentRole, str)]] = None
treatment_col: str
for (k, v) in roles.items():
if (isinstance(k, TreatmentRole) or (isinstance(k, ... |
def test():
print('Nested stream test')
Bdata = np.zeros([2], np.int32)
sdfg(B=Bdata)
B_regression = np.array([2, 0], dtype=np.int32)
diff = np.linalg.norm((B_regression - Bdata))
print('Difference:', diff)
assert (diff == 0) |
class FiniteWordPath_square_grid_list(WordDatatype_list, FiniteWordPath_square_grid, FiniteWord_class):
pass |
def set_time_limit_in_seconds(parser, args, component):
param = (component + '_time_limit')
limit = getattr(args, param)
if (limit is not None):
setattr(args, param, _get_time_limit_in_seconds(limit, parser)) |
def COM(self, marker):
n = (i16(self.fp.read(2)) - 2)
s = ImageFile._safe_read(self.fp, n)
self.info['comment'] = s
self.app['COM'] = s
self.applist.append(('COM', s)) |
def select_policies(runs, metric_np, K):
S = []
n = len(runs)
S.append(np.random.randint(0, n))
for iter in range(1, K):
v = np.zeros((n,), dtype=np.float32)
for i in range(n):
if (i not in S):
for j in S:
v[i] += abs((metric_np[i] - metric... |
class Conv1DTranspose(tf.keras.layers.Layer):
def __init__(self, filters, kernel_size, strides=1, padding='valid', **kwargs):
super().__init__()
self.conv2dtranspose = tf.keras.layers.Conv2DTranspose(filters, (kernel_size, 1), (strides, 1), padding, **kwargs)
def call(self, x):
x = tf.ex... |
def test_detection_list_select():
detections = seisbench.util.DetectionList([seisbench.util.Detection('CX.PB01.', None, None, peak_value=0.5), seisbench.util.Detection('CX.PB02.', None, None, peak_value=0.3), seisbench.util.Detection('CX.PB03.', None, None, peak_value=None)])
assert (len(detections.select(min_c... |
_REGISTRY.register()
def build_effnet_backbone(cfg):
pretrain = cfg.MODEL.BACKBONE.PRETRAIN
pretrain_path = cfg.MODEL.BACKBONE.PRETRAIN_PATH
last_stride = cfg.MODEL.BACKBONE.LAST_STRIDE
bn_norm = cfg.MODEL.BACKBONE.NORM
depth = cfg.MODEL.BACKBONE.DEPTH
cfg_files = {'b0': 'fastreid/modeling/backb... |
def flaky_xfail_mark(exception, issue_numbers):
if isinstance(issue_numbers, int):
issue_numbers = [issue_numbers]
if (not issue_numbers):
raise ValueError('at least one issue must be specified when marking a test as flaky')
issues = ' '.join((f'< for num in issue_numbers))
return pytest... |
def colorx(clip, factor):
return clip.fl_image((lambda pic: np.minimum(255, (factor * pic)).astype('uint8'))) |
def count_used_parameters(model):
return sum((p.numel() for p in model.parameters() if (p.grad is not None))) |
def test_short_decorator():
A = np.random.rand(20)
assert np.allclose(short_decorator(A), (A + A)) |
def get_all_int_dtypes() -> List[torch.dtype]:
return [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64] |
_grad()
def tensor2np(x: torch.Tensor) -> np.array:
x = (127.5 * (x + 1))
x = x.round().clamp(min=0, max=255).byte()
x = x.squeeze(0)
x = x.cpu().numpy()
x = np.transpose(x, (1, 2, 0))
x = np.ascontiguousarray(x)
return x |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.