code stringlengths 101 5.91M |
|---|
def is_unique(layout, axis: (Integral | None)=None) -> bool:
negaxis = (axis if (axis is None) else (- axis))
starts = ak.index.Index64.zeros(1, nplike=layout._backend.index_nplike)
parents = ak.index.Index64.zeros(layout.length, nplike=layout._backend.index_nplike)
return layout._is_unique(negaxis, sta... |
def idctn(x, type=2, s=None, axes=None, norm=None, overwrite_x=False, workers=None, *, orthogonalize=None):
return _execute(_pocketfft.idctn, x, type, s, axes, norm, overwrite_x, workers, orthogonalize) |
def to_pair(value, name):
if isinstance(value, Iterable):
if (len(value) != 2):
raise ValueError('Expected `{}` to have exactly 2 elements, got: ({})'.format(name, value))
return value
return tuple(repeat(value, 2)) |
class SimplifiedBasicBlock(BaseModule):
expansion = 1
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, plugins=None, init_fg=None):
super(SimplifiedBasicBlock, self).__init__(init_fg)
as... |
class add_attn(nn.Module):
def __init__(self, x_channels, g_channels=256):
super(add_attn, self).__init__()
self.W = nn.Sequential(nn.Conv2d(x_channels, x_channels, kernel_size=1, stride=1, padding=0), nn.BatchNorm2d(x_channels))
self.theta = nn.Conv2d(x_channels, x_channels, kernel_size=2, ... |
_model
def swsl_resnext101_32x16d(pretrained=True, **kwargs):
model_args = dict(block=Bottleneck, layers=[3, 4, 23, 3], cardinality=32, base_width=16, **kwargs)
return _create_resnet('swsl_resnext101_32x16d', pretrained, **model_args) |
def gray2rgb(img):
img = (img[(..., None)] if (img.ndim == 2) else img)
out_img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
return out_img |
def __plot_scores_kde(scores_pos, scores_neg, fig_name):
plt.rcParams['figure.figsize'] = [7.0, 3.5]
plt.rcParams['figure.autolayout'] = True
fig1 = plt.figure()
sns.kdeplot(scores_pos, bw=0.5, color='blue')
fig2 = plt.figure()
sns.kdeplot(scores_neg, bw=0.5, color='red')
pp = PdfPages(fig_n... |
def se_resnext101_32x4d(num_classes=1000):
model = SENet(SEResNeXtBottleneck, [3, 4, 23, 3], groups=32, reduction=16, dropout_p=None, inplanes=64, input_3x3=False, downsample_kernel_size=1, downsample_padding=0, num_classes=num_classes)
settings = pretrained_settings['se_resnext101_32x4d']['imagenet']
initi... |
class PyList(gdb.Command):
def __init__(self):
gdb.Command.__init__(self, 'py-list', gdb.COMMAND_FILES, gdb.COMPLETE_NONE)
def invoke(self, args, from_tty):
import re
start = None
end = None
m = re.match('\\s*(\\d+)\\s*', args)
if m:
start = int(m.grou... |
def extract_specific_category_data(category, images, labels, N=None):
ind = np.where((labels == category))[0]
if (N is not None):
ind = ind[0:N]
extracted_images = images[ind]
extracted_labels = labels[ind]
images_extracted_from = np.delete(images, ind, 0)
labels_extracted_from = np.dele... |
def read_continuous_bipartite_matrix(fh):
m = None
n = 0
G = dict()
for line in fh:
G[n] = dict()
sline = line.split()
if (m == None):
m = len(sline)
elif (len(sline) != m):
sys.stderr.write(('Error: expecting %d columns but got %d on row %d\n' % ... |
class KMeans(object):
def __init__(self, num_cluster, seed, hidden_size, gpu_id=0, device='cpu'):
self.seed = seed
self.num_cluster = num_cluster
self.max_points_per_centroid = 4096
self.min_points_per_centroid = 0
self.gpu_id = 0
self.device = device
self.fir... |
class BaseClass(TemporaryShowyourworkRepository):
local_build_only = True
def customize(self):
with edit_yaml((self.cwd / 'showyourwork.yml')) as config:
config['optimize_caching'] = True
config['dependencies'] = {'src/tex/ms.tex': ['src/data/C.dat']}
with open((self.cwd ... |
.expansion
class ExpandReduceCUDADevice(pm.ExpandTransformation):
environments = [CUDA]
_SPECIAL_RTYPES = {dtypes.ReductionType.Min_Location: 'ArgMin', dtypes.ReductionType.Max_Location: 'ArgMax'}
def expansion(node: 'Reduce', state: SDFGState, sdfg: SDFG):
from dace.codegen.prettycode import CodeIO... |
def get_xy_fd():
feature_columns = [SparseFeat('user', 3, embedding_dim=8), SparseFeat('gender', 2, embedding_dim=8), SparseFeat('item', (3 + 1), embedding_dim=8), SparseFeat('item_gender', (2 + 1), embedding_dim=8), DenseFeat('score', 1)]
feature_columns += [VarLenSparseFeat(SparseFeat('hist_item', (3 + 1), em... |
(IcmpInst, BaseSMTEncoder)
def _icmp(term, smt):
x = smt.eval(term.x)
y = smt.eval(term.y)
cmp = smt._icmp_ops[term.pred](x, y)
return bool_to_BitVec(cmp) |
def execute_predicted_sparql(sparql):
sparql = sparql.replace('wdt:instance_of/wdt:subclass_of', 'wdt:P31/wdt:P279')
url = '
extracted_property_names = [x[1] for x in re.findall('(wdt:|p:|ps:|pq:)([a-zA-Z_\\(\\)(\\/_)]+)(?![1-9])', sparql)]
pid_replacements = {}
for replaced_property_name in extract... |
def test(model):
datasets = {'DAVIS16_val': TestDAVIS('../DB/DAVIS', '2016', 'val'), 'DAVIS17_val': TestDAVIS('../DB/DAVIS', '2017', 'val'), 'DAVIS17_test-dev': TestDAVIS('../DB/DAVIS', '2017', 'test-dev')}
for (key, dataset) in datasets.items():
evaluator = evaluation.Evaluator(dataset)
evaluat... |
def test(task, task_dir, evaluator, run_name, num_test_samples, out_dir):
def write_log(f, res_dict):
try:
json.dump(res_dict, f)
except:
json.dump(res_dict['crashed'], f)
f.write('\n')
f.flush()
os.makedirs(out_dir, exist_ok=True)
test_examples_file =... |
_grad()
def full_test(model, loader):
model.eval()
total_correct = total_examples = 0
for batch in loader:
batch = batch.to(device)
(out, _) = model(batch.x, batch.adj_t)
total_correct += int((out.argmax(dim=(- 1)) == batch.y).sum())
total_examples += out.size(0)
return (... |
def write_version_py(source_root, filename='scipy/version.py'):
cnt = "# THIS FILE IS GENERATED DURING THE SCIPY BUILD\n# See tools/version_utils.py for details\n\nshort_version = '%(version)s'\nversion = '%(version)s'\nfull_version = '%(full_version)s'\ngit_revision = '%(git_revision)s'\ncommit_count = '%(commit_c... |
def weights_init_embedding(m, init_cfg):
classname = m.__class__.__name__
if (classname.find('AdaptiveEmbedding') != (- 1)):
if hasattr(m, 'emb_projs'):
for i in range(len(m.emb_projs)):
if (m.emb_projs[i] is not None):
nn.init.normal_(m.emb_projs[i], 0.0,... |
def _split_tensor_list_constants(g, block):
for node in block.nodes():
for subblock in node.blocks():
_split_tensor_list_constants(g, subblock)
if _is_constant_tensor_list(node):
inputs = []
for val in node.output().toIValue():
input = g.insertCons... |
def for_search(state, outcome):
if (state == 'error'):
return {'error': True}
if (state == 'ok'):
loss = outcome['loss']
var = outcome.get('var', None)
return {'loss': loss, 'var': var} |
def create_lr_schedule(base_lr, decay_type, total_steps, decay_rate=0.1, decay_steps=0, warmup_steps=0, power=1.0, min_lr=1e-05):
def step_fn(step):
lr = base_lr
step_mwu = jnp.maximum(0.0, (step - warmup_steps))
step_pct = jnp.clip((step_mwu / float((total_steps - warmup_steps))), 0.0, 1.0)... |
class TestVisualization(unittest.TestCase):
def test_undirected(self):
graph = karate_club(True)
adjacency = graph.adjacency
position = graph.position
labels = graph.labels
image = svg_graph(adjacency, position, labels=labels)
self.assertEqual(image[1:4], 'svg')
... |
def build_vocab(examples):
vocab = {}
def add_to_vocab(word_list):
for word in word_list:
if (word not in vocab):
vocab[word] = len(vocab)
for i in range(len(examples)):
add_to_vocab(examples[i].word_list_a)
if examples[i].text_b:
add_to_vocab(... |
def dataclass_to_box(dataclass, trace, name_suffix=None, skip_args=None):
flattened = dataclasses.astuple(dataclass)
names = [field.name for field in dataclasses.fields(dataclass)]
suffix = (f'_{name_suffix}' if name_suffix else '')
(replacements, node_map) = ({}, {})
for (name, value) in zip(names,... |
def set_model(opt):
model = FairSupConResNet(name=opt.model)
criterion = torch.nn.CrossEntropyLoss()
classifier = LinearClassifier(name=opt.model, num_classes=opt.ta_cls)
ckpt = torch.load(opt.ckpt, map_location='cpu')
state_dict = ckpt['model']
if torch.cuda.is_available():
if (torch.cu... |
class TestPointEnv():
def test_pickleable(self):
env = PointEnv()
round_trip = pickle.loads(pickle.dumps(env))
assert round_trip
step_env(round_trip)
env.close()
round_trip.close()
def test_does_not_modify_action(self):
env = PointEnv()
a = env.act... |
def _yes_schema(source, line_delimited, schema, nan_string, posinf_string, neginf_string, complex_record_fields, buffersize, initial, resize, highlevel, behavior, attrs):
if isinstance(schema, (bytes, str)):
schema = json.loads(schema)
if (not isinstance(schema, dict)):
raise TypeError(f'unrecog... |
def exec_bfs(G, workers, calcUntilLayer):
futures = {}
degreeList = {}
t0 = time()
vertices = G.keys()
parts = workers
chunks = partition(vertices, parts)
with ProcessPoolExecutor(max_workers=workers) as executor:
part = 1
for c in chunks:
job = executor.submit(ge... |
def generate(url):
parts = ['"""\n\n webencodings.labels\n \n\n Map encoding labels to their name.\n\n :copyright: Copyright 2012 by Simon Sapin\n :license: BSD, see LICENSE for details.\n\n"""\n\n# XXX Do not edit!\n# This file is automatically generated by mklabels.py\n\nLABELS = {\n']
labels =... |
_function_dispatch(_rec_append_fields_dispatcher)
def rec_append_fields(base, names, data, dtypes=None):
return append_fields(base, names, data=data, dtypes=dtypes, asrecarray=True, usemask=False) |
class HigherThresholdNearestNeighborBuffer(object):
def __init__(self, buffer_size, tolerance=2):
self.buffer_size = buffer_size
self.tolerance = tolerance
self.exempted_queue = []
self.seen_queue = {}
def reset(self):
self.exempted_queue = []
self.seen_queue = {}... |
def test_hdf5maker():
preprocessor(mseed_dir='downloads_mseeds', stations_json='station_list.json', overlap=0.3, n_processor=2)
dir_list = [ev for ev in os.listdir('.') if (ev.split('_')[(- 1)] == 'hdfs')]
assert (dir_list[0] == 'downloads_mseeds_processed_hdfs') |
class DummyModule(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
self.layer = torch.nn.Linear(in_features=32, out_features=2)
self.another_layer = torch.nn.Linear(in_features=2, out_features=2)
def forward(self, x: torch.Tensor) -> torch.Tensor:
x = self.layer(x... |
class PlyProperty(object):
def __init__(self, name, val_dtype):
self._name = str(name)
self._check_name()
self.val_dtype = val_dtype
def _get_val_dtype(self):
return self._val_dtype
def _set_val_dtype(self, val_dtype):
self._val_dtype = _data_types[_lookup_type(val_dt... |
def open_spinner(message):
if (sys.stdout.isatty() and (logger.getEffectiveLevel() <= logging.INFO)):
spinner = InteractiveSpinner(message)
else:
spinner = NonInteractiveSpinner(message)
try:
with hidden_cursor(sys.stdout):
(yield spinner)
except KeyboardInterrupt:
... |
def lr_func_step(cur_iter):
return (cfg.SOLVER.BASE_LR * (cfg.SOLVER.GAMMA ** (cur_iter // cfg.SOLVER.STEP_SIZE))) |
def _read_item(item, scaler=None, flip_indices=False):
label = item['class_label']
label = tf.cast(label, tf.int64)
del item['class_label']
features = list(item.values())
if flip_indices:
m_wbb = features[24]
m_wwbb = features[25]
features[24] = m_wwbb
features[25] = ... |
_grad()
def make_convolutional_sample(batch, model, mode='vanilla', custom_steps=None, eta=1.0, swap_mode=False, masked=False, invert_mask=True, quantize_x0=False, custom_schedule=None, decode_interval=1000, resize_enabled=False, custom_shape=None, temperature=1.0, noise_dropout=0.0, corrector=None, corrector_kwargs=No... |
_connect.numpy.implements('nanprod')
def _nep_18_impl_nanprod(a, axis=None, dtype=UNSUPPORTED, out=UNSUPPORTED, keepdims=False, initial=UNSUPPORTED, where=UNSUPPORTED):
return nanprod(a, axis=axis, keepdims=keepdims) |
def register_functions(root_module):
module = root_module
module.add_function('Abs', 'ns3::Time', [param('ns3::Time const &', 'time')])
module.add_function('Abs', 'ns3::int64x64_t', [param('ns3::int64x64_t const &', 'value')])
module.add_function('BreakpointFallback', 'void', [])
module.add_function... |
def format_prompt_with_data_frame(df: pd.DataFrame, prompt_dict: dict, df_postprocessor: Optional[Callable]=None, return_dict=False):
if (df_postprocessor is not None):
df = df_postprocessor(df)
list_dict_data = df.to_dict(orient='records')
prompts = [format_prompt(example, prompt_dict) for example ... |
def __dtype_from_pep3118(stream, is_subdtype):
field_spec = dict(names=[], formats=[], offsets=[], itemsize=0)
offset = 0
common_alignment = 1
is_padding = False
while stream:
value = None
if stream.consume('}'):
break
shape = None
if stream.consume('('):
... |
def get_cifar_anomaly_dataset(trn_img, trn_lbl, tst_img, tst_lbl, abn_cls_idx=0, manualseed=(- 1)):
trn_lbl = np.array(trn_lbl)
tst_lbl = np.array(tst_lbl)
nrm_trn_idx = np.where((trn_lbl != abn_cls_idx))[0]
abn_trn_idx = np.where((trn_lbl == abn_cls_idx))[0]
nrm_trn_img = trn_img[nrm_trn_idx]
a... |
def read_hf_webdataset(url: str, multimodal_cfg: Dict[(str, Any)], tokenizer, is_train: bool, rsample_frac=None):
urls = expand_url_to_file_list(url)
if is_train:
urls = repeat_shards(urls)
assert urls[0].endswith('.tar')
dataset = IterableDataset.from_generator(gen_from_webdataset_shards, gen_k... |
def sentence_similarity(question):
model = sent2vec.Sent2vecModel()
model.load_model('torontobooks_unigrams.bin')
a = [e[0] for e in model.embed_sentence(question).reshape((- 1), 1)]
data = np.load('data.npy').item()
similar_dic = {}
for (k, v) in data.iteritems():
b = [e[0] for e in mod... |
def get_argparser():
parser = argparse.ArgumentParser()
parser.add_argument('--data_root', type=str, default='./datasets/data', help='path to Dataset')
parser.add_argument('--dataset', type=str, default='voc', choices=['lvis', 'voc', 'cityscapes', 'ade20k', 'coco'], help='Name of dataset')
parser.add_ar... |
class _freq_encoder(Function):
_fwd(cast_inputs=torch.float32)
def forward(ctx, inputs, degree, output_dim):
if (not inputs.is_cuda):
inputs = inputs.cuda()
inputs = inputs.contiguous()
(B, input_dim) = inputs.shape
outputs = torch.empty(B, output_dim, dtype=inputs.dt... |
def _test_mpi(info, sdfg, dtype):
from mpi4py import MPI as MPI4PY
comm = MPI4PY.COMM_WORLD
rank = comm.Get_rank()
commsize = comm.Get_size()
mpi_sdfg = None
if (commsize < 2):
raise ValueError('This test is supposed to be run with at least two processes!')
for r in range(0, commsize... |
def register_Ns3CsParamVectorTlvValue_methods(root_module, cls):
cls.add_constructor([param('ns3::CsParamVectorTlvValue const &', 'arg0')])
cls.add_constructor([])
cls.add_method('Copy', 'ns3::CsParamVectorTlvValue *', [], is_const=True, is_virtual=True)
cls.add_method('Deserialize', 'uint32_t', [param(... |
def cauchy_conj_components_lazy(v, z, w, type=1):
(v, z, w) = _broadcast_dims(v, z, w)
(v_r, v_i) = (v.real.contiguous(), v.imag.contiguous())
(w_r, w_i) = (w.real.contiguous(), w.imag.contiguous())
z_i = z.imag.contiguous()
v_r = LazyTensor(rearrange(v_r, '... N -> ... 1 N 1'))
v_i = LazyTensor... |
def combine_paths(*args, **kws):
r = []
for a in args:
if (not a):
continue
if is_string(a):
a = [a]
r.append(a)
args = r
if (not args):
return []
if (len(args) == 1):
result = reduce((lambda a, b: (a + b)), map(glob, args[0]), [])
... |
def makestr(node):
if isinstance(node, ast.AST):
n = 0
nodename = typename(node)
s = ('(' + nodename)
for (chname, chval) in ast.iter_fields(node):
chstr = makestr(chval)
if chstr:
s += ((((' (' + chname) + ' ') + chstr) + ')')
... |
def rank_eval(gt_items, pred_items):
(R1, R5, R10, mAP10, med_rank) = ([], [], [], [], [])
for (i, cap) in enumerate(gt_items):
gt_fname = gt_items[cap]
pred_fnames = pred_items[cap]
preds = np.asarray([(gt_fname == pred) for pred in pred_fnames])
rank_value = min([idx for (idx, ... |
def save_results(args, sentences, predictions, idx2label, queries_text):
correct = defaultdict(list)
example2pred = {}
for (i, (sentence, pred)) in enumerate(zip(sentences, predictions)):
text = sentence['text']
gold = sentence['gold']
gold = int(gold)
pred = int(pred)
... |
def create_unique_name(name, list_names):
result = name
while (result in list_names):
result += '_'
return result |
def _upgrade_greater_than(old_constraint):
scalar = old_constraint.get('scalar')
high = old_constraint.get('high')
low = old_constraint.get('low')
high_is_string = isinstance(high, str)
low_is_string = isinstance(low, str)
strict = old_constraint.get('strict', False)
new_constraints = []
... |
class AutoModelForSequenceClassification(object):
def __init__(self):
raise EnvironmentError('AutoModelForSequenceClassification is designed to be instantiated using the `AutoModelForSequenceClassification.from_pretrained(pretrained_model_name_or_path)` or `AutoModelForSequenceClassification.from_config(con... |
class st_gcn(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, device, stride=1, dropout=0.5, residual=True, batch_size=64):
super().__init__()
print('Dropout={}'.format(dropout))
assert (len(kernel_size) == 2)
assert ((kernel_size[0] % 2) == 1)
padding =... |
class Model(nn.Module):
def __init__(self, new_shape):
super(Model, self).__init__()
self.new_shape = new_shape
def forward(self, x):
return ((x + 1), (x + 2)) |
def test_order_by_generator(mock_database):
generator = OrderByGenerator(mock_database)
table_name = 'example_table'
generated_sql = generator.sql_generate(table_name)
assert ('ORDERBY-SINGLE' in generated_sql['sql_tags'])
assert (len(generated_sql['queries']) == 6)
query = f'SELECT * FROM "{tab... |
def get_all_model_names():
model_names = set()
for module_name in ['modeling_auto', 'modeling_tf_auto', 'modeling_flax_auto']:
module = getattr(transformers.models.auto, module_name, None)
if (module is None):
continue
mapping_names = [x for x in dir(module) if (x.endswith('_... |
class VizdoomEnvMultiplayer(VizdoomEnv):
def __init__(self, level, player_id, port, num_players, skip_frames, level_map='map01', bin_resolution=32):
super().__init__(level, skip_frames=skip_frames, level_map=level_map)
self.port = port
self.player_id = player_id
self.num_players = nu... |
def smart_tokenizer_and_embedding_resize(special_tokens_dict: Dict, tokenizer: transformers.PreTrainedTokenizer, model: transformers.PreTrainedModel):
num_new_tokens = tokenizer.add_special_tokens(special_tokens_dict)
model.resize_token_embeddings(len(tokenizer))
if (num_new_tokens > 0):
input_embed... |
class BasicBlockV2(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, is_first_block_of_first_layer=False, use_cbam=False):
super(BasicBlockV2, self).__init__()
self.is_first_block_of_first_layer = is_first_block_of_first_layer
if (not is_first_bloc... |
def merge_input_batches(input_batches: List[InputBatch], max_num_samples: Optional[int]=None) -> InputBatch:
final_input_batch = InputBatch()
for (key, val) in vars(input_batches[0]).items():
if (key != 'ray_indices'):
if (val is None):
setval = None
elif isinstan... |
def main():
p = optparse.OptionParser(usage=(__doc__ or '').strip())
(options, args) = p.parse_args()
if (len(args) != 0):
p.error('invalid number of arguments')
pwd = os.path.dirname(__file__)
src_files = (os.path.abspath(__file__), os.path.abspath(os.path.join(pwd, 'functions.json')), os.p... |
def test_sampler_init_gpu_when_not_available(esm6, mock_no_gpu):
pytest.raises(Exception, esm_sampler.ESM_sampler, esm6, device='gpu') |
def compute_derivedSF(shortAxis, longAxis, area, perimt, MinDiameter, MaxDiameter, hull_area, hull_perimtr):
esf = (shortAxis / longAxis)
csf = (((4 * np.pi) * area) / (perimt ** 2))
sf1 = (shortAxis / MaxDiameter)
sf2 = (MinDiameter / MaxDiameter)
elg = (MaxDiameter / MinDiameter)
cvx = np.sqrt... |
.parametrize('test_x, expected', [(tf.constant([[0.0, 0.0]]), tf.constant([[0., 0.]])), (tf.constant([[0.5, 1.0]]), tf.constant([[0., 0.9873655]])), (tf.constant([[[0.5, 1.0]], [[0.0, 0.0]]]), tf.constant([[[0., 0.9873655]], [[0., 0.]]])), (tf.constant([[[0.5, 1.0], [0.0, 0.0]]]), tf.constant([[[0., 0.9873655], [0., 0.... |
def average_precision(r):
r = (np.asarray(r) != 0)
out = [precision_at_k(r, (k + 1)) for k in range(r.size) if r[k]]
if (not out):
return 0.0
return np.mean(out) |
def _find_single_yield_expression(node):
yield_statements = _find_yield_statements(node)
if (len(yield_statements) != 1):
return (None, None)
return yield_statements[0] |
def create_train_model(model_creator, hparams, scope=None, num_workers=1, jobid=0, extra_args=None):
src_file = ('%s.%s' % (hparams.train_prefix, hparams.src))
tgt_file = ('%s.%s' % (hparams.train_prefix, hparams.tgt))
src_vocab_file = hparams.src_vocab_file
tgt_vocab_file = hparams.tgt_vocab_file
g... |
class LeftRegularBand(UniqueRepresentation, Parent):
def __init__(self, alphabet=('a', 'b', 'c', 'd')):
self.alphabet = alphabet
Parent.__init__(self, category=Semigroups().Finite().FinitelyGenerated())
def _repr_(self):
return ('An example of a finite semigroup: the left regular band ge... |
def get_evaluation_metrics(inputs, targets):
ssim = tf.reduce_sum(tf.image.ssim(inputs, targets, max_val=255))
psnr = tf.reduce_sum(tf.image.psnr(inputs, targets, max_val=255))
rmse = tf.reduce_sum(RMSE(inputs, targets))
return (ssim, psnr, rmse) |
def prewitt(image, mask=None, *, axis=None, mode='reflect', cval=0.0):
output = _generic_edge_filter(image, smooth_weights=PREWITT_SMOOTH, axis=axis, mode=mode, cval=cval)
output = _mask_filter_result(output, mask)
return output |
def test_deprecate_parameter():
with pytest.warns(FutureWarning, match='is deprecated from'):
deprecate_parameter(Sampler(), '0.2', 'a')
with pytest.warns(FutureWarning, match="Use 'b' instead."):
deprecate_parameter(Sampler(), '0.2', 'a', 'b') |
def update_preprocessing_parameters(args):
if (args.dataset_code == 'redd_lf'):
args.cutoff = {'aggregate': 6000, 'refrigerator': 400, 'washer_dryer': 3500, 'microwave': 1800, 'dishwasher': 1200}
args.threshold = {'refrigerator': 50, 'washer_dryer': 20, 'microwave': 200, 'dishwasher': 10}
ar... |
class RMTorch(MeshTorchLayer):
def __init__(self, units: int, num_layers: int=None, hadamard: bool=False, basis: str=DEFAULT_BASIS, bs_error: float=0.0, theta_init: Union[(str, tuple, np.ndarray)]='haar_rect', phi_init: Union[(str, tuple, np.ndarray)]='random_phi', gamma_init: Union[(str, tuple, np.ndarray)]='rando... |
def kernel_gaussian(x, ls, z=None):
if (z is None):
z = x
return np.exp(((- np.sum(((x - z) ** 2))) / (2 * (ls ** 2)))) |
def update_config():
import argparse, sys
parser = argparse.ArgumentParser(description='Classification model training')
parser.add_argument('--config_file', type=str, default=None, required=True, help='Optional config file for params')
parser.add_argument('--model', default='deit_base_patch16_224', type... |
def _select_rand_weights(weight_idx=0, transforms=None):
transforms = (transforms or _RAND_TRANSFORMS)
assert (weight_idx == 0)
rand_weights = _RAND_CHOICE_WEIGHTS_0
probs = [rand_weights[k] for k in transforms]
probs /= np.sum(probs)
return probs |
def Res50_Deeplab(num_classes=21):
model = ResNet(Bottleneck, [3, 4, 6, 3], num_classes)
return model |
def register_Ns3DefaultDeleter__Ns3EventImpl_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::DefaultDeleter< ns3::EventImpl > const &', 'arg0')])
cls.add_method('Delete', 'void', [param('ns3::EventImpl *', 'object')], is_static=True)
return |
def compute_clip_loss(img, text):
img = torch.nn.functional.upsample_bilinear(img, (224, 224))
tokenized_text = clip.tokenize([text]).to(device)
(img_logits, _text_logits) = clip_model(img, tokenized_text)
return ((1 / img_logits) * 100) |
def get_topic_summary_dict(topics):
words_and_weights = {}
for (num, data) in enumerate(topics):
words_and_weights[str((num + 1))] = {}
words_and_weights[str((num + 1))]['name'] = ''
words_and_weights[str((num + 1))]['words'] = data
return words_and_weights |
def maple(model, data):
return (lambda X: other.MapleExplainer(model.predict, data).attributions(X, multiply_by_input=False)) |
class TestActivationCheckpointing(unittest.TestCase):
def test_activation_checkpointing_does_not_change_metrics(self):
base_flags = ['--encoder-layers', '2', '--decoder-layers', '2', '--encoder-embed-dim', '8', '--decoder-embed-dim', '8', '--restore-file', 'x.pt', '--log-format', 'json', '--log-interval', '... |
def get_default_temp_dir():
tempfile.gettempdir()
return os.path.join(tempfile.tempdir, 'sepp') |
def test_optimize_freeze_check():
with goos.OptimizationPlan() as plan:
x = goos.Variable([1])
y = goos.Variable([1])
y.freeze()
obj = (((x + y) ** 2) + 3)
goos.opt.scipy_minimize(obj, method='L-BFGS-B')
plan.run()
assert (x.get().array == (- 1))
asser... |
class BertConfig(PretrainedConfig):
pretrained_config_archive_map = BERT_PRETRAINED_CONFIG_ARCHIVE_MAP
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_pos... |
class LuminosityInner(ProcessingPlasmaProperty):
outputs = ('luminosity_inner',)
def calculate(r_inner, t_inner):
return ((((4 * np.pi) * const.sigma_sb.cgs) * (r_inner[0] ** 2)) * (t_inner ** 4)).to('erg/s') |
class TaskProcessor(object):
def __init__(self, task: BaseTask, data_path: str, output_path: str, model_path: str, resample: str=None):
self.task: BaseTask = task
self.data_path: str = data_path
self.model_path = model_path
self.output_path = output_path
self.task_output_path... |
def eliminate_overlapping_entities(entities_list):
subsumed = set([])
for (sub_i, sub) in enumerate(entities_list):
for over in entities_list[:sub_i]:
if any([(target in over['targets']) for target in sub['targets']]):
subsumed.add(sub['ent_id'])
return [entity for entity... |
def test_streaming_mean():
m = batcher.StreamingMean()
values = list(range(10, 20))
for (i, value) in enumerate(values):
m.add(value)
assert (m.value == np.mean(values[:(i + 1)])) |
def encode_dataset(input_file, w_map, c_map):
with open(input_file, 'r') as f:
lines = f.readlines()
(line_idx, features) = read_corpus(lines)
(w_st, w_unk, w_con, w_pad) = (w_map['<s>'], w_map['<unk>'], w_map['< >'], w_map['<\n>'])
(c_st, c_unk, c_con, c_pad) = (c_map['<s>'], c_map['<unk>'], c_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.