code stringlengths 101 5.91M |
|---|
class SoftCrossEntropy(nn.Module):
def __init__(self):
super(SoftCrossEntropy, self).__init__()
return
def forward(self, inputs, target, target_lens):
assert (inputs.shape == target.shape)
assert (inputs.shape[0] == target_lens.shape[0])
mask = (torch.arange(target.shape[... |
class NumpyForm(NumpyMeta, Form):
def __init__(self, primitive, inner_shape=(), *, parameters=None, form_key=None):
primitive = ak.types.numpytype.dtype_to_primitive(ak.types.numpytype.primitive_to_dtype(primitive))
if (not isinstance(inner_shape, Iterable)):
raise TypeError("{} 'inner_s... |
class RandomSelectPolicy(SelectPolicy):
def __init__(self, fuzzer: GPTFuzzer=None):
super().__init__(fuzzer)
def select(self) -> PromptNode:
seed = random.choice(self.fuzzer.prompt_nodes)
seed.visited_num += 1
return seed |
class VideoFolderDataset(Dataset):
def __init__(self, root, train, resolution, path=None, n_frames=16, skip=1, fold=1, max_size=None, use_labels=False, return_vid=False, time_saliency=False, sub=False, seed=42, **super_kwargs):
video_root = osp.join(os.path.join(root))
if (not (1 <= fold <= 3)):
... |
def save(model):
if issubclass(type(model), torch.jit.ScriptModule):
return model.save_to_buffer()
elif issubclass(type(model), torch.nn.Module):
return deepcopy(model)
else:
raise RuntimeError(f'Cannot save type {type(model)}') |
def make_estimator(name, categorical_columns=None, iforest_kw=None, lof_kw=None):
if (name == 'LOF'):
outlier_detector = LocalOutlierFactor(**(lof_kw or {}))
if (categorical_columns is None):
preprocessor = RobustScaler()
else:
preprocessor = ColumnTransformer(transfo... |
class StandardScaler():
def __init__(self):
self.mean = 0.0
self.std = 1.0
def fit(self, data):
self.mean = data.mean(0)
self.std = data.std(0)
def transform(self, data):
mean = (torch.from_numpy(self.mean).type_as(data).to(data.device) if torch.is_tensor(data) else s... |
def test_ArrayBuilder_real():
def f1(x, z):
x.real(1)
x.real(2.2)
x.real(z)
return x
a = ak.highlevel.ArrayBuilder()
b = f1(a, np.array([3.5], dtype=np.float32)[0])
assert (ak.operations.to_list(a.snapshot()) == [1, 2.2, 3.5])
assert (ak.operations.to_list(b.snapshot(... |
def pose_publisher():
model_state_pub = rospy.Publisher('/gazebo/set_model_states', ModelStates, queue_size=1)
relative_pose_pub = rospy.Publisher('/gazebo/relative_pose', Pose, queue_size=1)
poses_msg = ModelStates()
poses_msg.name = ([None] * 3)
poses_msg.pose = [Pose() for i in range(3)]
pose... |
class SelfTrainingClassifier(_RoutingNotSupportedMixin, MetaEstimatorMixin, BaseEstimator):
_estimator_type = 'classifier'
_parameter_constraints: dict = {'base_estimator': [HasMethods(['fit'])], 'threshold': [Interval(Real, 0.0, 1.0, closed='left')], 'criterion': [StrOptions({'threshold', 'k_best'})], 'k_best'... |
def test_anndataloader_distributed_sampler_init():
adata = scvi.data.synthetic_iid()
manager = generic_setup_adata_manager(adata)
with pytest.raises(ValueError):
_ = scvi.dataloaders.AnnDataLoader(manager, sampler='a sampler', distributed_sampler=True) |
def cardinality_bsgs(self, verbose=False):
E1 = self
k = self.base_field()
q = k.order()
if (q < 50):
if verbose:
print('q=', q, '< 50 so using exhaustive count')
return cardinality_exhaustive(self)
E2 = E1.quadratic_twist()
if verbose:
print('Quadratic twist ... |
def dropout_vnet(input_shape=(280, 280, 280, 1), kernel_size=3, activation='relu', padding='SAME', **kwargs):
inputs = Input(input_shape)
(conv1, pool1) = down_stage(inputs, 16, kernel_size=kernel_size, activation=activation, padding=padding)
(conv2, pool2) = down_stage(pool1, 32, kernel_size=kernel_size, a... |
class ManifoldPoint(Element):
def __init__(self, parent, coords=None, chart=None, name=None, latex_name=None, check_coords=True):
if parent.is_empty():
raise TypeError(f'cannot define a point on the {parent} because it has been declared empty')
Element.__init__(self, parent)
pare... |
def test_f1_macro_2d_list():
y_true = [[1, 2, 3, 4], [1, 2, 5, 6]]
y_pred = [[1, 5, 6], [1, 2, 3]]
assert (0.4285714 == approx(f1(y_true, y_pred, 'macro'))) |
def _check_bn(model):
flag = [False]
model.apply((lambda module: _check_bn_apply(module, flag)))
return flag[0] |
def register_types(module):
root_module = module.get_root()
module.add_class('Address', import_from_module='ns.network')
module.add_enum('MaxSize_e', ['MAX_SIZE'], outer_class=root_module['ns3::Address'], import_from_module='ns.network')
module.add_class('AttributeConstructionList', import_from_module='... |
.parametrize('hint, expected', [(A, UNSUPPORTED), (list[A], Instance(TypeInfo(list), (UNSUPPORTED,)))])
def test_convert_type_hint_unsupported(hint, expected):
ts = TypeSystem()
ts.convert_type_hint(hint, unsupported=UNSUPPORTED) |
def _SyncAllParams(devices, model, init_net, net, rendezvous, unique_param_names, max_concurrent_distributed_ops=4):
if ((rendezvous is None) or (rendezvous['num_shards'] <= 1)):
_SyncAllParamsSingleHost(devices, model, net, unique_param_names)
else:
_SyncAllParamsDistributed(devices, model, ini... |
class TestMinimumPhase():
def test_bad_args(self):
assert_raises(ValueError, minimum_phase, [1.0])
assert_raises(ValueError, minimum_phase, [1.0, 1.0])
assert_raises(ValueError, minimum_phase, np.full(10, 1j))
assert_raises(ValueError, minimum_phase, 'foo')
assert_raises(Valu... |
def load(file, file_format=None, **kwargs):
if isinstance(file, Path):
file = str(file)
if ((file_format is None) and is_str(file)):
file_format = file.split('.')[(- 1)]
if (file_format not in file_handlers):
raise TypeError('Unsupported format: {}'.format(file_format))
handler =... |
def test_named_record_int32_float64_parameters():
t = RecordType([NumpyType('int32'), NumpyType('float64')], None, parameters={'__record__': 'Name', 'p': [123]})
assert (str(ak.types.from_datashape(str(t), highlevel=False)) == str(t)) |
class Lambda(LambdaBase):
def forward(self, input):
return self.lambda_func(self.forward_prepare(input)) |
def read_json(fname):
with fname.open('rt') as handle:
return json.load(handle, object_hook=OrderedDict) |
class _UnilinearModel(Model):
def __init__(self):
super().__init__(_unilin, fjacd=_unilin_fjd, fjacb=_unilin_fjb, estimate=_unilin_est, meta={'name': 'Univariate Linear', 'equ': 'y = B_0 * x + B_1', 'TeXequ': '$y = \\beta_0 x + \\beta_1$'}) |
def parse_args():
parser = argparse.ArgumentParser(description='Convert the conll03 format data into conllu format.')
parser.add_argument('input', help='Input conll03 format data filename.')
parser.add_argument('output', help='Output json filename.')
args = parser.parse_args()
return args |
def generate_pureSetting(inter_prob, intra_prob, alpha):
cps = [15, 30, 60, 75, 90, 105, 135]
fname = (((((('pure_' + str(inter_prob)) + '_') + str(intra_prob)) + '_') + str(alpha)) + '.txt')
cps_sizes = []
cps_probs = []
sizes_1 = [250, 250]
probs_1 = construct_SBM_block(sizes_1, inter_prob, in... |
.parametrize('method', ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
def test_gh18171(method):
def f(x):
f._count += 1
return np.nan
f._count = 0
res = root_scalar(f, bracket=(0, 1), method=method)
assert (res.converged is False)
assert res.flag.startswith('The function value ... |
def main():
parser = argparse.ArgumentParser()
add_generic_args(parser, os.getcwd())
parser = GLUETransformer.add_model_specific_args(parser, os.getcwd())
args = parser.parse_args()
if (args.output_dir is None):
args.output_dir = os.path.join('./results', f"{args.task}_{time.strftime('%Y%m%d... |
class Mixed_5c(nn.Module):
def __init__(self):
super(Mixed_5c, self).__init__()
self.branch0 = nn.Sequential(BasicConv3d(832, 384, kernel_size=1, stride=1))
self.branch1 = nn.Sequential(BasicConv3d(832, 192, kernel_size=1, stride=1), SepConv3d(192, 384, kernel_size=3, stride=1, padding=1))
... |
.expansion
class ExpandReduceCUDABlockAll(pm.ExpandTransformation):
environments = [CUDA]
def redirect_edge(graph, edge, new_src=None, new_src_conn=None, new_dst=None, new_dst_conn=None, new_data=None):
data = (new_data if new_data else edge.data)
if (new_src and new_dst):
ret = grap... |
def convert_pkl(old_pkl, new_pkl):
import dill
import pickle
dill._dill._reverse_typemap['ObjectType'] = object
with open(old_pkl, 'rb') as f:
loaded = pickle.load(f, encoding='latin1')
with open(new_pkl, 'wb') as outfile:
pickle.dump(loaded, outfile) |
def _random_operator(data_type: str) -> str:
if (data_type == 'categorical'):
ops = ['==', '!=']
elif (data_type == 'boolean'):
ops = ['', 'not ']
elif (data_type == 'numerical'):
ops = ['==', '!=', '>', '<', '>=', '<=']
else:
raise ValueError(f'Unknown `data_type`: {data... |
def pnn_model_fn(features, labels, mode, params):
fields_embeddings = []
for cat_feature_column in params['category_feature_columns']:
embed_input = fc.input_layer(features, [cat_feature_column])
fields_embeddings.append(embed_input)
fields_embeddings = tf.concat(fields_embeddings, axis=(- 1... |
def get_list_of_files(directory_list):
files = []
for directory in directory_list:
dir_name = directory['directory_name']
schema_dir = directory['schema_directory']
with open(os.path.join(schema_dir, 'schema.json'), 'r') as json_data:
schema = json.load(json_data)
... |
class Trainer(DefaultTrainer):
def build_evaluator(cls, cfg, dataset_name, output_folder=None):
if (output_folder is None):
output_folder = os.path.join(cfg.OUTPUT_DIR, 'inference')
evaluator_list = []
evaluator_type = MetadataCatalog.get(dataset_name).evaluator_type
if (... |
class Trainer(BaseTrainer):
def __init__(self, cfg: (DictConfig | ExperimentConfig), build_networks: bool=True, ckpt_dir: Optional[os.PathLike]=None, keep: Optional[(str | Sequence[str])]=None, skip: Optional[(str | Sequence[str])]=None) -> None:
super().__init__(cfg=cfg, keep=keep, skip=skip)
asser... |
def add_vehicle(traci, veh_id, route_id, route_edge_ids: List[str], type_id, depart_pos, depart_lane, depart_speed):
traci.route.add(route_id, route_edge_ids)
logging.debug(f'Added route {route_id} with edge_ids {route_edge_ids}...')
traci.vehicle.add(veh_id, route_id, type_id, departPos=depart_pos, departL... |
def test_get_visual_block_pipeline():
pipe = Pipeline([('imputer', SimpleImputer()), ('do_nothing', 'passthrough'), ('do_nothing_more', None), ('classifier', LogisticRegression())])
est_html_info = _get_visual_block(pipe)
assert (est_html_info.kind == 'serial')
assert (est_html_info.estimators == tuple(... |
def s_to_speaker(span, speakers):
if (speakers[span.i1] == speakers[span.i2]):
return speakers[span.i1]
return None |
def get_tgt_model(args, root, sample_shape, num_classes, loss, add_loss=False, use_determined=False, context=None, opid=0):
(src_train_loader, _, _, _, _, _, _) = get_data(root, args.embedder_dataset, args.batch_size, False, maxsize=5000)
if (len(sample_shape) == 4):
IMG_SIZE = (224 if ((args.weight == ... |
def dict_val(metric_dict):
out = {}
for (k, v) in metric_dict.items():
out[k] = v.val
return out |
def PrimitiveGroups(d=None):
if (d is None):
return PrimitiveGroupsAll()
else:
d = Integer(d)
if (d < 0):
raise ValueError('a primitive group acts on a non negative integer number of positions')
return PrimitiveGroupsOfDegree(d) |
class OntologyLabelingFunction(LabelingFunction):
def __init__(self, name: str, ontology: Dict[(str, np.array)], case_sensitive: bool=False, max_ngrams: int=8, stopwords=None) -> None:
super().__init__(name, None)
self.max_ngrams = max_ngrams
self.case_sensitive = case_sensitive
self... |
class TDAmeritradeGetBalance(VirtualFunctionTool):
name = 'TDAmeritradeGetBalance'
summary = 'Retrieve the balance of an account that belongs to the User.'
parameters: List[ArgParameter] = [{'name': 'account', 'type': 'string', 'description': "The account type, one of ['self-directed TFSA', 'self-directed n... |
class PointMagneticFluxDensity(BaseRx):
def __init__(self, locations, orientation='x', component='real', **kwargs):
self.projField = 'b'
super().__init__(locations, orientation, component, **kwargs) |
def pad_batched_data(batched_data):
batched_post_tokens = [item['post'].split() for item in batched_data]
batched_res_tokens = [item['response'].split() for item in batched_data]
encoder_len = (max([len(p) for p in batched_post_tokens]) + 1)
decoder_len = (max([len(r) for r in batched_res_tokens]) + 1)
... |
def clear_no_need_grad_tester(rng, func, inputs, func_args=[], func_kwargs={}, backward=None, atol_f=1e-06, ctx=None, func_name=None, insert_identity=[], auto_forward=False):
if (ctx is None):
ctx = nn.Context()
if (backward is None):
backward = [True for _ in inputs]
if (not (True in backwa... |
class NLayerDiscriminator(nn.Module):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
super(NLayerDiscriminator, self).__init__()
if (type(norm_layer) == functools.partial):
use_bias = (norm_layer.func == nn.InstanceNorm2d)
else:
use_bias ... |
def ref_binary_error(x, l):
y = []
for (x_, l_) in zip(x, l):
y.append(((x_ >= 0.5) != (l_ >= 0.5)))
return np.array(y).reshape(x.shape) |
def _replace_ref_nodes_with_names(model: models.Model, model_list: List[optplan.ProblemGraphNodeSchema]) -> None:
def process_field(model: models.Model, child_model: models.Model) -> str:
if isinstance(child_model, str):
return child_model
ind = model_list.index(child_model)
retu... |
class ShiftedPrimedTableaux_weight_shape(ShiftedPrimedTableaux):
def __init__(self, weight, shape, skew=None, primed_diagonal=False):
ShiftedPrimedTableaux.__init__(self, skew=skew, primed_diagonal=primed_diagonal)
if (skew is None):
Parent.__init__(self, category=FiniteEnumeratedSets())... |
def test_map_param():
def map_uses_param(A: dace.float32[10], B: dace.float32[10], C: dace.float32[10]):
for i in dace.map[0:10]:
a = (i - A[i])
b = (B[i] * i)
C[i] = (a + b)
sdfg = map_uses_param.to_sdfg(simplify=True)
num_tasklet_fusions = sdfg.apply_transformat... |
def resize_worker(img_file, size, use_rgb, format, resample):
(i, file) = img_file
img = Image.open(file)
if use_rgb:
img = img.convert('RGB')
img = resize_and_convert(img, size, format, resample)
return (i, img) |
_module()
class EpochBasedRunnerAmp(EpochBasedRunner):
def save_checkpoint(self, out_dir, filename_tmpl='epoch_{}.pth', save_optimizer=True, meta=None, create_symlink=True):
if (meta is None):
meta = dict(epoch=(self.epoch + 1), iter=self.iter)
elif isinstance(meta, dict):
me... |
def Affine(name_scope, input_tensor, out_channels, relu=True):
input_shape = input_tensor.get_shape().as_list()
input_channels = input_shape[(- 1)]
with tf.name_scope(name_scope):
weights = tf.Variable(tf.truncated_normal([input_channels, out_channels], stddev=(1.0 / math.sqrt(float(input_channels))... |
def require_apex(test_case):
return unittest.skipUnless(is_apex_available(), 'test requires apex')(test_case) |
def filter_lines(lines):
lines = [line for line in map(str.strip, lines) if (line and (not line.startswith('#')))]
func_sigs = [split_signature(line) for line in lines if (line.split(' ')[0] != 'void')]
sub_sigs = [split_signature(line) for line in lines if (line.split(' ')[0] == 'void')]
all_sigs = lis... |
class STL10(CIFAR10):
base_folder = 'stl10_binary'
url = '
filename = 'stl10_binary.tar.gz'
tgz_md5 = '91f7769df0f17e558f3565bffb0c7dfb'
class_names_file = 'class_names.txt'
train_list = [['train_X.bin', '918c2871b30a85fa023e0c44e0bee87f'], ['train_y.bin', '5a34089d4802c674881badbb'], ['unlabele... |
def tree_map(fn: Any, pytree: PyTree) -> PyTree:
(flat_args, spec) = tree_flatten(pytree)
return tree_unflatten([fn(i) for i in flat_args], spec) |
class SimplicialComplexes(Category_singleton):
_method
def super_categories(self):
return [Sets()]
class Finite(CategoryWithAxiom):
class ParentMethods():
_method
def dimension(self):
return max((c.dimension() for c in self.facets()))
class ParentM... |
class build_py(old_build_py):
def run(self):
build_src = self.get_finalized_command('build_src')
if (build_src.py_modules_dict and (self.packages is None)):
self.packages = list(build_src.py_modules_dict.keys())
old_build_py.run(self)
def find_package_modules(self, package, p... |
def run_task(task):
log.info(f'Task name: {task.name}')
task_args = (task.args if ('args' in task) else '')
task_args = task_args.replace('$\\', '\\$')
command = f'CUDA_VISIBLE_DEVICES={utils.WORKER_CUDA_DEVICE} HYDRA_CONFIG_PATH={task.config_path} {task.environ} python {task.command} repeat={task.repea... |
class WoE():
def __init__(self, f_type: str, split: List[float], woe_diff_th: float=0.0, target_type: TaskType=TaskType.BIN):
self.f_type = f_type
self.split = split
self.woe_diff = woe_diff_th
self.target_type = target_type
self.iv = None
self.cod_dict = None
def... |
class BankManagerPayBill(VirtualFunctionTool):
name = 'BankManagerPayBill'
summary = 'Pay a bill to a specified payee with your service acccount number.'
parameters: List[ArgParameter] = [{'name': 'from_account_number', 'type': 'string', 'description': "The user's bank account number used for paying the bil... |
def evaluate_tfidf_distance(ref_texts, hypo_texts):
print('Evaluating TF-IDF Distance...')
vocab = get_vocab(ref_texts)
results = {'n_ref': len(ref_texts), 'n_hypo': len(hypo_texts)}
ref_feature = get_feature(ref_texts, vocab)
hypo_feature = get_feature(hypo_texts, vocab)
results[f'tfidf_distanc... |
def __curve_validation__(curve, actual_vector, probs):
for item in [actual_vector, probs]:
if (not isinstance(item, (list, numpy.ndarray))):
raise pycmCurveError(VECTOR_TYPE_ERROR)
if (len(actual_vector) != len(probs)):
raise pycmCurveError(VECTOR_SIZE_ERROR)
for item in probs:
... |
def extract_mep_S1_models(layout):
wandb_dir = RESULT_PATH.format(layout=layout)
runs = glob.glob(f'{wandb_dir}/run*')
run_ids = [x.split('-')[(- 1)] for x in runs]
print(runs)
print(run_ids)
api = wandb.Api()
for (i, run_id) in enumerate(run_ids):
run = api.run(f'{WANDB_NAME}/Overco... |
def subprocess_fn(rank, args, temp_dir):
dnnlib.util.Logger(should_flush=True)
if (args.num_gpus > 1):
init_file = os.path.abspath(os.path.join(temp_dir, '.torch_distributed_init'))
if (os.name == 'nt'):
init_method = ('file:///' + init_file.replace('\\', '/'))
torch.dist... |
class PoolAggregator(nn.Module):
def __init__(self, in_features, out_features):
super().__init__()
self.tran = nn.Linear(in_features, out_features, True)
def forward(self, x, neighbor):
f = [self.tran(torch.cat([x[i:(i + 1)], n])) for (i, n) in enumerate(neighbor)]
x = torch.cat(... |
def getConfigFromDict(obj, inputDict, defaultConfig):
if (not inputDict):
for (member, value) in vars(defaultConfig).items():
setattr(obj, member, value)
else:
for (member, value) in vars(defaultConfig).items():
setattr(obj, member, inputDict.get(member, value)) |
class CoercionPDtoKM(HyperbolicModelCoercion):
def image_coordinates(self, x):
return (((2 * real(x)) / ((Integer(1) + (real(x) ** 2)) + (imag(x) ** 2))), ((2 * imag(x)) / ((Integer(1) + (real(x) ** 2)) + (imag(x) ** 2))))
def image_isometry_matrix(self, x):
return SL2R_to_SO21((((matrix(2, [1, ... |
def tree_serialize_leaves_tensorstore(checkpoint_dir, pytree):
leaf_key_paths = jax_utils.leaf_key_paths(pytree, is_leaf=is_named_array)
specs = jtu.tree_map(partial(_tensorstore_spec_for, checkpoint_dir), leaf_key_paths, is_leaf=is_named_array)
async def _do_serialize():
futures = jtu.tree_map(_ser... |
def test_disagreement(example_diversity):
(y_pred_classifier1, y_pred_classifier2, y_real, y_ex1) = example_diversity
disagreement = disagreement_measure(y_real, y_pred_classifier1, y_pred_classifier2)
assert np.isclose(disagreement, 0.5).all() |
def extract_roi(opts, cls_ids, label, label_edit):
pixel_num = {'before_edit': 0, 'after_edit': 0, 'whole': 0}
roi = np.zeros((256, 256), np.uint8)
label = label.view(256, 256).numpy()
label_edit = label_edit.view(256, 256).numpy()
for ids in cls_ids:
roi += (label == int(ids)).astype(np.uin... |
class MLP(BaseModel):
name = 'mlp'
def __init__(self, task, embedding_size=768, n_classes=3, hidden_size=5, nlayers=1, dropout=0.1, representation=None, n_words=None):
super().__init__()
self.dropout_p = dropout
self.embedding_size = embedding_size
self.hidden_size = hidden_size
... |
def collate_fn(batch):
if (not isinstance(batch, Sequence)):
raise TypeError(f'{batch.dtype} is not supported.')
if isinstance(batch[0], DataContainer):
stacked = []
if batch[0].cpu_only:
stacked.append([sample.data for sample in batch])
return DataContainer(stack... |
def T_sequences_smallcases(t, existence=False, check=True):
db = {47: [((([1, (- 1), (- 1), 0, 0, (- 1), 1, (- 1)] + ([0] * 8)) + [1, (- 1), (- 1), 0, 0, (- 1), (- 1)]) + ([0] * 24)), ([0, 0, 0, (- 1), 1, 0, 0, 0, (- 1), (- 1), (- 1), 1, 1, 1, 1, 1, 0, 0, 0, 1, (- 1), 0, 0, 1] + ([0] * 23)), (([0] * 26) + [(- 1), 0... |
def get_parser():
parser = argparse.ArgumentParser(description='apply clusters')
parser.add_argument('data', help='location of tsv files')
parser.add_argument('--split', help='split to process', required=True)
parser.add_argument('--labels', help='split to process', default='phn')
parser.add_argumen... |
class docRowTypeSub(supermod.docRowType):
def __init__(self, entry=None):
supermod.docRowType.__init__(self, entry) |
class BasicMachine(object):
def __init__(self, datasets=(None, None), models=None, args=None, **kwargs):
super(BasicMachine, self).__init__()
self.args = args
print('==> creating model ')
self.model = archs.__dict__[self.args.arch]()
print('==> creating model [Finish]')
... |
def faiss_search_knn(feat, k, nprobe=128, num_process=4, is_precise=True, sort=True, verbose=False):
(dists, nbrs) = faiss_search_approx_knn(query=feat, target=feat, k=k, nprobe=nprobe, verbose=verbose)
if is_precise:
print('compute precise dist among k={} nearest neighbors'.format(k))
(dists, n... |
def train(epochs=10, batch_size=32, alpha=0.6, w=0.4, num_workers=2, lr=0.0001, save_epoch=10, train_path=(ROOT / 'dataset/KITTI/training'), model_path=(ROOT / 'weights/'), select_model='resnet18', api_key=''):
train_path = str(train_path)
model_path = str(model_path)
print('[INFO] Loading dataset...')
... |
def create_model(args, logger, model_name):
if (model_name == 'adapter_mlp'):
if (hasattr(args, 'adapter_inference') and args.adapter_inference):
from models.adapter_inference import Adapter
else:
from models.adapter import Adapter
model = Adapter(args, logger)
el... |
class Encoder_CNNtime_SAfreq(nn.Module):
def __init__(self, n_margin, n_frame, n_bin, cnn_channel, cnn_kernel, hid_dim, n_layers, n_heads, pf_dim, dropout, device):
super().__init__()
self.device = device
self.n_frame = n_frame
self.n_bin = n_bin
self.cnn_channel = cnn_channe... |
def get_representative_dataset(data_loader, n_iters, data_loader_key=0, transforms=None):
class RepresentativeDataset(object):
def __init__(self, in_data_loader):
self.dl = in_data_loader
self.iter = iter(self.dl)
def __call__(self):
for _ in range(n_iters):
... |
def binarize_scores(threshold: float, scores: list[float]) -> list[int]:
return (np.array(scores) > threshold).astype(int).tolist() |
def unfold(g, input, dimension, size, step):
return g.op('ATen', input, operator_s='unfold', dimension_i=dimension, size_i=size, step_i=step) |
def extract_data_for_mask_loss_from_matches(proposals_targets: Iterable[Instances], estimated_segm: torch.Tensor) -> DataForMaskLoss:
data = DataForMaskLoss()
masks_gt = []
offset = 0
assert (estimated_segm.shape[2] == estimated_segm.shape[3]), f'Expected estimated segmentation to have a square shape, b... |
class BaseEliminationOrder():
def __init__(self, model):
if (not isinstance(model, BayesianModel)):
raise ValueError('Model should be a BayesianModel instance')
self.bayesian_model = model.copy()
self.moralized_model = self.bayesian_model.moralize()
def cost(self, node):
... |
('/get_accounts')
def get_accounts():
accounts = []
for address in app.eth_accounts:
item = app.eth_accounts[address]
accounts.append({'address': address, 'name': item['name'], 'type': 'emulator'})
Account.enable_unaudited_hdwallet_features()
local_account_names = app.configure['local_ac... |
def print_scores(scores):
print(f'mean: {np.mean(scores):.4f}, std: {np.std(scores):.4f}')
counter = collections.Counter(scores)
for (k, v) in sorted(counter.items()):
print(f'score {k}: count {v}')
print('total count:', len(scores)) |
def get_overview_paragraphs(overview, specific_summary_dir):
overview_paragraphs = []
try:
soup = BeautifulSoup(urllib.request.urlopen(overview), 'html.parser')
except Exception as e:
print(e)
time.sleep(4)
try:
soup = BeautifulSoup(urllib.request.urlopen(overview... |
(Output('national-post-graph', 'figure'), Input('stored-df-data', 'data'), prevent_initial_call=True)
def update_fig_5(jsonified_cleaned_data):
df = pd.read_json(jsonified_cleaned_data, orient='split')
return plot_lines(df, 'National Post') |
class SetVocab(BaseVocab):
_base_special_tokens = [u'pad', u'root', u'unk']
def __init__(self, *args, **kwargs):
super(SetVocab, self).__init__(*args, **kwargs)
special_tokens = [getattr(base_special_token, self._config.getstr(self, 'special_token_case'))() for base_special_token in self._base_s... |
def random_blur(image, height, width, p=1.0):
del width
def _transform(image):
sigma = tf.random.uniform([], 0.1, 2.0, dtype=tf.float32)
return gaussian_blur(image, kernel_size=(height // 10), sigma=sigma, padding='SAME')
return random_apply(_transform, p=p, x=image) |
def record_video_of_policy(task, world_params, policy_fn, file_name, number_of_resets, max_time_steps=100, env_wrappers=np.array([]), env_wrappers_args=np.array([])):
actual_skip_frame = world_params['skip_frame']
env = get_world(task.get_task_name(), task.get_task_params(), world_params, enable_visualization=F... |
def pair_to_graph(sp1, sp2):
g = Graph()
for part in sp1:
part_list = list(part)
if part_list:
g.add_vertex((part_list[0], 1))
if (part_list[0] < 0):
g.add_edge((part_list[0], 1), (abs(part_list[0]), 2))
for i in range(1, len(part_list)):
... |
def create_ret_var(ctx: LeanGenContext, offset: int, cast: str, ret_var_base: str, is_explicit: bool, is_tail_call: bool, pc_offset: int) -> str:
ret_var = inc_name_sub(ret_var_base, ctx.name_sub)
ctx.add_main("generalize' hr_rev_{}: {}mem (ap{} - {}) = {},".format(ret_var, ((cast + ' ') if cast else ''), pc_of... |
def add_filehandler(logger, filepath, level=logging.DEBUG):
fh = logging.FileHandler(filepath)
fh.setLevel(level)
fh.setFormatter(formatter)
logger.addHandler(fh) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.