code stringlengths 101 5.91M |
|---|
def eval(configs):
print('Evaluate')
statistics_file = os.path.join(BASE_PATH, 'stats.json')
if os.path.exists(statistics_file):
print('Statistics file already exists!')
return statistics_file
import common.utils as utils
import pyrenderer
from volnet.inference import LoadedModel... |
def convert_to_execution_order(sql, schema):
ast = parse(sql)
eo_sql = format(ast, schema, in_execution_order=True)
return eo_sql |
class G_D(nn.Module):
def __init__(self, G, D):
super(G_D, self).__init__()
self.G = G
self.D = D
def forward(self, z, gy, x=None, dy=None, train_G=False, return_G_z=False, policy=False, CR=False, CR_augment=None):
if (z is not None):
with torch.set_grad_enabled(train... |
def GenerateSM80_SparseTensorOp_16832(manifest, args):
if (not CudaToolkitVersionSatisfies(args.cuda_version, 11, 1)):
return
layouts = [(LayoutType.ColumnMajor, LayoutType.ColumnMajor, LayoutType.RowMajor), (LayoutType.ColumnMajor, LayoutType.RowMajor, LayoutType.RowMajor), (LayoutType.RowMajor, Layout... |
def _padded_batch(example_ds, batch_size, shapes, drop_remainder=False):
padded_shapes = {}
padded_shapes['observation'] = {}
for (k, v) in shapes.items():
if ('observation' in k):
padded_shapes['observation'][k.replace('observation/', '')] = (((- 1),) + v)
else:
padd... |
class Adamax(Optimizer):
def __init__(self, params, lr=required, warmup=(- 1), t_total=(- 1), schedule='warmup_linear', b1=0.9, b2=0.999, e=1e-08, weight_decay=0, max_grad_norm=1.0, **kwargs):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= ... |
def patch_deprecated_methods(env):
global warn_once
if warn_once:
logger.warn(("Environment '%s' has deprecated methods '_step' and '_reset' rather than 'step' and 'reset'. Compatibility code invoked. Set _gym_disable_underscore_compat = True to disable this behavior." % str(type(env))))
warn_on... |
def make_y_lmdb_from_yuv(video_path_list, index_frame_list, key_list, lmdb_path, yuv_type='420p', h=None, w=None, batch=7000, compress_level=1, multiprocessing_read=False, map_size=None):
assert lmdb_path.endswith('.lmdb'), "lmdb_path must end with '.lmdb'."
assert (not op.exists(lmdb_path)), f'Folder {lmdb_pat... |
def register_Ns3LteRrcSapMeasObjectToAddMod_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::LteRrcSap::MeasObjectToAddMod const &', 'arg0')])
cls.add_instance_attribute('measObjectEutra', 'ns3::LteRrcSap::MeasObjectEutra', is_const=False)
cls.add_instance_attribute('m... |
class SubmoduleWithBasis(CombinatorialFreeModule):
def __classcall_private__(cls, basis, support_order, ambient=None, unitriangular=False, category=None, *args, **opts):
basis = Family(basis)
if (ambient is None):
ambient = basis.an_element().parent()
Mod = ModulesWithBasis(ambie... |
class Pool2dBenchmark(op_bench.TorchBenchmarkBase):
def init(self, kernel, stride, N, C, H, W, device, op_func):
self.input = torch.rand(N, C, H, W, device=device)
self.kernel = kernel
self.stride = stride
self.op_func = op_func(self.kernel, stride=self.stride)
def forward(self):... |
def better_exchook(etype, value, tb, debugshell=False, autodebugshell=True, file=None, with_color=None, with_preamble=True):
if (file is None):
file = sys.stderr
color = Color(enable=with_color)
output = _OutputLinesCollector(color=color)
rec_args = dict(autodebugshell=False, file=file, with_col... |
class Block_ViT_cross(nn.Module):
def __init__(self, config, vis, channel_num):
super(Block_ViT_cross, self).__init__()
self.attn_normQ = LayerNorm(channel_num[4], eps=1e-06)
self.attn_normKV = LayerNorm(config.KV_sizec, eps=1e-06)
self.channel_attn = Attention_org_cross(config, vis,... |
def simRMLVel(dofs, smallestTimeStep, flags, currentPosVelAccel, maxAccelJerk, selection, targetVel):
handle = lib.simRMLVel(dofs, smallestTimeStep, flags, currentPosVelAccel, maxAccelJerk, selection, targetVel, ffi.NULL)
_check_return(handle)
return handle |
def test_count_message_tokens_invalid_model():
messages = [Message('user', 'Hello'), Message('assistant', 'Hi there!')]
with pytest.raises(NotImplementedError):
count_message_tokens(messages, model='invalid_model') |
class TestBundledInputs(TestCase):
def test_single_tensors(self):
class SingleTensorModel(torch.nn.Module):
def forward(self, arg):
return arg
im = cv2.imread('caffe2/test/test_img/p1.jpg')
tensor = torch.from_numpy(im)
inflatable_arg = bundle_jpeg_image(t... |
.parametrize('data_dict', [pytest.param('full_spark_dataset', marks=pytest.mark.spark), pytest.param('full_pandas_dataset', marks=pytest.mark.core)])
def test_feature_schema_schema_interaction_features(data_dict, request):
dataset = create_dataset(request.getfixturevalue(data_dict))
assert (dataset.feature_sche... |
class SentenceRepresentation():
def __init__(self, corpus):
self.corpus = corpus
def get_instance(cls, corpus):
return cls(corpus)
def _get_sents_with_representations(self):
(sents, sents_vec) = ([], [])
for doc in self.corpus:
for sent in doc:
sen... |
class SingleSubprocVecEnv2(VecEnv):
def __init__(self, env_fns, spaces=None):
self.waiting = False
self.closed = False
nenvs = len(env_fns)
(self.remotes, self.work_remotes) = zip(*[Pipe() for _ in range(nenvs)])
self.ps = [Process(target=worker2_single, args=(work_remote, re... |
('tasks.implementations.dataset_check_version.Project.repository')
class TestVersionCheckTask():
def setup(self):
self.uut = VersionCheckTask()
self.uut._report_missing_key = MagicMock()
def test_missing_revision(self, _):
meta = {'misuses': ['1']}
project = create_project('-proj... |
class BaseDataset(object):
def get_imagedata_info(self, data):
(pids, cams) = ([], [])
for (_, pid, camid) in data:
pids += [pid]
cams += [camid]
pids = set(pids)
cams = set(cams)
num_pids = len(pids)
num_cams = len(cams)
num_imgs = len... |
def extract_sdae_coil100(slope=0.0, dim=10):
return extractSDAE(dim=[49152, 500, 500, 2000, dim], slope=slope) |
class ExtCNNDMLoader(JsonLoader):
def __init__(self, fields=None):
fields = (fields or {'text': None, 'summary': None, 'label': None, 'publication': None})
super(ExtCNNDMLoader, self).__init__(fields=fields)
def load(self, paths: Union[(str, Dict[(str, str)])]=None):
if (paths is None):
... |
def load_dataset(norm_flag=True):
imgX = sio.loadmat('river/river_before.mat')['river_before']
imgY = sio.loadmat('river/river_after.mat')['river_after']
imgX = np.reshape(imgX, newshape=[(- 1), imgX.shape[(- 1)]])
imgY = np.reshape(imgY, newshape=[(- 1), imgY.shape[(- 1)]])
GT = sio.loadmat('river/... |
def has_vector_accessnode(inf: vector_inference.VectorInferenceGraph):
for (node, _) in inf.sdfg.start_state.all_nodes_recursive():
if (isinstance(node, nodes.AccessNode) and isinstance(node.desc(inf.sdfg), data.Scalar)):
return (inf.get_constraint(node) == vector_inference.InferenceNode.Vector)... |
def merge_list_of_dicts(L):
result = {}
for d in L:
result.update(d)
return result |
def current_stream():
_lazy_init()
return torch.cuda.Stream(_cdata=torch._C._cuda_getCurrentStream()) |
def get_site_dirs():
sitedirs = []
sitedirs.extend(_pythonpath())
prefixes = [sys.prefix]
if (sys.exec_prefix != sys.prefix):
prefixes.append(sys.exec_prefix)
for prefix in prefixes:
if prefix:
if (sys.platform in ('os2emx', 'riscos')):
sitedirs.append(os.... |
class FairseqDataclass():
_name: Optional[str] = None
def name():
return None
def _get_all_attributes(self) -> List[str]:
return [k for k in self.__dataclass_fields__.keys()]
def _get_meta(self, attribute_name: str, meta: str, default: Optional[Any]=None) -> Any:
return self.__da... |
def rmsprop(opfunc, x, config, state=None):
if ((config is None) and (state is None)):
raise ValueError('rmsprop requires a dictionary to retain state between iterations')
state = (state if (state is not None) else config)
lr = config.get('learningRate', 0.01)
alpha = config.get('alpha', 0.99)
... |
class ReconstructionErrorsTest(TestCase):
y = np.array([[[0.0], [0.1]], [[1.0], [0.5]], [[0.1], [0.1]], [[0.0], [0.5]]])
y_hat = np.array([[[0.1], [2.0]], [[0.5], [0.0]], [[3.0], [0.1]], [[5.0], [0.5]]])
STEP_SIZE = 1
def _run(self, score_window, smoothing_window, smooth, rec_error_type, expected):
... |
def test_invalid_parameters_in_stacking():
stacker = StackingClassifier(estimators=[])
html_output = estimator_html_repr(stacker)
assert (html.escape(str(stacker)) in html_output) |
def get_lm_pipeline(model: PreTrainedModel):
model_class = model.__class__.__name__
if (model_class == 'LlamaForCausalLM'):
return nn.Sequential(model.model.norm, model.lm_head)
elif (model_class == 'RWForCausalLM'):
return nn.Sequential(model.transformer.ln_f, model.lm_head)
elif (model... |
def validate_map_location(map_location=None):
if isinstance(map_location, str):
map_location = torch.device(map_location)
elif (not ((map_location is None) or isinstance(map_location, torch.device))):
raise ValueError(('map_location should be either None, string or torch.device, but got type: ' ... |
def main():
p = argparse.ArgumentParser(description=main.__doc__)
p.add_argument('catlas_prefix', help='catlas prefix')
p.add_argument('mh_index_picklefile', help='pickled hashval index')
p.add_argument('lca_db')
args = p.parse_args()
catlas = CAtlas(args.catlas_prefix, load_sizefile=True)
n... |
def load_img_future_de_snow_kitti(filepath, nFrames, img_id, phase='train'):
tt = int((nFrames / 2))
img_id = (img_id + tt)
num_dir = filepath.split('/')[3]
if (phase == 'train'):
targetPath = ('Dataset/KITTI_snow/Train_GT/' + num_dir)
else:
targetPath = ('Dataset/KITTI_snow/Test_GT/... |
class ParaphraseGenerator():
def __init__(self, device='cuda'):
self._device = device
self._tokenizer = AutoTokenizer.from_pretrained('Vamsi/T5_Paraphrase_Paws')
self._model = AutoModelForSeq2SeqLM.from_pretrained('Vamsi/T5_Paraphrase_Paws').to(self._device)
def generate_sent(self, input... |
def num_ifs_loops(graph):
graph_str = str(graph)
graph_body = graph_str[0:graph_str.find('return')]
return (graph_body.count('prim::Loop') + graph_body.count('prim::If')) |
def _get_cache_dir(req, wheel_cache):
cache_available = bool(wheel_cache.cache_dir)
assert req.link
if (cache_available and _should_cache(req)):
cache_dir = wheel_cache.get_path_for_link(req.link)
else:
cache_dir = wheel_cache.get_ephem_path_for_link(req.link)
return cache_dir |
class DisplayLatexMessagePassing(MessagePassing):
def __init__(self, model):
model.init_shapes()
super().__init__(model, message_keys=['a', 'b'])
def forward(self, node, message):
m = format_latex_message(message, 'incoming')
new_message = node.forward_message(message)
m ... |
class ImagesDataset(Dataset):
def __init__(self, source_root, target_root, opts, target_transform=None, source_transform=None):
self.source_paths = sorted(data_utils.make_dataset(source_root))
self.target_paths = sorted(data_utils.make_dataset(target_root))
self.source_transform = source_tra... |
def collect_results_cpu(result_part, size, tmpdir=None):
(rank, world_size) = get_dist_info()
if (tmpdir is None):
MAX_LEN = 512
dir_tensor = torch.full((MAX_LEN,), 32, dtype=torch.uint8, device='cuda')
if (rank == 0):
os.makedirs('.dist_test', exist_ok=True)
tmpd... |
def load_dataset_example(format, name, dataset_dir):
dataset_dir = '{}/{}'.format(dataset_dir, name)
if (format == 'PyG'):
if (name == 'QM7b'):
dataset_raw = QM7b(dataset_dir)
graphs = GraphDataset.pyg_to_graphs(dataset_raw)
return graphs |
def test_floor():
x = Symbol('x')
y = Symbol('y')
assert (floor(nan) == nan)
assert (floor(oo) == oo)
assert (floor((- oo)) == (- oo))
assert (floor(0) == 0)
assert (floor(1) == 1)
assert (floor((- 1)) == (- 1))
assert (floor(E) == 2)
assert (floor(pi) == 3)
assert (floor(Rat... |
class RegexMatch(NgramMatcher):
def init(self):
try:
self.rgx = self.opts['rgx']
except KeyError:
raise Exception('Please supply a regular expression string r as rgx=r.')
self.ignore_case = self.opts.get('ignore_case', True)
self.attrib = self.opts.get('attrib... |
def rounddict(d: Dict[(Any, float)], x=2):
return {k: round(number=v, ndigits=x) for (k, v) in d.items()} |
def test_array_api_deprecations():
X = sp.sparse.csr_array([[1, 2, 3], [4, 0, 6]])
msg = '1.13.0'
with pytest.deprecated_call(match=msg):
X.get_shape()
with pytest.deprecated_call(match=msg):
X.set_shape((2, 3))
with pytest.deprecated_call(match=msg):
X.asfptype()
with py... |
def as_numpy(obj):
if isinstance(obj, collections.Sequence):
return [as_numpy(v) for v in obj]
elif isinstance(obj, collections.Mapping):
return {k: as_numpy(v) for (k, v) in obj.items()}
elif isinstance(obj, Variable):
return obj.data.cpu().numpy()
elif torch.is_tensor(obj):
... |
def simple_seg(hans):
assert (not isinstance(hans, bytes_type)), 'must be unicode string or [unicode, ...] list'
if isinstance(hans, text_type):
return _seg(hans)
else:
hans = list(hans)
if (len(hans) == 1):
return simple_seg(hans[0])
return list(chain(*[simple_se... |
def fetch(data_filename):
try:
return _fetch(data_filename)
except (ConnectionError, ModuleNotFoundError):
pytest.skip(f'Unable to download {data_filename}', allow_module_level=True) |
.parametrize('dumb_samplers', [True, False])
def test_parallel_thompson_sampling_builder_raises_when_update_with_wrong_function(dumb_samplers: bool) -> None:
x_range = tf.linspace(0.0, 1.0, 5)
x_range = tf.cast(x_range, dtype=tf.float64)
xs = tf.reshape(tf.stack(tf.meshgrid(x_range, x_range, indexing='ij'),... |
def test_no_feature_flag_raises_error():
with config_context(enable_metadata_routing=False):
with pytest.raises(RuntimeError, match='This method is only available'):
ConsumingClassifier().set_fit_request(sample_weight=True) |
class GCL_skip(nn.Module):
def __init__(self, g, f, in_feats, out_feats, activation, dropout, bias=True):
super(GCL_skip, self).__init__()
self.g = g
self.f = f
self.wh = nn.Parameter(torch.Tensor(in_feats, out_feats))
self.ws = nn.Parameter(torch.Tensor(out_feats, out_feats)... |
def _transformList(l):
ret = np.empty(len(l), dtype=np.object)
for (i, arr) in enumerate(l):
ret[i] = arr
return ret |
def inference_context(model):
training_mode = model.training
model.eval()
(yield)
model.train(training_mode) |
(Output('select-causal-method', 'options'), Input('select-causal-method-parent', 'n_clicks'))
def update_method_dropdown(n_clicks):
options = []
ctx = dash.callback_context
prop_id = ctx.triggered_id
if (prop_id == 'select-causal-method-parent'):
methods = sorted(causal_method.get_supported_meth... |
class DataConfig():
def __init__(self, defaults={}):
super(DataConfig, self).__init__()
self.defaults = defaults
def apply(self, args):
if (torch.distributed.get_rank() == 0):
print('configuring data')
self.apply_defaults(args)
return make_loaders(args)
de... |
def render_missing_impact(itmdt: Intermediate, cfg: Config) -> Dict[(str, Any)]:
plot_width = (cfg.plot.width if (cfg.plot.width is not None) else 500)
plot_height = (cfg.plot.height if (cfg.plot.height is not None) else 500)
tabs: List[Panel] = []
htgs: Dict[(str, List[Tuple[(str, str)]])] = {}
if ... |
def _bfs_relational(adj, roots, max_nodes_per_hop=None):
visited = set()
current_lvl = set(roots)
next_lvl = set()
while current_lvl:
for v in current_lvl:
visited.add(v)
next_lvl = _get_neighbors(adj, current_lvl)
next_lvl -= visited
if (max_nodes_per_hop and... |
class AutoModelForMaskedImageModeling(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_mixed_none_2d_local():
result = ak.argsort([[None, 1, None, 0, None, None, (- 1)], None, [None, 2, None, 2, 0, None, (- 2)]], axis=1)
assert ak.is_valid(result)
assert (result.to_list() == [[6, 3, 1, 0, 2, 4, 5], None, [6, 4, 1, 3, 0, 2, 5]])
assert (result.type == ak.types.ArrayType(ak.types.O... |
.parametrize('whiten', ['arbitrary-variance', 'unit-variance', False])
.parametrize('return_X_mean', [True, False])
.parametrize('return_n_iter', [True, False])
def test_fastica_output_shape(whiten, return_X_mean, return_n_iter):
n_features = 3
n_samples = 10
rng = np.random.RandomState(0)
X = rng.rando... |
class ConvolutionalComponent(tf.keras.Model):
def __init__(self, channels, kernels, strides, name='ConvolutionalComponent', **kwargs):
super().__init__(name=name, **kwargs)
self.channels = channels
self.kernels = kernels
self.strides = strides
self.num_of_nets = (len(self.cha... |
class ResConvBlock(ConvBlock):
def forward(self, x):
dx = self.conv_block(x)
return (x + dx) |
class Conv1dGLU(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, dropout):
super(Conv1dGLU, self).__init__()
self.out_channels = out_channels
self.conv1 = nn.Conv1d(in_channels, (2 * out_channels), kernel_size=kernel_size, padding=2)
self.dropout = nn.Dropout(dr... |
def isclose(a, b, rel_tol=1e-09, abs_tol=0.0, method='weak'):
if (method not in ('asymmetric', 'strong', 'weak', 'average')):
raise ValueError('method must be one of: "asymmetric", "strong", "weak", "average"')
if ((rel_tol < 0.0) or (abs_tol < 0.0)):
raise ValueError('error tolerances must be n... |
def __get_by_pos(candidates, pos):
for mention in candidates:
if (mention.attributes['type'] == pos):
return mention |
def convert_links(links_by_name):
all_converted = {}
for (name, links) in links_by_name.iteritems():
converted = []
for l in links:
relation_name = convert_name(l[2])
converted.append((l[0], l[1], relation_name))
all_converted[name] = converted
return all_conv... |
def smtpNotifier(to, subject, body):
sender = to
receivers = [to]
message = f'''From: <{to}>
To: {to} <{to}>
Subject: {subject}
{body}
'''
try:
smtpObj = smtplib.SMTP('localhost')
smtpObj.sendmail(sender, receivers, message)
print(f'Successfully notified to {to}')
except smt... |
def rec_get_const_div_inv(expr: Expression, desc_ctx: LeanDescContext) -> List[Tuple[(str, int, bool)]]:
if isinstance(expr, ExprNeg):
return rec_get_const_div_inv(expr.val, desc_ctx)
if isinstance(expr, ExprCast):
return rec_get_const_div_inv(expr.expr, desc_ctx)
if isinstance(expr, ExprOpe... |
class TestImitationLoss(TestCase):
def _fake_tensors(self):
return {'output_actions': tf.random_uniform((BATCH, 2, ACTION_SIZE)), 'ctrnet_outputs': tf.random_uniform((BATCH, 2, ACTION_SIZE))}
def test_float_outputs(self):
il = ImitationLoss()
with tf.variable_scope('test_float_outputs'):... |
def embed_model_spatio_temporal_gcnn(n_neuron, timesteps, num_nodes, num_features, graph_conv_filters_shape1, graph_conv_filters_shape2, num_filters, num_classes, n_dropout, protocol):
i3d = i3d_modified(weights='rgb_imagenet_and_kinetics')
model_branch = i3d.i3d_flattened(num_classes=num_classes)
optim = S... |
class AttrDict(dict):
__setattr__ = dict.__setitem__
def __getattribute__(self, item):
if (item in self):
return self[item]
else:
return super().__getattribute__(item) |
def is_hf_dataset(dataset):
if (not is_datasets_available()):
return False
from datasets import Dataset, IterableDataset
return isinstance(dataset, (Dataset, IterableDataset)) |
def test_config_hdf(hdf_file_path, tardis_config_verysimple):
expected = Configuration.from_config_dict(tardis_config_verysimple, validate=True, config_dirname='test')
expected.to_hdf(hdf_file_path, overwrite=True)
actual = pd.read_hdf(hdf_file_path, key='/simulation/config')
expected = expected.get_pro... |
def random_swap(words, n):
new_words = words.copy()
for _ in range(n):
new_words = swap_word(new_words)
return new_words |
class DummyMortalityOntology():
def get_children(self, code: str) -> List[str]:
if (code == 'SNOMED/'):
return ['DEATH_CHILD']
return [] |
_builder('ok_vqa_instruct')
class OKVQAInstructBuilder(COCOVQAInstructBuilder):
DATASET_CONFIG_DICT = {'default': 'configs/datasets/okvqa/defaults_instruct.yaml'} |
.parametrize('param,min_feature,value', [(parametrization.GratingParam([1, 2, 5, 6.7], 10), 1.5, [[1, (- 1), 0, 0], [0, 1, (- 1), 0], [0, 0, 1, (- 1)], [(- 1), 0, 0, 0], [0, 0, 0, 1]]), (parametrization.CompositeParam([parametrization.GratingParam([1, 2, 5, 6.7], 10), parametrization.GratingParam([3, 4], 8)]), 1.5, [[1... |
def spearman(x, y):
assert (len(x) == len(y) > 0)
q = (lambda n: map((lambda val: (sorted(n).index(val) + 1)), n))
d = sum(map((lambda x, y: ((x - y) ** 2)), q(x), q(y)))
return (1.0 - ((6.0 * d) / float((len(x) * ((len(y) ** 2) - 1.0))))) |
class FlowDensity(mrl.Module):
def __init__(self, item, optimize_every=2, batch_size=1000, lr=0.001, num_layer_pairs=3, normalize=True):
super().__init__('{}_flow'.format(item), required_agent_modules=['replay_buffer'], locals=locals())
self.step = 0
self.item = item
self.num_layer_p... |
def get_devices(devices=None):
if (not torch.cuda.is_available()):
return [torch.device('cpu')]
if (not devices):
return [torch.device(('cuda:' + str(i))) for i in range(torch.cuda.device_count())]
return [torch.device(ordinal) for ordinal in devices] |
def block_inception_b(inputs, scope=None, reuse=None):
with slim.arg_scope([slim.conv2d, slim.avg_pool2d, slim.max_pool2d], stride=1, padding='SAME'):
with tf.variable_scope(scope, 'BlockInceptionB', [inputs], reuse=reuse):
with tf.variable_scope('Branch_0'):
branch_0 = slim.conv... |
class SingleTablePreset():
_synthesizer = None
_default_synthesizer = GaussianCopulaSynthesizer
def _setup_fast_preset(self, metadata, locales):
self._synthesizer = GaussianCopulaSynthesizer(metadata=metadata, default_distribution='norm', enforce_rounding=False, locales=locales)
def __init__(sel... |
def generate_case_from_nntxt_str(nntxt_str, nnp_filename, param_format, dataset_sample_num, batch_size=None):
proto = proto_from_str(nntxt_str)
with generate_csv_png(dataset_sample_num, get_input_size(proto)) as dataset_csv_file:
for ds in proto.dataset:
ds.batch_size = (batch_size if batch_... |
def mkdir_list(p_list, use_relative_path=True, log=True):
root_path = os.path.abspath(os.path.dirname(__file__)).split('utils')[0]
p_list = (p_list if isinstance(p_list, list) else [p_list])
for p in p_list:
p = (os.path.join(root_path, p) if use_relative_path else p)
p = get_dir_of_file(p)
... |
def generate_targets(org_bboxes, p_c, p_e, motion_parameters):
(track_num, _, _) = motion_parameters.shape
target = [org_bboxes, motion_parameters, p_c, p_e]
return target |
def parse_args():
parser = argparse.ArgumentParser(description='Med VQA')
parser.add_argument('--cfg', help='decide which cfg to use', required=False, default='/home/test.yaml', type=str)
parser.add_argument('--gpu', type=int, default=0, help='use gpu device. default:0')
parser.add_argument('--test', ty... |
def convert_dataset_for_tensorflow(dataset, non_label_column_names, batch_size, dataset_mode='variable_batch', shuffle=True, drop_remainder=True):
def densify_ragged_batch(features, label=None):
features = {feature: ragged_tensor.to_tensor(shape=batch_shape[feature]) for (feature, ragged_tensor) in features... |
def process_json_file(json_file_path, src_dir, ori_dst_dir, binary_dst_dir, instance_dst_dir):
assert ops.exists(json_file_path), '{:s} not exist'.format(json_file_path)
image_nums = len(os.listdir(ori_dst_dir))
count_unlabeled = 0
with open(json_file_path, 'r') as file:
for (line_index, line) i... |
def load_categories_from_csv_file(csv_path):
categories = []
with tf.gfile.Open(csv_path, 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
if (not row):
continue
if (len(row) != 2):
raise ValueE... |
class IntegerAttribute(AbstractAttribute):
def __init__(self, name, data, histogram_size):
super().__init__(name, data, histogram_size)
self.is_categorical = False
self.is_numerical = True
self.data_type = DataType.INTEGER
self.data = self.data.astype(int)
self.data_d... |
_torch
_sigopt
class TrainerHyperParameterSigOptIntegrationTest(unittest.TestCase):
def setUp(self):
args = TrainingArguments('.')
self.n_epochs = args.num_train_epochs
self.batch_size = args.train_batch_size
def test_hyperparameter_search(self):
class MyTrialShortNamer(TrialShor... |
def diffusion_defaults():
return dict(learn_sigma=False, diffusion_steps=1000, noise_schedule='linear', timestep_respacing='', use_kl=False, predict_xstart=False, rescale_timesteps=False, rescale_learned_sigmas=False) |
def parse_uri(uri):
groups = URI.match(uri).groups()
return (groups[1], groups[3], groups[4], groups[6], groups[8]) |
def test_random_single_image():
shap.image_plot(np.random.randn(3, 20, 20), np.random.randn(3, 20, 20), show=False) |
def weakly_connected_component(dfg, node_in_component: Node) -> StateSubgraphView:
seen = set()
to_search = [node_in_component]
while to_search:
node = to_search.pop()
if (node in seen):
continue
seen.add(node)
for succ in dfg.successors(node):
to_sear... |
_numpy_output()
def test_transpose3(A: dace.float32[(M, N, N, M)]):
return A.transpose(3, 0, 2, 1) |
def load_model(load_path, e_common, e_separate_A, e_separate_B, decoder, ae_opt, disc, disc_opt):
state = torch.load(load_path)
e_common.load_state_dict(state['e_common'])
e_separate_A.load_state_dict(state['e_separate_A'])
e_separate_B.load_state_dict(state['e_separate_B'])
decoder.load_state_dict(... |
_module
class IterTimerHook(Hook):
def before_epoch(self, runner):
self.t = time.time()
def before_iter(self, runner):
runner.log_buffer.update({'data_time': (time.time() - self.t)})
def after_iter(self, runner):
runner.log_buffer.update({'time': (time.time() - self.t)})
self... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.