code stringlengths 101 5.91M |
|---|
def nn(input, layers_sizes, reuse=None, flatten=False, name=''):
for (i, size) in enumerate(layers_sizes):
activation = (tf.nn.relu if (i < (len(layers_sizes) - 1)) else None)
input = tf.compat.v1.layers.dense(inputs=input, units=size, kernel_initializer=tf.compat.v1.keras.initializers.VarianceScali... |
def p_comp_iter(s, body):
if (s.sy in ('for', 'async')):
return p_comp_for(s, body)
elif (s.sy == 'if'):
return p_comp_if(s, body)
else:
return body |
def evaluate(model, test_idxs):
model.eval()
batch_idx = 1
total_loss = 0
pred = torch.empty(config['batch_size'], 1).type(torch.LongTensor)
X_test = text_features[test_idxs]
Y_test = text_targets[test_idxs]
global max_train_acc, max_acc, max_f1
for i in range(0, X_test.shape[0], config[... |
def test_method_get_variable_references(method_mock, default_test_case):
float1 = stmt.FloatPrimitiveStatement(default_test_case, 5.0)
float2 = stmt.FloatPrimitiveStatement(default_test_case, 10.0)
meth = stmt.MethodStatement(default_test_case, method_mock, float2.ret_val, args={'test': float1.ret_val})
... |
def sanitize(x: Any) -> Any:
if isinstance(x, (str, float, int, bool)):
return x
elif isinstance(x, torch.autograd.Variable):
return sanitize(x.data)
elif isinstance(x, torch._TensorBase):
return x.cpu().tolist()
elif isinstance(x, numpy.ndarray):
return x.tolist()
el... |
class ThreeInterpolate(Function):
def forward(ctx, features, idx, weight):
ctx.save_for_backward(idx, weight, features)
return _ext.three_interpolate(features, idx, weight)
def backward(ctx, grad_out):
(idx, weight, features) = ctx.saved_tensors
m = features.size(2)
grad_... |
class DPRDoc_Retrieval():
def __init__(self, topk=100, model_type='ftwctx'):
if torch.cuda.is_available():
self.device = torch.device('cuda')
else:
self.device = torch.device('cpu')
self.topk = topk
self.model_type = model_type
self.q_tokenizer = DPRQu... |
class ARBatchSampler(Sampler):
def __init__(self, data_source, batch_size, drop_last=False, epoch=0):
super(ARBatchSampler, self).__init__(data_source)
self.data_source = data_source
self.batch_size = batch_size
self.drop_last = drop_last
self._epoch = epoch
self.img_... |
def OzaBaggingAdwin(base_estimator=KNNADWINClassifier(), n_estimators=10, random_state=None):
warnings.warn("'OzaBaggingAdwin' has been renamed to 'OzaBaggingADWINClassifier' in v0.5.0.\nThe old name will be removed in v0.7.0", category=FutureWarning)
return OzaBaggingADWINClassifier(base_estimator=base_estimat... |
class PipelineTestCaseMeta(type):
def __new__(mcs, name, bases, dct):
def gen_test(ModelClass, checkpoint, tiny_config, tokenizer_class, feature_extractor_class):
((tiny_config is None), 'TinyConfig does not exist')
((checkpoint is None), 'checkpoint does not exist')
def ... |
def pop_layer(model):
if (not model.outputs):
raise Exception('Sequential model cannot be popped: model is empty.')
model.layers.pop()
if (not model.layers):
model.outputs = []
model.inbound_nodes = []
model.outbound_nodes = []
else:
model.layers[(- 1)].outbound_n... |
def test_deepcopy():
class Nocopy(SDFGConvertible):
def __sdfg__(self, *args, **kwargs):
def bla(a: dace.float64[20]):
return a
return bla.to_sdfg()
def __sdfg_closure__(self, reevaluate=None):
return {}
def __sdfg_signature__(self):
... |
def _legal_action_mask(board_2d):
return jax.vmap(_can_slide_left)(jnp.array([board_2d, jnp.rot90(board_2d, 1), jnp.rot90(board_2d, 2), jnp.rot90(board_2d, 3)])) |
def test_get_data_for_tensorkey_locally(collaborator_mock, tensor_key):
tensor_key = tensor_key._replace(round_number=1)
nparray = numpy.array([0, 1, 2, 3, 4])
collaborator_mock.tensor_db.get_tensor_from_cache = mock.Mock(side_effect=[None, nparray])
ret = collaborator_mock.get_data_for_tensorkey(tensor... |
_sentencepiece
_torch
_pytesseract
class LayoutXLMProcessorIntegrationTests(unittest.TestCase):
_property
def get_images(self):
from datasets import load_dataset
ds = load_dataset('hf-internal-testing/fixtures_docvqa', split='test')
image_1 = Image.open(ds[0]['file']).convert('RGB')
... |
class _ComputeSim(torch.nn.Module):
def __init__(self):
super(_ComputeSim, self).__init__()
def forward(self, x1, x2):
assert (x1.ndim == 2), 'x1.ndim must be 2, but found {}.'.format(x1.ndim)
assert (x1.size()[0] == 1), 'x1.size[0] must be 1, but found {}.'.format(x1.size()[0])
... |
def main():
args = parse_args()
if (args is None):
exit()
with tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:
gan = StarGAN_v2(sess, args)
gan.build_model()
show_all_variables()
if (args.phase == 'train'):
gan.train()
pri... |
class mnist_model(nn.Module):
def __init__(self):
super(mnist_model, self).__init__()
self.layer1 = nn.Conv2d(1, 20, kernel_size=5, stride=1, padding=0)
self.layer2 = nn.Conv2d(20, 50, kernel_size=5, stride=1, padding=0)
self.layer3 = nn.Linear(800, 500, bias=True)
self.layer... |
def get_check_binary_allowed(format_control):
def check_binary_allowed(req):
if req.use_pep517:
return True
canonical_name = canonicalize_name(req.name)
allowed_formats = format_control.get_allowed_formats(canonical_name)
return ('binary' in allowed_formats)
return ch... |
def trainer_main(args):
if args.ignore_warnings:
warnings.filterwarnings('ignore')
Path(args.checkpoints_dir).mkdir(parents=True, exist_ok=True)
seed_everything(args.seed)
tokenizer = FSNERTokenizerUtils(args.pretrained_model)
train_data_dict = load_dataset((args.train_data if (args.mode == ... |
class GaussianMLPRegressor(LayersPowered, Serializable):
def __init__(self, name, input_shape, output_dim, mean_network=None, hidden_sizes=(32, 32), hidden_nonlinearity=tf.nn.tanh, optimizer=None, use_trust_region=True, step_size=0.01, learn_std=True, init_std=1.0, adaptive_std=False, std_share_network=False, std_h... |
def node_to_text(test, f):
(result, name, time_real) = read_test(test)
output = ('%s: Test Suite "%s" (%s)\n' % (result, name, time_real))
f.write(output)
for details in test.findall('FailureDetails'):
f.write(' Details:\n')
f.write((' Message: %s\n' % details.find('Message').t... |
def DeepR50V3PlusD(args, num_classes, criterion, criterion_aux):
print('Model : DeepLabv3+, Backbone : ResNet-50')
return DeepV3Plus(num_classes, trunk='resnet-50', criterion=criterion, criterion_aux=criterion_aux, variant='D16', skip='m1', args=args) |
def test_step_reward():
env = MetaMazeEnv()
obs = env.reset()
assert (obs == [1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0.0]).all()
env.reward_row_pos = env.reward_col_pos = 1
assert (env.row_pos == env.col_pos == 3)
(obs, reward, done, _) = env.step(2)
assert (obs == [0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1... |
class YelpFullLoader(CLSBaseLoader):
def download(self, dev_ratio: float=0.0, re_download: bool=False):
dataset_name = 'yelp-review-full'
data_dir = self._get_dataset_path(dataset_name=dataset_name)
data_dir = _split_dev(dataset_name=dataset_name, data_dir=data_dir, dev_ratio=dev_ratio, re_d... |
class UNet3DConditionModel(ModelMixin, ConfigMixin):
_supports_gradient_checkpointing = True
_to_config
def __init__(self, sample_size: Optional[int]=None, in_channels: int=4, out_channels: int=4, center_input_sample: bool=False, flip_sin_to_cos: bool=True, freq_shift: int=0, down_block_types: Tuple[str]=('... |
class CategoryRole(ColumnRole):
_name = 'Category'
def __init__(self, dtype: Dtype=object, encoding_type: str='auto', unknown: int=5, force_input: bool=False, label_encoded: bool=False, ordinal: bool=False):
self.dtype = dtype
self.encoding_type = encoding_type
self.unknown = unknown
... |
def get_data_iter(type, image_dir, batch_size, num_threads, device_id, num_gpus, crop, val_size=256, world_size=1, local_rank=0):
if (type == 'train'):
pip_train = HybridTrainPipe(batch_size=batch_size, num_threads=num_threads, device_id=local_rank, data_dir=image_dir, crop=crop, world_size=world_size, loca... |
def gelu(x: stk.Matrix):
assert isinstance(x, stk.Matrix)
return stk.Matrix(x.size(), F.gelu(x.data, approximate='tanh'), x.row_indices, x.column_indices, x.offsets, x.column_indices_t, x.offsets_t, x.block_offsets_t) |
def usage(progname):
sys.stderr.write((('usage: ' + progname) + ' num_pairs N\n'))
sys.stderr.write(' num_pairs is the number of node pairs to generate\n')
sys.stderr.write(' N is the number of nodes (so generates in [0..N-1])\n')
sys.exit(1) |
def build(session_file):
f = open(session_file, 'r')
query_freq = {}
total_freq = 0
for (num, session) in enumerate(f):
session = session.strip().split('\t')
for query in session:
query_freq[query] = (query_freq.get(query, 0.0) + 1.0)
total_freq += 1
if ((... |
class _TotalOrderingMixin(object):
__slots__ = ()
def __eq__(self, other):
raise NotImplementedError
def __ne__(self, other):
equal = self.__eq__(other)
if (equal is NotImplemented):
return NotImplemented
return (not equal)
def __lt__(self, other):
rai... |
def ResNet152(num_classes=10):
return ResNet(Bottleneck, layers=[3, 8, 36, 3], filters=[64, 128, 256, 512]) |
def assert_raises_fpe(strmatch, callable, *args, **kwargs):
try:
callable(*args, **kwargs)
except FloatingPointError as exc:
assert_((str(exc).find(strmatch) >= 0), ('Did not raise floating point %s error' % strmatch))
else:
assert_(False, ('Did not raise floating point %s error' % s... |
def dev():
if torch.cuda.is_available():
return torch.device(f'cuda')
return torch.device('cpu') |
(tryfirst=True)
def pytest_report_header(config):
if config._env_timeout:
return [('timeout: %ss\ntimeout func_only: %s' % (config._env_timeout, config._env_timeout_func_only))] |
class SUNDataLoader():
def __init__(self, data_path, device, is_scale=False, is_unsupervised_attr=False, is_balance=True):
print(data_path)
sys.path.append(data_path)
self.data_path = data_path
self.device = device
self.dataset = 'SUN'
print(('$' * 30))
print(... |
def SBM_snapshot(G_prev, alpha, sizes, probs):
G_t = G_prev.copy()
nodelist = list(range(0, sum(sizes)))
G_new = nx.stochastic_block_model(sizes, probs, nodelist=nodelist)
n = len(G_t)
if (alpha == 1.0):
return G_new
for i in range(0, n):
for j in range((i + 1), n):
p... |
class HighLevelContext():
def __init__(self, behavior: (Mapping | None)=None, attrs: (Mapping[(str, Any)] | None)=None):
self._behavior = behavior
self._attrs = attrs
self._is_finalized = False
self._attrs_from_objects = []
self._behavior_from_objects = []
def __enter__(s... |
def test_check_input5():
with pytest.raises(TypeError, match=('Please check you are using the right metric objects,' + ' or the right order of the attributes!')):
validation_metrics_tmp = validation_metrics.copy()
validation_metrics_tmp[0] = model
trainer = Trainer(dataHandler, model, losses... |
class ConvBnReLU3d(ConvBn3d):
_FLOAT_MODULE = nni.ConvBnReLU3d
_FLOAT_CONV_MODULE = nn.Conv3d
_FLOAT_BN_MODULE = nn.BatchNorm3d
_FLOAT_RELU_MODULE = nn.ReLU
def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, dilation=1, groups=1, bias=None, padding_mode='zeros', eps=1e-0... |
class Conv1x1(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, groups=1):
super(Conv1x1, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, 1, stride=stride, padding=0, bias=False, groups=groups)
self.bn = nn.BatchNorm2d(out_channels)
self.relu = nn.... |
class PerceiverForOpticalFlow(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_clip():
default_clipid = 'development/1'
dataset = dcase23_task6b.Dataset(TEST_DATA_HOME)
clip = dataset.clip(default_clipid)
expected_attributes = {'audio_path': os.path.join(os.path.normpath('tests/resources/sound_datasets/dcase23_task6b/'), 'development/1.wav'), 'clip_id': 'development/1'}
... |
def dynamic_range_compression(x, C=1, clip_val=1e-05):
return torch.log((torch.clamp(x, min=clip_val) * C)) |
def get_quantization_quantizers(node: BaseNode) -> Tuple[(Dict, List)]:
weight_quantizers = {}
activation_quantizers = []
if node.is_weights_quantization_enabled():
weight_attrs = DEFAULT_KERAS_INFO.get_kernel_op_attributes(node.type)
weight_quantizer = get_weights_quantizer_for_node(node)
... |
def run():
logger = config.get_logger('train')
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
os.environ['TRANSFORMERS_OFFLINE'] = '1'
if (config['visualizer']['type'] != ''):
visualizer = config.initialize(name='visualizer', module=module_vis, exp_name=config['name'], web_dir=config._web_log_di... |
def check_pipeline(dir_1: str, dir_2: str):
assert (os.listdir(dir_1).sort() == os.listdir(dir_2).sort() == ['test_files', 'splits'].sort())
test_path_dir1 = os.path.join(dir_1, 'test_files')
test_path_dir2 = os.path.join(dir_2, 'test_files')
if (os.path.exists(test_path_dir1) or os.path.exists(test_pat... |
def check_n_clusters(n_clusters: int, n_row: int, n_min: int=0):
if (n_clusters > n_row):
raise ValueError('The number of clusters exceeds the number of rows.')
if (n_clusters < n_min):
raise ValueError('The number of clusters must be at least {}.'.format(n_min))
else:
return |
class MLP(nn.Sequential):
def __init__(self, inputs, outputs, hidden=100):
super().__init__(Flatten(inputs), nn.Linear(inputs, hidden), nn.Softplus(), nn.Linear(hidden, outputs)) |
def _empty_body_uv_results():
return OrderedDict({'body_uv': OrderedDict([('AP', (- 1)), ('AP50', (- 1)), ('AP75', (- 1)), ('APm', (- 1)), ('APl', (- 1))])}) |
def workspace(name='workspace'):
workspace = gap_workspace_file('libgap', name)
try:
workspace_mtime = os.path.getmtime(workspace)
except OSError:
return (workspace, False)
return (workspace, (workspace_mtime >= timestamp())) |
def package_files(directory, relative_parent=''):
paths = []
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
relative_path = os.path.join(relative_parent, filename)
if os.path.isfile(filepath):
if (not str(filename).startswith('.')):
... |
def test_bitpacked_fields():
def test_single_bitpacked_fields(physical_type, compute_type, quant_bits, test_case):
ti.init(arch=ti.cpu, debug=True)
qit1 = ti.types.quant.int(quant_bits[0], True, compute_type)
qit2 = ti.types.quant.int(quant_bits[1], False, compute_type)
qit3 = ti.typ... |
def draw_overlay(img, mask, color=[0, 0, 255], op=0.5):
img[np.where(mask)] = ((img[np.where(mask)] * (1 - op)) + (np.array(color) * op)) |
def get_logger(logdir):
logger = logging.getLogger('emotion')
ts = str(datetime.datetime.now()).split('.')[0].replace(' ', '_')
ts = ts.replace(':', '_').replace('-', '_')
file_path = os.path.join(logdir, 'run_{}.log'.format(ts))
hdlr = logging.FileHandler(file_path)
formatter = logging.Formatte... |
def DeepR152V3PlusD_OS8(args, num_classes, criterion, criterion_aux):
print('Model : DeepLabv3+, Backbone : ResNet-152')
return DeepV3Plus(num_classes, trunk='resnet-152', criterion=criterion, criterion_aux=criterion_aux, variant='D', skip='m1', args=args) |
class WQSymBases(Category_realization_of_parent):
def __init__(self, base, graded):
self._graded = graded
Category_realization_of_parent.__init__(self, base)
def _repr_(self):
if self._graded:
type_str = 'graded'
else:
type_str = 'filtered'
return ... |
class SIMPLE_LAYER(torch.nn.Module):
def __init__(self, feat_in, feat_out):
super(SIMPLE_LAYER, self).__init__()
self.temp_layer = Linear(feat_in, feat_out)
def forward(self, x, edge_index):
return self.temp_layer(x) |
def dyn_batch_without_padding(new, i, sofar):
if args.distillation:
return (sofar + max(len(new.src), len(new.trg), len(new.dec)))
else:
return (sofar + max(len(new.src), len(new.trg))) |
def get_union_variant(x: Field):
is_dyn_array = (x.count and (not isinstance(x.count, int)))
is_ptr = (x.by_ref or x.by_mut or is_dyn_array)
name = _T(x.name)
out = '[FieldOffset(0)] '
if is_ptr:
out += f'IntPtr {name}'
elif x.count:
out += f'[MarshalAs(UnmanagedType.ByValArray, ... |
class PropertyDocumenter(DocstringStripSignatureMixin, ClassLevelDocumenter):
objtype = 'property'
member_order = 60
priority = (AttributeDocumenter.priority + 1)
def can_document_member(cls, member: Any, membername: str, isattr: bool, parent: Any) -> bool:
if isinstance(parent, ClassDocumenter)... |
class NumericRange():
def __init__(self, ranges, inclusive_intervals=None, null_value=None, is_not_null_condition=False):
self.is_not_null_condition = is_not_null_condition
self.ranges = ranges
self.null_value = null_value
self.inclusive_intervals = inclusive_intervals
if (se... |
def default_conv(in_channels, out_channels, kernel_size, bias=True, groups=1):
return nn.Conv2d(in_channels, out_channels, kernel_size, padding=(kernel_size // 2), bias=bias, groups=groups) |
def EmbeddingLookupFeatures(params, sparse_features, allow_weights):
if (not isinstance(params, list)):
params = [params]
sparse_features = tf.convert_to_tensor(sparse_features)
(indices, ids, weights) = gen_parser_ops.unpack_sparse_features(sparse_features)
embeddings = tf.nn.embedding_lookup(p... |
def timeit(f):
WINDOW_SIZE = 128
timeit._elapsed = defaultdict((lambda : deque(maxlen=WINDOW_SIZE)))
def summarize():
print('\x1b[33m----- Summarize -----\x1b[0m')
for (k, q) in timeit._elapsed.items():
print(f'{k:55s} took: {np.mean(q):.5f} sec [{len(q)} samples]')
timeit.su... |
def get_bn_params(sess, name):
moving_mean_tensor = sess.graph.get_tensor_by_name(os.path.join(name, 'moving_mean:0'))
moving_var_tensor = sess.graph.get_tensor_by_name(os.path.join(name, 'moving_variance:0'))
beta_tensor = sess.graph.get_tensor_by_name(os.path.join(name, 'beta:0'))
moving_mean = sess.r... |
def test_listarrayA64():
for depth in (0, 1, 2, 3):
for cuts in itertools.permutations((0, 1, 4, (- 5)), depth):
assert (to_list(modelA[cuts]) == to_list(listarrayA64[cuts]))
if (depth < 3):
assert (listarrayA64.to_typetracer()[cuts].form == listarrayA64[cuts].form)
... |
class TensorOutputOp():
Template = '\n${visitor}\n\nusing ${instance_name} = cutlass::epilogue::threadblock::VisitorOpTensorOutput<\n ${element_accumulator}, ${output_tile_iterator}, ${visitor_name}>;\n'
counter = 0
def __init__(self, element_accumulator, visitor) -> None:
self.element_accumulato... |
def generate_python_code(matcher):
cg = CodeGenerator(matcher)
(a, b) = cg.generate_code()
return (a, b) |
def close_file():
global _FILE
if (not (_FILE is None)):
_FILE.close()
_FILE = None |
def format_next(text, new_text, pos, can_newline, width, ispaces):
new_len = len(new_text)
if (((pos + new_len) > width) and can_newline):
text += (('\n' + ispaces) + new_text)
pos = new_len
can_newline = False
else:
if (pos > 0):
text += (' ' + new_text)
... |
def check_spec_implementation():
count = 0
with open(os.path.join(CURRENT_DIR, '..', 'kernel-specification.yml')) as specfile:
indspec = yaml.safe_load(specfile)['kernels']
for spec in indspec:
if ('def awkward' not in spec['definition']):
if (count == 0):
... |
def evaluate(model, weights, dataset, datatype, split, count, shot, seed, gpu, hist_path, seg_path):
print('evaluating {} with weights {} on {} {}-{}'.format(model, weights, datatype, dataset, split))
os.environ['CUDA_VISIBLE_DEVICES'] = str(gpu)
device = torch.device('cuda:0')
torch.manual_seed(seed)
... |
class PLBartTokenizer(metaclass=DummyObject):
_backends = ['sentencepiece']
def __init__(self, *args, **kwargs):
requires_backends(self, ['sentencepiece']) |
def read_script_from_list_string(list_string):
script_lines = []
f = list_string
index = 1
for line in f:
if ('[' not in line):
continue
line = line.strip()
if ((len(line) > 0) and (not line.startswith('#'))):
script_lines.append(parse_script_line(line, in... |
class MultiscaleCombinedHeadLongTemporalWindow(nn.Module):
def __init__(self, in_channels, num_classes, variance_output, variance_per_axis, **kwargs):
super().__init__()
self.embedding_size = 3
self.variance_channels = ((self.embedding_size if variance_per_axis else 1) if variance_output els... |
def l2_dist(x, y, pw=False):
if (pw is False):
x = x.unsqueeze(1)
y = y.unsqueeze(0)
return (- th.norm((x - y), p=2, dim=(- 1))) |
def test_fpn_carafe():
FPN_CARAFE(in_channels=[8, 16, 32, 64], out_channels=8, start_level=0, end_level=3, num_outs=4)
FPN_CARAFE(in_channels=[8, 16, 32, 64], out_channels=8, start_level=0, end_level=(- 1), num_outs=4)
with pytest.raises(AssertionError):
FPN_CARAFE(in_channels=[8, 16, 32, 64], out_c... |
def interpolate_hermite(images, camera_id, file_format):
if (len(images) < 4):
raise ValueError('Need at least four images for Hermite spline interpolation!')
new_images = []
T0 = image_to_idx(images[0])
dq0 = DualQuaternion.FromQT(images[0].q, images[0].t)
T1 = image_to_idx(images[1])
d... |
def _pipeline_parallel_post_init(cfg: DistributedTrainingConfig, num_pipeline_devices, num_pipelines_per_node):
if (not cfg.distributed_no_spawn):
assert ((cfg.distributed_world_size % num_pipeline_devices) == 0)
cfg.distributed_world_size = (cfg.distributed_world_size // num_pipeline_devices)
... |
class BaseDataLoader(object):
def __init__(self):
pass
def initialize(self, opt):
self.opt = opt
pass
def load_data(self):
return None |
def print_header(colwidth=16, sep=' '):
items = []
for item in BenchResult._fields:
items.append(fit_str(item))
return sep.join(items) |
def is_mods(fn: str, mods: Collection[str]) -> bool:
import re
return any([is_mod(fn, mod) for mod in mods]) |
class AverageMeters():
def __init__(self):
super().__init__()
self.average_meters = {}
def add_loss_value(self, loss_name, loss_val, n=1):
if (loss_name not in self.average_meters):
self.average_meters[loss_name] = AverageMeter()
self.average_meters[loss_name].update(... |
def copy_to_gpu(gpu: bool, tensor: T) -> T:
if gpu:
return tensor.cuda()
else:
return tensor |
class COCODatasetBase(ReidBaseDataModule):
def __init__(self, cfg, **kwargs):
super().__init__(cfg, **kwargs)
assert (cfg.DATASETS.JSON_TRAIN_PATH != ''), 'DATASETS.JSON_TRAIN_PATH is not specified in the config'
self.dataset_dir = cfg.DATASETS.ROOT_DIR
self.json_train_path = cfg.DAT... |
def _do_bistochastic_test(scaled):
_do_scale_test(scaled)
assert_almost_equal(scaled.sum(axis=0).mean(), scaled.sum(axis=1).mean(), decimal=1) |
class ConfusionMatrix():
def __init__(self, actual_vector=None, predict_vector=None, matrix=None, digit=5, threshold=None, file=None, sample_weight=None, transpose=False, classes=None, is_imbalanced=None, metrics_off=False):
self.actual_vector = actual_vector
self.predict_vector = predict_vector
... |
def __getitem_(g, self, i):
if sym_help._is_tensor_list(self):
return g.op('SequenceAt', self, i)
else:
from torch.onnx.symbolic_opset9 import __getitem_ as getitem
return getitem(g, self, i) |
class Argument(object):
def __init__(self, _type, name, is_optional):
self.type = _type
self.name = name
self.is_optional = is_optional
def __repr__(self):
return ((self.type + ' ') + self.name) |
class ModuleTestCluster(TestCluster):
def __init__(self, linenos: int) -> None:
self.__type_system = TypeSystem()
self.__linenos = linenos
self.__generators: dict[(ProperType, OrderedSet[GenericAccessibleObject])] = defaultdict(OrderedSet)
self.__modifiers: dict[(TypeInfo, OrderedSet... |
class PsiOptimized(nn.Module):
def __init__(self, dim=128, K=100, numclasses=50, use_adapter=False, adapter_reduce_dim=True):
super().__init__()
self.use_adapter = use_adapter
self.adapter_reduce_dim = adapter_reduce_dim
if use_adapter:
self.adapter = ResBlockAudio(dim)
... |
class UniFormer(nn.Module):
def __init__(self, model_name: str='S', pretrained: str=None, num_classes: int=1000, *args, **kwargs) -> None:
super().__init__()
assert (model_name in uniformer_settings.keys()), f'UniFormer model name should be in {list(uniformer_settings.keys())}'
depth = unifo... |
class Function_limit(BuiltinFunction):
def __init__(self):
BuiltinFunction.__init__(self, 'limit', nargs=0, conversions=dict(maxima='limit'))
def _latex_(self):
return '\\lim'
def _print_latex_(self, ex, var, to, direction=''):
if (repr(direction) == 'minus'):
dir_str = '... |
def create_image_vectors(images):
img_vectors = {}
for img in images.keys():
img_data = image.img_to_array(images[img])
img_data = np.expand_dims(img_data, axis=0)
img_data = preprocess_input(img_data)
vgg16_feature = model.predict(img_data)
vgg16_feature_np = np.array(vg... |
class STNClsNet(nn.Module):
def __init__(self, args):
super(STNClsNet, self).__init__()
self.args = args
r1 = args.span_range_height
r2 = args.span_range_width
assert ((r1 < 1) and (r2 < 1))
target_control_points = torch.Tensor(list(itertools.product(np.arange((- r1),... |
class CCRStructure(Structure):
_fields_ = [('results', POINTER(CodeCompletionResult)), ('numResults', c_int)]
def __len__(self):
return self.numResults
def __getitem__(self, key):
if (len(self) <= key):
raise IndexError
return self.results[key] |
def coordinated_get(coordinator, queue):
while (not coordinator.should_stop()):
try:
return queue.get(block=True, timeout=1.0)
except Queue.Empty:
continue
raise Exception('Coordinator stopped during get()') |
class ZipReader(object):
zip_bank = dict()
def __init__(self):
super(ZipReader, self).__init__()
def get_zipfile(path):
zip_bank = ZipReader.zip_bank
if (path not in zip_bank):
zfile = zipfile.ZipFile(path, 'r')
zip_bank[path] = zfile
return zip_bank[p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.