code stringlengths 101 5.91M |
|---|
class Similarity():
def __init__(self, model_name_or_path='shibing624/text2vec-base-chinese', similarity_type=SimilarityType.COSINE, embedding_type=EmbeddingType.BERT, encoder_type=EncoderType.MEAN, max_seq_length=256):
if (embedding_type not in [EmbeddingType.BERT, EmbeddingType.WORD2VEC]):
log... |
def eval_policy(policy, env_name, seed, eval_episodes=10):
eval_env = gym.make(env_name)
eval_env.seed((seed + 100))
avg_reward = 0.0
for _ in range(eval_episodes):
(state, done) = (eval_env.reset(), False)
while (not done):
action = eval_env.action_space.sample()
... |
def generate_types(package_name: str, file_name: str, values_indices: T.Mapping[(str, T.Dict[(str, IndexEntry)])], use_eigen_types: bool, shared_types: T.Mapping[(str, str)]=None, scalar_type: str='double', output_dir: T.Openable=None, lcm_bindings_output_dir: T.Openable=None, templates: template_util.TemplateList=None... |
def _mul_fateman_mul(f, g):
f = f.change_ring(QQ)
g = g.change_ring(QQ)
f_list = f.list()
g_list = g.list()
fgcd = f_list[0].content(f_list)
ggcd = g_list[0].content(g_list)
z_poly_f = (f * fgcd.denominator()).change_ring(ZZ)
z_poly_g = (g * ggcd.denominator()).change_ring(ZZ)
div = ... |
class MultigraphDecoder():
def __init__(self, multigraph_creator):
self.coref_multigraph_creator = multigraph_creator
def decode(self, corpus):
for doc in corpus:
for mention in doc.system_mentions:
mention.attributes['set_id'] = None
self.decode_for_one_d... |
class KirillovReshetikhinTableaux(CrystalOfWords):
def __classcall_private__(cls, cartan_type, r, s):
ct = CartanType(cartan_type)
if (not ct.is_affine()):
raise ValueError('The Cartan type must be affine')
typ = ct.type()
if ct.is_untwisted_affine():
if (typ ... |
class A000213(SloaneSequence):
def __init__(self):
SloaneSequence.__init__(self, offset=0)
self._b = []
self._precompute()
def _repr_(self):
return 'Tribonacci numbers: a(n) = a(n-1) + a(n-2) + a(n-3).'
def _precompute(self, how_many=20):
try:
f = self._f
... |
class Latex(LatexCall):
def __init__(self, debug=False, slide=False, density=150, engine=None):
self.__debug = debug
self.__slide = slide
self.__engine = engine
self.__density = density
def _relation_symbols(self):
import operator
return {operator.lt: ' < ', opera... |
def _get_qmu_qsqrt(kernel, inducing_variable):
Z = inducing_variable.Z.numpy()
Kzz = kernel(Z, full_cov=True).numpy()
q_sqrt = np.linalg.cholesky((Kzz + (default_jitter() * np.eye(len(Z)))))
q_mu = (q_sqrt np.random.randn(len(Z), 1))
return (q_mu, q_sqrt) |
class LinkData():
def __init__(self, category, start, end, mention, comp, value, name, link_feat, gl_pos=None):
self.gl_pos = gl_pos
self.category = category
self.start = start
self.end = end
self.mention = mention
self.comp = comp
self.value = str(value)
... |
.parametrize('y_pred', [np.array(y_pred_list), y_pred_list])
def test_gamma_conformity_score_consistency(y_pred: NDArray) -> None:
gamma_conf_score = GammaConformityScore()
signed_conf_scores = gamma_conf_score.get_signed_conformity_scores(X_toy, y_toy, y_pred)
y_obs = gamma_conf_score.get_estimation_distri... |
class SetAttentionBlock(nn.Module):
def __init__(self, d_model, num_heads, d_head, d_ff, dropouth=0.0, dropouta=0.0):
super(SetAttentionBlock, self).__init__()
self.mha = MultiHeadAttention(d_model, num_heads, d_head, d_ff, dropouth=dropouth, dropouta=dropouta)
def forward(self, feat, lengths):
... |
def grid2list(grid):
list_in = [[]]
for grid_temp in grid:
list_out = []
for val in grid_temp:
for list_temp in list_in:
list_out.append((list_temp + [val]))
list_in = list_out
return list_in |
def test_dataset():
dataset = soundata.initialize('esc50')
assert isinstance(dataset, core.Dataset)
dataset = soundata.initialize('urbansound8k')
assert isinstance(dataset, core.Dataset)
dataset = soundata.initialize('urbansed')
assert isinstance(dataset, core.Dataset)
print(dataset) |
class Lighting(object):
def __init__(self, alphastd, eigval, eigvec):
self.alphastd = alphastd
self.eigval = torch.Tensor(eigval)
self.eigvec = torch.Tensor(eigvec)
def __call__(self, img):
if (self.alphastd == 0):
return img
alpha = img.new().resize_(3).norma... |
class loss_count(torch.autograd.Function):
def forward(ctx, outputs, target, network_config, layer_config):
desired_count = network_config['desired_count']
undesired_count = network_config['undesired_count']
shape = outputs.shape
n_steps = shape[4]
out_count = torch.sum(outpu... |
def tqdm_with_logging(iterable=None, desc=None, total=None, leave=True, ncols=None, mininterval=0.1, maxinterval=10.0, miniters=None, ascii=None, disable=False, unit='it', unit_scale=False, dynamic_ncols=False, smoothing=0.3, bar_format=None, initial=0, position=None, postfix=None, logging_on_close=True, logging_on_upd... |
def basewise_bits(motif):
epsilon = 0.001
assert (motif.shape[1] == 4)
ent = np.apply_along_axis((lambda x: (- np.sum((x * np.log2(np.clip(x, epsilon, (1 - epsilon))))))), 1, motif)
return ent |
def test_toarrow_ListArray_RegularArray():
content = ak.highlevel.Array(['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']).layout
offsets = ak.index.Index32(np.array([0, 3, 3, 5, 6, 9]))
array = ak.contents.ListOffsetArray(offsets, content)
assert (array.to_arrow().to_pylist() == ... |
def _mmd2_and_ratio(K_XX, K_XY, K_YY, const_diagonal=False, biased=False, min_var_est=_eps):
(mmd2, var_est) = _mmd2_and_variance(K_XX, K_XY, K_YY, const_diagonal=const_diagonal, biased=biased)
ratio = (mmd2 / tf.sqrt(tf.maximum(var_est, min_var_est)))
return (mmd2, ratio) |
def check_wv_tok_in_nlu_tok(wv_tok1, nlu_t1):
g_wvi1_corenlp = []
nlu_t1_low = [tok.lower() for tok in nlu_t1]
for (i_wn, wv_tok11) in enumerate(wv_tok1):
wv_tok11_low = [tok.lower() for tok in wv_tok11]
results = find_sub_list(wv_tok11_low, nlu_t1_low)
(st_idx, ed_idx) = results[0]
... |
class DSTProcessor(DataProcessor):
def __init__(self, root):
self.D = [[], [], []]
self.D[0] = self.load_data(os.path.join(root, 'train_dials.json'))
self.D[1] = self.load_data(os.path.join(root, 'dev_dials.json'))
self.D[2] = self.load_data(os.path.join(root, 'test_dials.json'))
... |
def evaluate_single(postprocessed_sql_str, g_str, db_dir, db_id, kmaps):
p_str = postprocessed_sql_str
db_name = db_id
db = os.path.join(db_dir, db_id, (db_id + '.sqlite'))
schema = Schema(get_schema(db))
g_sql = get_sql(schema, g_str)
evaluator = Evaluator()
levels = ['easy', 'medium', 'har... |
class TypeConvertTransformer(BaseEstimator, TransformerMixin):
def __init__(self, columns, dtype):
self.columns = columns
self.dtype = dtype
def fit(self, X, *args):
return self
def transform(self, X):
for col in self.columns:
X[col] = X[col].astype(self.dtype)
... |
def test_polyder():
cases = [([5], 0, [5]), ([5], 1, [0]), ([3, 2, 1], 0, [3, 2, 1]), ([3, 2, 1], 1, [6, 2]), ([3, 2, 1], 2, [6]), ([3, 2, 1], 3, [0]), ([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]), ([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]), ([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]), ([[3, 2, 1], [5, 6, 7... |
class ParsedData():
parameters: dict[(str, Any)]
body: Any = NOT_SET
def __hash__(self) -> int:
value = hash(tuple(self.parameters.items()))
if (self.body is not NOT_SET):
if isinstance(self.body, (dict, list)):
value ^= hash(json.dumps(self.body, sort_keys=True))... |
class Capture(object):
def __init__(self, capfd):
self.capfd = capfd
self.out = ''
self.err = ''
def __enter__(self):
self.capfd.readouterr()
return self
def __exit__(self, *args):
(self.out, self.err) = self.capfd.readouterr()
def __eq__(self, other):
... |
def parse_module(module_name: str, query_type4py: bool=False) -> _ModuleParseResult:
module = importlib.import_module(module_name)
type4py_data: (Type4pyData | None) = None
syntax_tree: (astroid.Module | None) = None
linenos: int = (- 1)
try:
source_file = inspect.getsourcefile(module)
... |
def dla60x_c(pretrained=None, **kwargs):
BottleneckX.expansion = 2
model = DLA([1, 1, 1, 2, 3, 1], [16, 32, 64, 64, 128, 256], block=BottleneckX, **kwargs)
if (pretrained is not None):
model.load_pretrained_model(data='imagenet', name='dla60x_c', hash='b870c45c')
return model |
_args('v', 'f', 'i')
def dropout(g, input, p, train):
sym_help.assert_training_mode(train, 'dropout')
if (not sym_help._training_mode):
return input
warnings.warn('Dropout is a training op and should not be exported in inference mode. Make sure to call eval() on the model, and to export it with para... |
def assert_model_downloaded(checkpoint_path, url, use_wget=False):
if Path(checkpoint_path).exists():
log.debug(f'[+] Model already present at {checkpoint_path}!')
return
log.info(f'[-] Model not found at {checkpoint_path}! Will download it')
checkpoint_path = str(checkpoint_path)
if (no... |
def _check_timit_folders(uppercase, data_folder):
if uppercase:
test_str = '/TEST/DR1'
train_str = '/TRAIN/DR1'
else:
test_str = '/test/dr1'
train_str = '/train/dr1'
if (not os.path.exists((data_folder + test_str))):
err_msg = ('the folder %s does not exist (it is exp... |
def test_folder():
x = pickle_load(open('log_trans/infos_trans.pkl', 'rb'))
dataset = CaptionDataset(x['opt'])
ds = torch.utils.data.Subset(dataset, dataset.split_ix['train'])
ds[0] |
def test_comment_encoding_when_reindent():
sql = u'select foo -- Comment containing Umlauts\nfrom bar'
formatted = sqlparse.format(sql, reindent=True)
assert (formatted == sql) |
class TVQADataset(BaseDataset):
def __init__(self, *args, split='', **kwargs):
assert (split in ['train', 'val', 'test'])
self.split = split
self.metadata = None
self._load_metadata()
if (split == 'train'):
names = ['tvqa_train']
elif (split == 'val'):
... |
_args('v', 'i')
def _dim_arange(g, like, dim):
like_shape = g.op('Shape', like)
stop = g.op('Gather', like_shape, g.op('Constant', value_t=torch.tensor(dim)), axis_i=0)
if (sym_help._operator_export_type == torch.onnx.OperatorExportTypes.ONNX_ATEN_FALLBACK):
return g.op('_caffe2::Range', stop)
e... |
def dir_mat(path):
import scipy.io as sio
path = get_absolute_path(path)
return sio.whosmat(path) |
def filter_newstyle_options(func, **options):
allowed = get_options_from_function(func).keys()
filtered = {}
for key in options.keys():
for prefix in ['', 'use_', 'opt_', 'opt_allow_']:
if ((prefix + key) in allowed):
filtered[(prefix + key)] = options[key]
return fil... |
class Learner(BaseLearner):
def __init__(self, data, model, evaluator, batch_size=1, verbose=False):
super(Learner, self).__init__(data, model, evaluator, batch_size, verbose)
if (type(self.model).__name__ == 'BasicEncoderDecoder'):
setattr(self, '_run_batch', self._run_batch_basic)
... |
def plot_benchmark(output_path_root: str='tmp-/') -> None:
csv_files = glob((os.path.join(output_path_root, '*/') + 'stats.csv'), recursive=True)
pkl_files = []
for csv_file in csv_files:
folder = os.path.dirname(csv_file)
pkl_file = os.path.join(folder, 'results.pkl')
if ((not os.pa... |
class MeshInstance():
def __init__(self):
self.mesh_ptr = _ti_core.create_mesh()
self.relation_set = set()
self.verts = MeshElementField(self, MeshElementType.Vertex, {}, {}, {})
self.edges = MeshElementField(self, MeshElementType.Edge, {}, {}, {})
self.faces = MeshElementFie... |
def check_tree(tree):
def _check_node(node):
if np.isscalar(node):
return True
elif (isinstance(node, tuple) and (len(node) == 2)):
return (_check_node(node[0]) & _check_node(node[1]))
else:
raise Exception('Not a tree!')
return _check_node(tree) |
class CustomTrain(CustomBase):
def __init__(self, size, training_images_list_file):
super().__init__()
with open(training_images_list_file, 'r') as f:
paths = f.read().splitlines()
self.data = ImagePaths(paths=paths, size=size, random_crop=False) |
def randn_backward(grad_inputs, inputs, input_shapes, outputs, output_shapes, mu=0, sigma=1, shape=[], seed=(- 1)):
return ([None] * (len(grad_inputs) + len(inputs))) |
class LazySet(set):
_props = ('__str__', '__repr__', '__unicode__', '__hash__', '__sizeof__', '__cmp__', '__lt__', '__le__', '__eq__', '__ne__', '__gt__', '__ge__', '__contains__', '__len__', '__nonzero__', '__getitem__', '__setitem__', '__delitem__', '__iter__', '__sub__', '__and__', '__xor__', '__or__', '__rsub__... |
def dice_coef(y_tru, y_prd):
y_tru = tf.reshape(y_tru, [2, (- 1)])
y_prd = tf.reshape(y_prd, [2, (- 1)])
y_prd_pr = tf.sigmoid(y_prd)
intersection = tf.reduce_sum((y_prd_pr * y_tru), 0)
union = (tf.reduce_sum(y_prd_pr, 0) + tf.reduce_sum(y_tru, 0))
dice = (((2.0 * intersection) + _smooth) / (uni... |
class SentenceREDataset(data.Dataset):
def __init__(self, path, rel2id, tokenizer, kwargs, sort=False, sort_reverse=False):
super().__init__()
self.path = path
self.tokenizer = tokenizer
self.rel2id = rel2id
self.kwargs = kwargs
self.sort = sort
self.data = []... |
def add_code_sample_docstrings(*docstr, tokenizer_class=None, checkpoint=None, output_type=None, config_class=None):
def docstring_decorator(fn):
model_class = fn.__qualname__.split('.')[0]
is_tf_class = (model_class[:2] == 'TF')
if ('SequenceClassification' in model_class):
code... |
.operations('invalid')
def test_invalid_operation_suggestion(cli, cli_args, snapshot_cli):
assert (cli.run(*cli_args, '--validate-schema=true') == snapshot_cli) |
def get_a_expr_field_value(node: A_Expr):
if isinstance(node.lexpr, ColumnRef):
column = node.lexpr
value = node.rexpr
elif (isinstance(node.rexpr, ColumnRef) or isinstance(node.rexpr, ColumnRef)):
column = node.rexpr
value = node.lexpr
assert isinstance(column, ColumnRef)
... |
def train(small_dataset, n_items, constructor, actor_reg_loss_scaler=0.0, n_epochs_pred_only=0, n_epochs_ac_only=0, n_epochs_pred_and_ac=0, break_early=False, lr_actor=0.001, lr_critic=0.0001, lr_ac=2e-06, batch_size=100, min_kl=0.0, max_kl=0.2, batches_to_anneal_over=200000, verbose=False):
print('boom, top of tra... |
class TrainEngine(object):
def __init__(self):
self.hooks = {name: (lambda state: None) for name in ['on_start', 'on_start_epoch', 'on_end_epoch', 'on_start_episode', 'on_end_episode', 'on_end']}
def train(self, loss_func, train_loader, val_loader, epochs, n_episodes, **kwargs):
state = {'train_... |
_module(name='Pretrained')
class PretrainedInit():
def __init__(self, checkpoint: str, prefix: Optional[str]=None, map_location: Optional[str]=None):
self.checkpoint = checkpoint
self.prefix = prefix
self.map_location = map_location
def __call__(self, module: nn.Module) -> None:
... |
def cleanUrl(url):
title = unquote_plus(url)
title = removeAllapostrophe(title)
return title |
def pause(info='Press any key to continue ...', err=False):
if ((not isatty(sys.stdin)) or (not isatty(sys.stdout))):
return
try:
if info:
echo(info, nl=False, err=err)
try:
getchar()
except (KeyboardInterrupt, EOFError):
pass
finally:
... |
def test_fc_dropseq_dataset(save_path: str):
gene_dataset = scvi.data.frontalcortex_dropseq(save_path=save_path)
unsupervised_training_one_epoch(gene_dataset) |
def save_obj_data(model, filename):
assert (('v' in model) and (model['v'].size != 0))
with open(filename, 'w') as fp:
if (('v' in model) and (model['v'].size != 0)):
for v in model['v']:
fp.write(('v %f %f %f\n' % (v[0], v[1], v[2])))
if (('vn' in model) and (model['... |
class HashMissing(HashError):
order = 2
head = 'Hashes are required in --require-hashes mode, but they are missing from some requirements. Here is a list of those requirements along with the hashes their downloaded archives actually had. Add lines like these to your requirements files to prevent tampering. (If ... |
def iter10x10y(num):
for ir in range((num - 1), (- 1), (- 1)):
for ic in range((num - 1), (- 1), (- 1)):
(yield (ir, ic)) |
def log_images_from_w(ws, G, names):
for (name, w) in zip(names, ws):
w = w.to(global_config.device)
log_image_from_w(w, G, name) |
.parametrize('ctx, func_name', ctxs)
.parametrize('seed', [313])
def test_atan_forward_backward(seed, ctx, func_name):
from nbla_test_utils import function_tester
rng = np.random.RandomState(seed)
inputs = [(rng.randn(2, 3, 4).astype(np.float32) * 1)]
inputs += [(rng.randn(2, 3, 4).astype(np.float32) * ... |
def print_header_ps(s):
s += '%% --- Auto-generated PostScript ---\n\n\n'
s += '%% Generated on: \n'
s += (('%%' + time.asctime()) + '\n')
return s |
def validate_config_dict(workflow_config_dict):
try:
config_schema.validate(workflow_config_dict)
except SchemaError as se:
raise se |
def load_pointcloud_ply(filename):
with open(filename, 'rb') as fh:
assert (fh.readline().rstrip() == b'ply')
assert (fh.readline().rstrip() == b'format binary_little_endian 1.0')
nr_elements = int(fh.readline().strip().decode('ascii').split(' ')[(- 1)])
assert (fh.readline().rstrip(... |
def test_vaihingen():
test_dataset = ISPRSDataset(pipeline=[], img_dir=osp.join(osp.dirname(__file__), '../data/pseudo_vaihingen_dataset/img_dir'), ann_dir=osp.join(osp.dirname(__file__), '../data/pseudo_vaihingen_dataset/ann_dir'))
assert (len(test_dataset) == 1) |
def profile(n):
def decorator_with_name(func):
def func_wrapper(*args, **kwargs):
with ProfileKV(n):
return func(*args, **kwargs)
return func_wrapper
return decorator_with_name |
def build_detector(cfg, train_cfg=None, test_cfg=None):
if ((train_cfg is not None) or (test_cfg is not None)):
warnings.warn('train_cfg and test_cfg is deprecated, please specify them in model', UserWarning)
assert ((cfg.get('train_cfg') is None) or (train_cfg is None)), 'train_cfg specified in both ou... |
class Flatten(Module):
__constants__ = ['start_dim', 'end_dim']
start_dim: int
end_dim: int
def __init__(self, start_dim: int=1, end_dim: int=(- 1)) -> None:
super(Flatten, self).__init__()
self.start_dim = start_dim
self.end_dim = end_dim
def forward(self, input: Tensor) -> ... |
def read_json(fn):
try:
with open(fn, 'r', encoding='utf-8') as f:
return json.load(f)
except Exception as e:
raise sb.errors.SmartBugsError(e) |
class VideoRetrievalCollator(object):
def __init__(self, tokenizer, max_length=40):
self.tokenizer = tokenizer
self.max_length = max_length
def collate_batch(self, batch):
v_collate = default_collate
visual_inputs = v_collate([d['vid'] for d in batch])
text_examples = fla... |
def convert_bn2affine_model(module, process_group=None, channel_last=False, merge=True):
mod = module
if (isinstance(module, torch.nn.modules.batchnorm._BatchNorm) and (not isinstance(module, ops.MixtureBatchNorm2d))):
mod = ops.AffineChannel2d(module.num_features)
mod.weight.data = module.weigh... |
def _cross_entropy_pytorch(logits, target, ignore_index=None, reduction='mean'):
lprobs = F.log_softmax(logits, dim=(- 1), dtype=torch.float32)
return F.nll_loss(lprobs, target, ignore_index=ignore_index, reduction=reduction) |
def _make_balanced_sampler(labels):
class_counts = np.bincount(labels)
class_weights = (1.0 / class_counts)
weights = class_weights[labels]
return WeightedRandomSampler(weights, len(weights)) |
def exists(S, P):
for x in S:
if P(x):
return (True, x)
return (False, None) |
class Parser(ABC):
def parse_aggregation_answer(self, states: List[Dict], texts: List[str]) -> Union[(Dict, List[Dict])]:
pass
def parse_improve_answer(self, state: Dict, texts: List[str]) -> Dict:
pass
def parse_generate_answer(self, state: Dict, texts: List[str]) -> List[Dict]:
pas... |
class Differential_multigraded(Differential):
def __init__(self, A, im_gens):
Differential.__init__(self, A, im_gens)
diff_deg = []
for x in A.gens():
y = self(x)
if (y != 0):
diff_deg.append((y.degree() - x.degree()))
if (len(set(diff_deg)) > ... |
def get_large_hourglass_net(num_layers, heads, head_conv):
model = HourglassNet(heads, 2)
return model |
class GumbelSoftmax(nn.Module):
def __init__(self, ste=False, log_softmax_enable: bool=True, eps: float=1e-06):
super(GumbelSoftmax, self).__init__()
self.eps = eps
self.u = Uniform(0, 1)
self.softmax = nn.Softmax(dim=(- 1))
self.log_softmax_enable = log_softmax_enable
... |
_toolkit()
class Amazon(FunctionToolkit):
name_for_human = 'Amazon'
description_for_human = 'Toolkit for common online shopping tasks on Amazon.'
name_for_model = 'Amazon'
description_for_model = 'An Amazon toolkit to perform common online shopping tasks like searching for products, viewing product deta... |
_model
def swsl_resnet50(pretrained=True, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
model.default_cfg = default_cfgs['swsl_resnet50']
if pretrained:
load_pretrained(model, num_classes=kwargs.get('num_classes', 0), in_chans=kwargs.get('in_chans', 3))
return model |
class BaseFeatureExtractor(nn.Module):
def forward(self, *input):
pass
def __init__(self):
super(BaseFeatureExtractor, self).__init__()
def output_num(self):
pass |
def get_pk_from_identity(obj):
key = identity_key(instance=obj)[1]
return ':'.join((text_type(x) for x in key)) |
def load_url(url, model_dir='~/.torch/proxyless_nas', map_location=None):
cached_file = download_url(url, model_dir)
map_location = ('cpu' if ((not torch.cuda.is_available()) and (map_location is None)) else None)
return torch.load(cached_file, map_location=map_location) |
class NumberedListState(Enum):
NO_NUM = 0
CONSECUTIVE = 1
DOWN = 2
UP = 3
UNKNOWN = 4 |
def eval_vehicle_id_(model, valid_loader, query_length, cfg):
metric = Clck_R1_mAP(query_length, max_rank=cfg.test.max_rank, rerank=cfg.test.rerank, remove_junk=cfg.test.remove_junk, feat_norm=cfg.test.feat_norm, output_path=cfg.output_dir, lambda_=cfg.test.lambda_)
model.eval()
with torch.no_grad():
... |
def build_loss(opt):
opt = deepcopy(opt)
loss_type = opt.pop('type')
loss = LOSS_REGISTRY.get(loss_type)(**opt)
logger = get_root_logger()
logger.info(f'Loss [{loss.__class__.__name__}] is created.')
return loss |
def read_hdf5(filepath, key='tensor', efficient=False):
assert os.path.exists(filepath), ('file %s not found' % filepath)
if efficient:
h5f = h5py.File(filepath, 'r')
assert (key in [key for key in h5f.keys()]), ('key %s does not exist in %s with keys %s' % (key, filepath, ', '.join(h5f.keys()))... |
class TestCaffe2Backend(unittest.TestCase):
('test broken because Lapack was always missing.')
def test_helper(self):
class SuperResolutionNet(nn.Module):
def __init__(self, upscale_factor, inplace=False):
super(SuperResolutionNet, self).__init__()
self.relu =... |
def main():
from autopipe.autopipe.api import build_profiled_graph
import torch
from torch.nn import Sequential, Linear
IN_FEATURES = 320
OUT_FEATURES = 8
n_encoder_decoder = 12
l = []
for i in range(n_encoder_decoder):
l.append(Linear(IN_FEATURES, IN_FEATURES))
l.append(Line... |
def hook_layernorm(m, x, y):
num_ele = y.numel()
flops = (2 * num_ele)
if m.elementwise_affine:
flops += (2 * num_ele)
return int(flops) |
def _wait_n_rounds(collection):
n = 0
for _ in range(RETRIES):
query = {'type': 'INFERENCE'}
n = collection.count_documents(query)
if (n == N_CLIENTS):
return n
_eprint(f'Succeded cleints {n}. Sleeping for {SLEEP}.')
sleep(SLEEP)
_eprint(f'Succeded clients... |
class QResult():
def __init__(self, name):
self._result = defaultdict(list)
self._name = name
self._recorder_paths = []
self._date2ICs = []
def append(self, key, value):
self._result[key].append(value)
def append_path(self, xpath):
self._recorder_paths.append(... |
def test_stats(model, X, Y, cutoff=None, fpr=None):
x_test_tensor = torch.from_numpy(X).float()
y_test_tensor = torch.from_numpy(Y).float()
test_data = TensorDataset(x_test_tensor, y_test_tensor)
test_loader = DataLoader(dataset=test_data, batch_size=args.size, shuffle=True)
all_preds = []
all_y... |
def buildcallback(rout, um):
global cb_map
from . import capi_maps
outmess(('\tConstructing call-back function "cb_%s_in_%s"\n' % (rout['name'], um)))
(args, depargs) = getargs(rout)
capi_maps.depargs = depargs
var = rout['vars']
vrd = capi_maps.cb_routsign2map(rout, um)
rd = dictappend(... |
def get_nmnist(data_path, network_config):
n_steps = network_config['n_steps']
batch_size = network_config['batch_size']
print('loading NMNIST')
if (not os.path.exists(data_path)):
os.mkdir(data_path)
train_path = (data_path + '/Train')
test_path = (data_path + '/Test')
trainset = NM... |
def sauvola(img, window_size=WS_SAUVOLA):
th = threshold_sauvola(img, window_size)
bin_img = (img > th)
return bin_img |
('detection', 'ets', ETSDetectorParams)
class ETSDetector(AnomalyDetectionAlgo):
def __init__(self, params: ETSDetectorParams):
ets_config = ETSDetectorConfig(max_forecast_steps=params.max_forecast_steps, target_seq_index=params.target_seq_index, error=params.error, trend=params.trend, damped_trend=params.d... |
def cross_entropy2d(input, target, weight=None, size_average=True):
(n, c, h, w) = input.size()
if (LooseVersion(torch.__version__) < LooseVersion('0.3')):
log_p = F.log_softmax(input)
else:
log_p = F.log_softmax(input, dim=1)
log_p = log_p.transpose(1, 2).transpose(2, 3).contiguous()
... |
def createInstanceImage(annotation, encoding):
size = (annotation.imgWidth, annotation.imgHeight)
if (encoding == 'ids'):
backgroundId = name2label['unlabeled'].id
elif (encoding == 'trainIds'):
backgroundId = name2label['unlabeled'].trainId
else:
print("Unknown encoding '{}'".fo... |
def makeStubAsWithHosts(emu: Emulator, base: Base, asn: int, exchange: int, hosts_total: int):
network = 'net0'
stub_as = base.createAutonomousSystem(asn)
stub_as.createNetwork(network)
router = stub_as.createRouter('router0')
router.joinNetwork(network)
router.joinNetwork('ix{}'.format(exchange... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.