code stringlengths 101 5.91M |
|---|
def main():
with tf.Session(config=TF_CONFIG) as sess:
gan = GAN(sess, MODEL_CONFIG)
gan.init_all()
refine_gan = RefineGAN(sess, MODEL_CONFIG, gan)
refine_gan.init_all()
refine_gan.load_latest('../checkpoints')
print('[*] Preparing data...')
z_sample = np.rand... |
def run_sample_decode(infer_model, infer_sess, model_dir, hparams, summary_writer, src_data, tgt_data, ckpt_index=None):
with infer_model.graph.as_default():
(loaded_infer_model, global_step) = model_helper.create_or_load_model(infer_model.model, model_dir, infer_sess, 'infer', ckpt_index)
_sample_decod... |
def prepare(params, samples):
(_, params.word2id) = create_dictionary(samples)
params.word_vec = get_wordvec(PATH_TO_VEC, params.word2id)
params.wvec_dim = 300
return |
def _ensure_hms(inner_result: ParsedDate, remain_tokens: List[str]) -> ParsedDate:
result = deepcopy(inner_result)
remain_str = remain_tokens[0]
hms_tokens = []
ispm = False
for token in AM:
if (token in remain_str):
hms_tokens = split(remain_str, AM)
break
for to... |
class MultiInheritanceEstimator(DontPickleAttributeMixin, BaseEstimator):
def __init__(self, attribute_pickled=5):
self.attribute_pickled = attribute_pickled
self._attribute_not_pickled = None |
.parametrize('use_inner, use_outter,sparse_feature_num', [(True, True, 3), (False, False, 1)])
def test_PNN(use_inner, use_outter, sparse_feature_num):
model_name = 'PNN'
sample_size = SAMPLE_SIZE
(x, y, feature_columns) = get_test_data(sample_size, sparse_feature_num=sparse_feature_num, dense_feature_num=s... |
def multi_perspective_expand_for_2D(in_tensor, decompose_params):
in_tensor = tf.expand_dims(in_tensor, axis=1)
decompose_params = tf.expand_dims(decompose_params, axis=0)
return tf.multiply(in_tensor, decompose_params) |
def adj_list_to_matrix(adj_list):
n = len(adj_list)
adj_matrix = np.zeros((n, n))
for (i, c) in enumerate(adj_list):
for (j, weight) in c:
adj_matrix[(i, j)] = weight
return adj_matrix |
class BaseInputExample(ABC):
words: List[str]
space_after: List[bool]
tree: Optional[nltk.Tree]
def leaves(self) -> Optional[List[str]]:
pass
def pos(self) -> Optional[List[Tuple[(str, str)]]]:
pass |
def test__sort_leaderboard_no_rank():
rank = None
metrics = METRICS
score = {k: range(5) for k in metrics.keys()}
score['pipeline'] = range(5)
score = pd.DataFrame(score)
expected_return = score.iloc[::(- 1)].reset_index(drop=True)
expected_return['rank'] = range(1, 6)
returned = benchma... |
_numpy_output(check_dtype=True)
def test_ufunc_nextafter_fd(A: dace.float32[10], B: dace.float64[10]):
return np.nextafter(A, B) |
(config_path=None, config_name='config')
def xpreprocess(cfg: PreprocessingConfig) -> None:
overwatch.info('Preprocessing :: Running Phases for Frame Extraction, Language Compilation, and Batching...')
set_global_seed(cfg.seed)
(train_registry, val_registry, train_dir, val_dir) = preprocess_videos(cfg.datas... |
def get_transforms(cfg):
train_transform = create_transform(input_size=cfg.DATA.CROP_SIZE, scale=(0.8, 1), is_training=True, color_jitter=0.4, auto_augment='rand-m9-mstd0.5-inc1', interpolation='bicubic', re_prob=0.25, re_mode='pixel', re_count=1)
test_transform = transforms.Compose([transforms.Resize((cfg.DATA... |
def filter_out_benchmarks(benchmark: str, deployment_name: str, language: str, language_version: str) -> bool:
if ((deployment_name == 'aws') and (language == 'python') and (language_version == '3.9')):
return ('411.image-recognition' not in benchmark)
return True |
class TestMakeTwoClass(test_util.TestCase):
def setUp(self):
self.test_configs = [(1,), (7,), (1, 3), (2, 5)]
def testMakeTwoClass(self):
for input_size in self.test_configs:
op = core.CreateOperator('MakeTwoClass', ['X'], ['Y'])
X = np.random.rand(*input_size).astype(np.... |
def main(args):
seed = args.seed
random = np.random.RandomState(seed)
n = args.number
path = args.file
format_ = args.format_
coords = file_utils.read_coordinates(path, format=format_)
image_names = []
groups = []
for (name, group) in coords.groupby('image_name'):
image_names... |
def get_mnist2_anomaly_dataset(trn_img, trn_lbl, tst_img, tst_lbl, nrm_cls_idx=0, proportion=0.5, manualseed=(- 1)):
if (manualseed != (- 1)):
torch.manual_seed(manualseed)
nrm_trn_idx = torch.from_numpy(np.where((trn_lbl.numpy() == nrm_cls_idx))[0])
abn_trn_idx = torch.from_numpy(np.where((trn_lbl.... |
def is_triangular(B) -> bool:
if isinstance(B, (list, tuple)):
G = B
else:
try:
G = B.gens()
except Exception:
raise TypeError('is_triangular wants as input an ideal, or a list of polynomials\n')
vars = G[0].parent().gens()
n = len(G)
for i in range(n)... |
def dirContainsTestSuite(path, lit_config):
cfgpath = os.path.join(path, lit_config.site_config_name)
if os.path.exists(cfgpath):
return cfgpath
cfgpath = os.path.join(path, lit_config.config_name)
if os.path.exists(cfgpath):
return cfgpath |
class SAP(nn.Module):
def __init__(self, out_dim):
super(SAP, self).__init__()
self.act_fn = nn.Tanh()
self.sap_layer = SelfAttentionPooling(out_dim)
def forward(self, feature, att_mask):
feature = self.act_fn(feature)
sap_vec = self.sap_layer(feature, att_mask)
r... |
_function()
def lf_regex_check_out(x):
return (SPAM if re.search('check.*out', x.text, flags=re.I) else ABSTAIN) |
def register_Ns3CsmaChannel_methods(root_module, cls):
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_constructor([])
cls.add_method('Attach', 'int32_t', [param('ns3::Ptr< ns3::CsmaNetDevice >', 'device')])
cls.add_method('Detach', 'bool', [param('ns3::Ptr< ns3::CsmaNetDevice >',... |
def get_c_function_param(x: Field):
is_dyn_array = (x.count and (not isinstance(x.count, int)))
name = _T(x.name)
if (is_dyn_array or x.by_ref):
return f'[MarshalAs(UnmanagedType.LPArray)] {get_type_name(x.type)}[] {name}'
elif x.by_mut:
return f'[MarshalAs(UnmanagedType.LPArray)] [In, O... |
class StandardSymplecticSpace(EuclideanSpace):
_symplectic_form: SymplecticForm
def __init__(self, dimension: int, name: Optional[str]=None, latex_name: Optional[str]=None, coordinates: str='Cartesian', symbols: Optional[str]=None, symplectic_name: Optional[str]='omega', symplectic_latex_name: Optional[str]=Non... |
def TD_product(k, TD1, n1, TD2, n2, check=True):
N = (n1 * n2)
TD = []
for X1 in TD1:
for X2 in TD2:
TD.append([((x1 * n2) + (x2 % n2)) for (x1, x2) in zip(X1, X2)])
if check:
assert is_transversal_design(TD, k, N)
return TD |
def probs(model, hyper, data, target):
(s_log_pw, s_log_qw, s_log_likelihood) = (0.0, 0.0, 0.0)
for _ in range(hyper.n_samples):
output = torch.log(model(data))
(sample_log_pw, sample_log_qw) = model.get_lpw_lqw()
sample_log_likelihood = ((- F.nll_loss(output, target, reduction='sum')) *... |
def _is_int_value(value, target_value: int) -> bool:
if isinstance(value, numbers.Integral):
return (value == target_value)
if ((len(value.free_symbols) > 0) or (int(value) != target_value)):
return False
return True |
.parametrize('sparse_feature_num,dense_feature_num', [(2, 0), (0, 2), (2, 2)])
def test_WDL(sparse_feature_num, dense_feature_num):
model_name = 'WDL'
sample_size = SAMPLE_SIZE
(x, y, feature_columns) = get_test_data(sample_size, sparse_feature_num=sparse_feature_num, dense_feature_num=dense_feature_num)
... |
def spinning_up_ddpg_config():
config = spinning_up_td3_config()
config.target_network_update_freq = 1
config.activ = 'relu'
return config |
def revert_sync_batchnorm(module):
module_output = module
if isinstance(module, torch.nn.modules.batchnorm.SyncBatchNorm):
new_cls = BatchNormXd
module_output = BatchNormXd(module.num_features, module.eps, module.momentum, module.affine, module.track_running_stats)
if module.affine:
... |
def get_total_page(html):
try:
page_count = json.loads(html, encoding='utf-8').get('data', '').get('page', '').get('totalpage', 1)
except Exception as e:
parser.error('Errors occurred when parsing total page of repost,specification is {}'.format(e))
page_count = 1
return page_count |
def test_rpad_recordarray():
keys = ['x', 'y']
offsets = ak.index.Index64(np.asarray([0, 0, 1, 3]))
content = ak.contents.numpyarray.NumpyArray(np.asarray([1.1, 2.2, 2.2]))
content1 = ak.contents.listoffsetarray.ListOffsetArray(offsets, content)
offsets = ak.index.Index64(np.asarray([0, 2, 3, 3]))
... |
def test_synthetic_sample_results_in_sampled_delay_when_delay_function_is_given():
n_actions = 3
delay_function = ExponentialDelaySampler(max_scale=100.0, random_state=12345).exponential_delay_function
dataset = BanditEnvironmentSimulator(n_actions=n_actions, reward_function=logistic_sparse_reward_function,... |
def O7():
A = Matrix(GF(3), [[1, 0, 0, 1, 1, 1, 1], [0, 1, 0, 0, 1, 2, 2], [0, 0, 1, 1, 0, 1, 0]])
M = TernaryMatroid(A, 'abcdefg')
M.rename(('O7: ' + repr(M)))
return M |
.overload_method(TupleType, 'content')
def Tuple_content(builder, index):
if (isinstance(builder, TupleType) and isinstance(index, numba.types.Integer)):
def getter(builder, index):
content = builder._contents[numba.literally(index)]
return content
return getter |
def norm(edge_index, num_nodes, edge_weight=None, improved=False, dtype=None):
if (edge_weight is None):
edge_weight = torch.ones((edge_index.size(1),), dtype=dtype, device=edge_index.device)
fill_value = (1.0 if (not improved) else 2.0)
(edge_index, edge_weight) = add_remaining_self_loops(edge_inde... |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--data-root', help='data root for both image file and anno file')
parser.add_argument('--in-path', help='mapping file of image_name and ann_file, "image_name ann_file" in each line')
parser.add_argument('--out-path', help='output ... |
def _bytes_feature(value):
if (value is None):
value = []
if (six.PY3 and isinstance(value, six.text_type)):
value = six.binary_type(value, encoding='utf-8')
if isinstance(value, np.ndarray):
value = value.reshape((- 1))
value = bytes(value)
if (not isinstance(value, list... |
def Pooling_ansatz1(params, wires):
qml.CRZ(params[0], wires=[wires[0], wires[1]])
qml.PauliX(wires=wires[0])
qml.CRX(params[1], wires=[wires[0], wires[1]]) |
def get_unified_clusters(clusters, to_unify):
def to_set(v, s):
if (not isinstance(v, list)):
s.add(v)
return
for x in v:
to_set(x, s)
(A, B) = (set(), set())
to_set(clusters, A)
new_clusters = []
for (c_i, cluster) in enumerate(clusters):
... |
_utils.test(arch=ti.cpu)
def test_vector_to_list():
a = ti.Vector.field(2, float, ())
data = [2, 3]
b = ti.Vector(data)
assert (list(b) == data)
assert (len(b) == len(data))
a[None] = b
assert all((a[None] == ti.Vector(data))) |
class UploadCommand(BaseUserCommand):
def walk_dir(self, rel_path):
entries: List[os.DirEntry] = list(os.scandir(rel_path))
files = [(os.path.join(os.getcwd(), f.path), f.path) for f in entries if f.is_file()]
for f in entries:
if f.is_dir():
files += self.walk_di... |
def main():
graph = graph_loader(graph_type='ky2', seed=1)
params = {'runs': 1, 'steps': 30, 'seed': 1, 'attack': 'rb_node', 'attack_approx': int((0.1 * len(graph))), 'plot_transition': True, 'gif_animation': True, 'gif_snaps': True, 'edge_style': None, 'node_style': None, 'fa_iter': 20}
print('Creating exa... |
def main(args):
config = load_config(args.config)
logger.info('config: {}'.format(json.dumps(config)))
set_seed((args.seed or config['seed']))
(model_ori, checkpoint, epoch, best) = prepare_model(args, logger, config)
logger.info('Model structure: \n {}'.format(str(model_ori)))
custom_ops = {}
... |
def preprocess_assumptions(args):
args = list(args)
last = None
for (i, x) in reversed(list(enumerate(args))):
if isinstance(x, str):
del args[i]
last = x
elif (((not hasattr(x, 'assume')) or (isinstance(x, Expression) and x.is_symbol())) and (last is not None)):
... |
def getEdgesAndLabels(docs_dir, models_dir, comparator):
edges = []
labels = []
docs_edges = _getEdgesIter(docs_dir, comparator)
models_edges = _getEdgesIter(models_dir, comparator)
for topic in docs_edges:
curr_docs_edges = set(docs_edges[topic])
curr_models_edges = set(models_edges... |
class WideAndDeepModel(tf.keras.Model):
def __init__(self, data, num_users, num_items, embedding_size, mlp_hidden_size, dropout_prob, lr, l_w, l_b, name='WideAndDeepModel', **kwargs):
super().__init__(name=name, **kwargs)
self._data = data
self._num_users = num_users
self._num_items ... |
def pytorch_to_onnx(onnx_filename, model, input_example):
if (not os.path.exists(onnx_filename)):
torch.onnx.export(model, input_example, onnx_filename) |
class ModelType(ExplicitEnum):
LayoutLM = 'layoutlm'
LayoutLMv2andv3 = 'layoutlmv2andv3'
VisionEncoderDecoder = 'vision_encoder_decoder' |
def main(args):
if (args.modelpath is None):
savepath = f'./inferences/defaultsd/{args.dataset}/{args.capstyle}'
else:
mp = os.path.basename(os.path.normpath(args.modelpath))
if ('traintext' not in args.modelpath):
if ('imagenette' in args.modelpath):
args.dat... |
def vis_faces(log_hooks):
display_count = len(log_hooks)
fig = plt.figure(figsize=(8, (4 * display_count)))
gs = fig.add_gridspec(display_count, 3)
for i in range(display_count):
hooks_dict = log_hooks[i]
fig.add_subplot(gs[(i, 0)])
if ('diff_input' in hooks_dict):
vi... |
def main(unused_argv):
if (FLAGS.hint_mode == 'encoded_decoded'):
encode_hints = True
decode_hints = True
elif (FLAGS.hint_mode == 'decoded_only'):
encode_hints = False
decode_hints = True
elif (FLAGS.hint_mode == 'none'):
encode_hints = False
decode_hints = F... |
def parse_text_to_table(text, strict=False):
text = text.replace(' <NEWLINE> ', '\n').strip()
data = []
for line in text.splitlines():
line = line.strip()
if (not line.startswith(SEP)):
line = (SEP + line)
if (not line.endswith(SEP)):
line = (line + SEP)
... |
class AddBenchmark(op_bench.TorchBenchmarkBase):
def init(self, M, N, K, device):
self.input_one = torch.rand(M, N, K, device=device, requires_grad=True)
self.input_two = torch.rand(M, N, K, device=device, requires_grad=True)
self.set_module_name('add')
def forward(self):
return ... |
def create_batches(data_size, batch_size, shuffle=True):
batches = []
ids = list(range(data_size))
if shuffle:
random.shuffle(ids)
for i in range(int((data_size / batch_size))):
start = (i * batch_size)
end = ((i + 1) * batch_size)
batches.append(ids[start:end])
rest ... |
class GridEncoder(nn.Module):
def __init__(self, input_dim=3, num_levels=16, level_dim=2, per_level_scale=2, base_resolution=16, log2_hashmap_size=19, desired_resolution=None, gridtype='hash', align_corners=False, interpolation='linear'):
super().__init__()
if (desired_resolution is not None):
... |
def train_one_epoch(model: torch.nn.Module, model_ema, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, mixup_fn: Optional[Mixup]=None, log_writer=None, args=None):
model.train(True)
metric_logger = misc.Metric... |
def init_tf(config_dict: dict=None) -> None:
if (tf.compat.v1.get_default_session() is not None):
return
cfg = _sanitize_tf_config(config_dict)
np_random_seed = cfg['rnd.np_random_seed']
if (np_random_seed is not None):
np.random.seed(np_random_seed)
tf_random_seed = cfg['rnd.tf_rand... |
def print_options(args, model):
message = ''
num_params = sum((p.numel() for p in model.parameters() if p.requires_grad))
num_params = (num_params / 1000000)
message += (' FL train of %s with total model parameters: %2.1fM \n' % (args.model, num_params))
message += ' Other Train related parameters ... |
.spark
.parametrize('sample, seed', [(False, None), (True, None), (True, 123)], ids=['no_sampling', 'sample_not_fixed', 'sample_fixed'])
def test_predict(fitted_model, log_ucb, sample, seed):
fitted_model.seed = seed
fitted_model.sample = sample
equality_check = (sparkDataFrameNotEqual if (fitted_model.samp... |
('split-video', add_help_option=False)
('--output', '-o', metavar='DIR', type=click.Path(exists=False, dir_okay=True, writable=True, resolve_path=False), help='Output directory to save videos to. Overrides global option -o/--output if set.')
('--filename', '-f', metavar='NAME', default='$VIDEO_NAME-Scene-$SCENE_NUMBER'... |
class GTestParamTestInvalidName2Test(gtest_test_utils.TestCase):
def testExitCodeAndOutput(self):
TestExitCodeAndOutput(COMMAND) |
class CopyInfo():
def __init__(self, src_addr, dst_addr, dir, size, begin_usec, end_usec, info=''):
self.src_addr = src_addr
self.dst_addr = dst_addr
self.dir = dir
self.size = size
self.begin_usec = begin_usec
self.end_usec = end_usec
self.info = info |
class FP16_Module(nn.Module):
def __init__(self, module):
super(FP16_Module, self).__init__()
self.add_module('module', module.half())
def forward(self, *inputs, **kwargs):
return fp16_to_fp32(self.module(*fp32_to_fp16(inputs), **kwargs))
def state_dict(self, destination=None, prefix... |
def make_optimizer_and_schedule(args, model, checkpoint, lr, step_lr):
optimizer = Adam(model.parameters(), lr)
schedule = None
if step_lr:
schedule = lr_scheduler.StepLR(optimizer, step_size=step_lr)
elif args.custom_schedule:
cs = args.custom_schedule
periods = (eval(cs) if (ty... |
def change_vector_label(row_index, att_data, solutions_found, changed_variables, variables):
original_vector = att_data.copy()
changes = 0
found_solution = 0
(_, error, temp) = scale_input_and_detect_single(row_index, att_data)
previous_best_error = error[row_index]
temp = sort_temp_and_drop(row... |
.parametrize('n_attacks, n_success, n_baseline, n_control, confidence_level, expected_rate, expected_baseline', [(100, 100, 0, None, 0.95, SuccessRate(value=0., error=0.), SuccessRate(value=0., error=0.)), (100, 100, 0, None, 0.68, SuccessRate(value=0., error=0.), SuccessRate(value=0., error=0.)), (100, 23, 11, None, 0... |
def register_Ns3ConstantPositionMobilityModel_methods(root_module, cls):
cls.add_constructor([param('ns3::ConstantPositionMobilityModel const &', 'arg0')])
cls.add_constructor([])
cls.add_method('GetTypeId', 'ns3::TypeId', [], is_static=True)
cls.add_method('DoGetPosition', 'ns3::Vector', [], is_const=T... |
def format_list(List, interval='\t', decimals=None):
if (decimals is None):
return interval.join(['{0}'.format(element) for element in List])
else:
return interval.join(['{0:.{1}f}'.format(element, decimals) for element in List]) |
def _print_metrics(stage, step, metrics, throttle=None):
for (k, v) in metrics.items():
print((' %s:' % k), v) |
def my_attention(inputs, merge_size=0, attention=True, attention_size=256, sep_attend=True, return_alphas=True, hidden_nl=0):
(W_projs, B_projs, hiddens) = ([], [], [])
(W_omegas, b_omegas, u_omegas) = ([], [], [])
inds = {}
for (i, x) in enumerate(inputs):
inds[i] = i
(w, b, u) = init_a... |
class OneTypeList(list):
def __init__(self, item_class, seq=None):
self.item_class = item_class
if (seq is not None):
for obj in seq:
self.append(obj)
def __setitem__(self, key, value):
if (type(value) in (list, tuple)):
for (ii, val) in enumerate(... |
def main():
tf_summary_writer = tf.summary.create_file_writer(args.checkpoint_dir)
train_data = Batch_generator(args.num_answer, args.img_dir, args.box_dir, args.anno_dir, args.prep_dir, 'train')
val_data = Batch_generator(args.num_answer, args.img_dir, args.box_dir, args.anno_dir, args.prep_dir, 'val')
... |
def test_plan_heavy(tmp_path):
plan_dir = (tmp_path / 'test_plan')
plan_dir.mkdir()
with goos.OptimizationPlan() as plan:
x = goos.Variable(3.0, name='x')
y = goos.Variable(2.0, name='y')
z = (x + y)
z.parallelize()
assert (z.get() == 5)
assert (z.get_grad([x,... |
def plot_value_functions():
for exp in EXPS:
save_dir = os.path.join('pdf_plots', 'value_functions')
if (not os.path.exists(save_dir)):
os.makedirs(save_dir, exist_ok=True)
true_value_function = np.load(os.path.join(os.getcwd(), 'Resources', TASK, 'state_values.npy'))
for... |
def match_patts(file_path, file_patterns, src, tgt, lang):
for file_pattern in file_patterns:
params = {k: v for (k, v) in [('src', src), ('tgt', tgt), ('lang', lang)] if (k in file_pattern)}
matching = file_pattern.format(**params)
if isinstance(file_pattern, tuple):
(pattern, d... |
def generate(output_dir: Path, config: codegen.CodegenConfig=None) -> None:
factors_dir = (output_dir / 'factors')
if (config is None):
config = codegen.CppConfig()
cam_types = sf.CameraCal.__subclasses__()
codegen.Codegen.function(func=inverse_range_landmark_prior_residual, config=config).with_... |
.parametrize('sampling', ['x', 'on_manifold', 'cd'])
def test_nae(sampling):
encoder = FCNet(2, 1)
decoder = FCNet(1, 2)
nae = NAE(encoder, decoder, initial_dist='gaussian', sampling=sampling)
opt = Adam(nae.parameters(), lr=0.0001)
X = torch.randn((10, 2), dtype=torch.float)
lik = nae.predict(X... |
def test_tokenizer():
if True:
sql = 'SELECT avg(age) FROM Student WHERE StuID IN ( SELECT T1.StuID FROM Has_allergy AS T1 JOIN Allergy_Type AS T2 ON T1.Allergy = T2.Allergy WHERE T2.allergytype = "food" INTERSECT SELECT T1.StuID FROM Has_allergy AS T1 JOIN Allergy_Type AS T2 ON T1.Allergy = T2.Allerg... |
def test_mpc_warm_start(solver, warm_start):
mpc_solver = get_solver(solver, warm_start, 1, 'mean')
agent = MPCAgent(mpc_solver=mpc_solver)
evaluate_agent(agent, environment=env, num_episodes=1, max_steps=MAX_ITER, render=False) |
def _recall_micro_1d(y_true: np.ndarray, y_pred: np.ndarray):
sum_intersection = 0
sum_prediction_and_ancestors = 0
for (ground_truth, prediction) in zip(y_true, y_pred):
ground_truth_set = set([ground_truth])
ground_truth_set.discard('')
predicted_set = set([prediction])
pre... |
class Cascading(Simulation):
def __init__(self, graph, runs=10, steps=100, l=0.8, r=0.2, **kwargs):
super().__init__(graph, runs, steps, **kwargs)
self.prm.update({'l': l, 'r': r, 'c': len(graph), 'robust_measure': 'largest_connected_component', 'k_a': 10, 'attack': 'id_node', 'attack_approx': None,... |
def import_class_from_path(class_path):
(module_path, class_name) = class_path.split(':')
module = importlib.import_module(module_path)
return getattr(module, class_name) |
def _SQS14():
return [[0, 1, 2, 5], [0, 1, 3, 6], [0, 1, 4, 13], [0, 1, 7, 10], [0, 1, 8, 9], [0, 1, 11, 12], [0, 2, 3, 4], [0, 2, 6, 12], [0, 2, 7, 9], [0, 2, 8, 11], [0, 2, 10, 13], [0, 3, 5, 13], [0, 3, 7, 11], [0, 3, 8, 10], [0, 3, 9, 12], [0, 4, 5, 9], [0, 4, 6, 11], [0, 4, 7, 8], [0, 4, 10, 12], [0, 5, 6, 8],... |
def get_signal_correlations(model, dataloaders, tier, device='cpu', as_dict=False, per_neuron=True):
correlations = {}
for (data_key, dataloader) in dataloaders[tier].items():
(trial_indices, image_ids, neuron_ids, responses) = get_data_filetree_loader(dataloader=dataloader, tier=tier)
(_, predi... |
def main(args):
cfg = get_default_cfg()
if args.cfg_file:
cfg.merge_from_file(args.cfg_file)
cfg.merge_from_list(args.opts)
cfg.freeze()
device = torch.device(cfg.DEVICE)
if (cfg.SEED >= 0):
set_random_seed(cfg.SEED)
print('Creating model')
model = SeqNet(cfg)
model.t... |
class RandomSampler(_BasicSampler):
def __init__(self, dataset, params, is_training=True, seed=0, return_index=False):
self.num_points_per_sample = 0
self.modify_type = None
super(RandomSampler, self).__init__(*[dataset, params, is_training])
self.center = np.array([((self.dataset.ma... |
def create_backbone(args, device):
model = vits.__dict__['vit_base']()
state_dict = torch.load(args.dino_pretrain_path, map_location='cpu')
model.load_state_dict(state_dict)
if (args.warmup_model_dir is not None):
print(f'Loading weights from {args.warmup_model_dir}')
model.load_state_di... |
class TIntFltH(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
HashPrimes = _snap.TIntFltH_HashPrimes
def __init__(self, *args):
_snap.TIntFltH_swiginit(self, _snap.new_TIntFltH(*args))
def Load(self, ... |
def train(model, optimizer, train_loader, criterion, entropy_loss_func, opts):
y_probs = np.zeros((0, len(train_loader.dataset.CLASSES)), np.float)
y_trues = np.zeros(0, np.int)
losses = []
model.train()
for (i, (x_low, x_high, label)) in enumerate(tqdm(train_loader)):
(x_low, x_high, label)... |
class TunableMixin():
def _tunables(cls) -> list[Any]:
_tunables = []
for attr_key in dir(cls):
if (attr_key == '_tunables'):
continue
attr = getattr(cls, attr_key)
if (hasattr(attr, '_tunables') or isfunction(attr)):
_tunables.appe... |
def is_acceptable(tensor):
if (not torch._C._get_cudnn_enabled()):
return False
if (tensor.type() not in CUDNN_TENSOR_TYPES):
return False
if (not is_available()):
warnings.warn('PyTorch was compiled without cuDNN support. To use cuDNN, rebuild PyTorch making sure the library is visi... |
def mean_color(scan_ids, all_scans):
mean_rgb = np.zeros((1, 3), dtype=np.float32)
n_points = 0
for scan_id in scan_ids:
color = all_scans[scan_id].color
mean_rgb += np.sum(color, axis=0)
n_points += len(color)
mean_rgb /= n_points
return mean_rgb |
def existsSemiDirectedPath(node_from, node_to, bound, graph):
Q = Queue()
V = set()
Q.put(node_from)
V.add(node_from)
node_e = None
distance = 0
while (not Q.empty()):
node_t = Q.get_nowait()
if (node_t == node_to):
return True
if (node_e == node_t):
... |
def compute_F1(gold_files, sys_files, labeled=False):
correct = 0
predicted = 0
actual = 0
n_tokens = 0
n_sequences = 0
current_seq_correct = False
n_correct_sequences = 0
current_fp = 0
current_sent = 0
for (gold_file, sys_file) in zip(gold_files, sys_files):
with codecs... |
class storage():
instance = None
client = None
def __init__(self):
self.client = gcp_storage.Client()
def unique_name(name):
(name, extension) = os.path.splitext(name)
return '{name}.{random}{extension}'.format(name=name, extension=extension, random=str(uuid.uuid4()).split('-')[0... |
('dace.libraries.blas.bmm')
def bmmnode(pv, sdfg: dace.SDFG, state: dace.SDFGState, A, B, C, alpha=1, beta=0, trans_a=False, trans_b=False):
(A_in, B_in) = (state.add_read(name) for name in (A, B))
C_out = state.add_write(C)
libnode = BatchedMatMul('bmm')
libnode.alpha = alpha
libnode.beta = beta
... |
def load_data(args):
data_path = os.path.join(args.data_dir, ('data_%s.json' % args.eval_name))
return json.load(open(data_path, 'r')) |
_utils.test(arch=archs_support_ndarray_ad, default_fp=ti.f32, require=ti.extension.adstack)
def test_ad_fibonacci_index():
N = 5
M = 10
a = ti.ndarray(ti.f32, shape=M, needs_grad=True)
b = ti.ndarray(ti.f32, shape=M, needs_grad=True)
f = ti.ndarray(ti.f32, shape=(), needs_grad=True)
def fib(a: t... |
def _read_pretrained_embedding_file(embeddings_filename: str, embedding_dim: int, vocab: Vocabulary, namespace: str='tokens') -> torch.FloatTensor:
if ((embeddings_filename[(- 3):] == '.h5') or (embeddings_filename[(- 5):] == '.hdf5')):
return _read_pretrained_hdf5_format_embedding_file(embeddings_filename,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.