code stringlengths 101 5.91M |
|---|
def process_cfg(cfg_dir, java_dir, final_cfg_dir):
cfg_file_list = os.listdir(cfg_dir)
os.chdir(cfg_dir)
for item in tqdm(cfg_file_list):
if (item.find('.txt') > 0):
cfg_file = open(item, encoding='utf-8')
cfg_id = item.split('.')[0].replace('A', '')
try:
... |
class AttentionBlock(nn.Module):
def __init__(self, in_ch: int, skip_ch: int, out_ch: ty.N[int]=None, upsample_mode: str='nearest'):
super().__init__()
self.in_ch = (in_ch + skip_ch)
self.out_ch = (out_ch or in_ch)
self.upsample_mode = upsample_mode
self.layers = nn.Sequentia... |
def sklearn_OutputCodeClassifier(*args, **kwargs):
return sklearn.multiclass.OutputCodeClassifier(*args, **kwargs) |
def _check_for_nans(metrics: Dict, new_params: P) -> chex.Numeric:
metrics_nans = _check_metrics_for_nans(metrics)
params_nans = jnp.any(jnp.isnan(jax.flatten_util.ravel_pytree(new_params)[0]))
return jnp.logical_or(metrics_nans, params_nans) |
def Nnet3DescriptorToDot(descriptor, parent_node_name):
dot_lines = []
[segments, arguments] = descriptor_parser.IdentifyNestedSegments(descriptor)
if segments:
for segment in segments:
dot_lines += DescriptorSegmentToDot(segment, parent_node_name, parent_node_name)
elif arguments:
... |
def worker(args):
(video_name, video_path, out_dir, sample_fps) = args
def get_stride(src_fps):
if (sample_fps <= 0):
stride = 1
else:
stride = int((src_fps / sample_fps))
return stride
vc = cv2.VideoCapture(video_path)
fps = vc.get(cv2.CAP_PROP_FPS)
n... |
def filter_roidb(roidb):
print(('before filtering, there are %d images...' % len(roidb)))
i = 0
while (i < len(roidb)):
if (len(roidb[i]['boxes']) == 0):
del roidb[i]
i -= 1
i += 1
print(('after filtering, there are %d images...' % len(roidb)))
return roidb |
def test_hist():
np.random.seed(0)
X_col = np.random.random_sample((1000,))
(counts, vals) = np.histogram(X_col, bins='doane')
X_col = np.concatenate(([np.nan], X_col))
native = Native.get_native_singleton()
n_cuts = native.get_histogram_cut_count(X_col)
cuts = native.cut_uniform(X_col, n_cu... |
def get_obj_label(key):
words = key.split('_')
return ' '.join(map((lambda w: (str(w[0]).upper() + w[1:])), words)) |
def add_self_bond(bond_features):
if (len(bond_features.shape) == 3):
bf = np.transpose(bond_features, (2, 0, 1))
bf = np.concatenate((bf, [np.identity(bf.shape[2])]), axis=0)
else:
bf = np.concatenate(([bond_features], [np.identity(bond_features.shape[1])]), axis=0)
return bf |
def custom_draw_geometry_load_option(pcd, render_option_path):
vis = o3d.visualization.Visualizer()
vis.create_window()
vis.add_geometry(pcd)
vis.get_render_option().load_from_json(render_option_path)
vis.run()
vis.destroy_window() |
class TestDagDrawer(QiskitTestCase):
def setUp(self):
qr = QuantumRegister(2, 'qr')
circuit = QuantumCircuit(qr)
circuit.cx(qr[0], qr[1])
circuit.cx(qr[0], qr[1])
self.dag = circuit_to_dag(circuit)
def test_dag_drawer_no_graphviz(self):
with unittest.mock.patch('n... |
def simu_data(n, p, rho=0.25, snr=2.0, sparsity=0.06, effect=1.0, seed=None):
rng = np.random.default_rng(seed)
k = int((sparsity * p))
mu = np.zeros(p)
Sigma = toeplitz((rho ** np.arange(0, p)))
X = rng.multivariate_normal(mu, Sigma, size=n)
non_zero = rng.choice(p, k)
beta_true = np.zeros(... |
class SentUnit():
def __init__(self, sent_index, raw_words, list_of_bpes, discourse_bag):
self.sent_index = sent_index
self.raw_words = raw_words
self.bpes = list(itertools.chain(*list_of_bpes))
self.prefix_len = (- 1)
self.discourse_bag = discourse_bag
def get_bpe_w_cls_... |
class SepFormer(nn.Module):
def __init__(self, in_chan, n_src, n_heads=8, ff_hid=1024, chunk_size=250, hop_size=None, n_repeats=8, n_blocks=2, norm_type='gLN', ff_activation='relu', mask_act='relu', bidirectional=True, dropout=0):
super(SepFormer, self).__init__()
self.in_chan = in_chan
self... |
def get_cov_left_right(cov_diag, k):
shape_cov = tf.shape(cov_diag)
(_, top_idx) = tf.nn.top_k(cov_diag, k=k)
(ii, _) = tf.meshgrid(tf.range(shape_cov[0]), tf.range(k), indexing='ij')
top_idx = tf.stack([ii, top_idx], axis=(- 1))
top_k = tf.gather_nd(cov_diag, top_idx)
top_k_cov = tf.linalg.diag... |
def read_filenames(root_dir):
speaker2filenames = defaultdict((lambda : []))
for path in sorted(glob.glob(os.path.join(root_dir, '*/*'))):
filename = path.strip().split('/')[(- 1)]
(speaker_id, utt_id) = re.match('p(\\d+)_(\\d+)\\.wav', filename).groups()
speaker2filenames[speaker_id].ap... |
class Output():
def __init__(self, n_output_channels, filters):
self.n_output_channels = n_output_channels
self.filters = filters
conv = partial(Conv2D, kernel_size=(1, 1), activation='relu', padding='same', use_bias=False)
self.input_bn = BatchNormalization()
self.input_conv... |
class TFConvBertForQuestionAnswering(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
class Anchor():
def __init__(self, reg_num, yind, fold):
self.__yind = yind
self.__fold = fold
self.__reg_num = reg_num
self.__gate_placed = []
self.gate_anchor = 0
def plot_coord(self, index, gate_width):
h_pos = ((index % self.__fold) + 1)
if (self.__fol... |
def cross_entropy(pred, label, weight=None, reduction='mean', avg_factor=None):
loss = F.cross_entropy(pred, label, reduction='none')
if (weight is not None):
weight = weight.float()
loss = weight_reduce_loss(loss, weight=weight, reduction=reduction, avg_factor=avg_factor)
return loss |
class TestFSAFHead(TestCase):
def test_fsaf_head_loss(self):
s = 300
img_metas = [{'img_shape': (s, s), 'pad_shape': (s, s), 'scale_factor': 1}]
cfg = Config(dict(assigner=dict(type='CenterRegionAssigner', pos_scale=0.2, neg_scale=0.2, min_pos_iof=0.01), allowed_border=(- 1), pos_weight=(- 1... |
_lr_scheduler('fixed')
class FixedSchedule(FairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
args.warmup_updates = (getattr(args, 'warmup_updates', 0) or 0)
self.lr = args.lr[0]
if (args.warmup_updates > 0):
self.warmup_factor = (... |
def get_ov_sut(model_path, preprocessed_data_dir, performance_count):
return _3DUNET_OV_SUT(model_path, preprocessed_data_dir, performance_count) |
def preprocess_image(image_buffer, output_height, output_width, num_channels, is_training=False):
if is_training:
image = _decode_crop_and_flip(image_buffer, num_channels)
image = _resize_image(image, output_height, output_width)
else:
image = tf.image.decode_jpeg(image_buffer, channels=... |
def parse_distributed_args():
parser = ArgumentParser(description='Dist FlowNMT')
parser.add_argument('--nnodes', type=int, default=1, help='The number of nodes to use for distributed training')
parser.add_argument('--node_rank', type=int, default=0, help='The rank of the node for multi-node distributed tra... |
class NfCfg():
depths: Tuple[(int, int, int, int)]
channels: Tuple[(int, int, int, int)]
alpha: float = 0.2
stem_type: str = '3x3'
stem_chs: Optional[int] = None
group_size: Optional[int] = None
attn_layer: Optional[str] = None
attn_kwargs: dict = None
attn_gain: float = 2.0
widt... |
def hex_to_rgb(value):
value = value.lstrip('#')
hex_total_length = len(value)
rgb_section_length = (hex_total_length // 3)
return tuple((int(value[i:(i + rgb_section_length)], 16) for i in range(0, hex_total_length, rgb_section_length))) |
class BertGenerationConfig(PretrainedConfig):
model_type = 'bert-generation'
def __init__(self, vocab_size=50358, hidden_size=1024, num_hidden_layers=24, num_attention_heads=16, intermediate_size=4096, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, ini... |
def get_python_logger() -> logging.Logger:
logger = logging.getLogger()
logger.handlers = []
ch = logging.StreamHandler()
formatter = logging.Formatter(f'{Fore.CYAN}{Style.BRIGHT}%(message)s', '%H:%M:%S')
ch.setFormatter(formatter)
logger.addHandler(ch)
logger.setLevel('INFO')
return log... |
def parse_args():
parser = ArgumentParser(description='CIFAR')
parser.add_argument('--dataset', choices=['cifar10', 'pathfinder'], required=True)
parser.add_argument('--resolution', type=int, default=None)
parser.add_argument('--data_path', help='path for data file.', required=True)
return parser.pa... |
.parametrize('size', list_sizes())
.parametrize('dtype', list_float_dtypes())
.parametrize('device', list_devices())
def test_hybrid_search(benchmark, size, dtype, device):
nns_opt = dict(knn=1, radius=0.01)
np_a = np.array(np.random.rand(size, 3), dtype=to_numpy_dtype(dtype))
np_b = np.array(np.random.rand... |
class MetaTransformer_AD_ResBackBone(nn.Module):
def __init__(self, model_cfg, input_channels, grid_size, **kwargs):
super().__init__()
self.model_cfg = model_cfg
norm_fn = partial(uni3d_norm_2_in.UniNorm1d, dataset_from_flag=int(self.model_cfg.db_source), eps=0.001, momentum=0.01, voxel_coo... |
def get_model(point_cloud, is_training, bn_decay=None, num_class=NUM_CLASSES):
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_points = {}
l0_xyz = tf.slice(point_cloud, [0, 0, 0], [(- 1), (- 1), 3])
l0_points = None
(l1_xyz, l1_points, l1_indices) ... |
def _reduce_prod_over_leaves(xs: PyTree) -> Array:
return functools.reduce((lambda a, b: (a * b)), jax.tree_util.tree_leaves(xs)) |
def save_metrics(metrics, exp_dir, filename='metrics.json', i=None):
if (i is not None):
filename = '{}.{}'.format(filename, i)
with open(os.path.join(exp_dir, filename), 'w') as f:
json.dump(dict(metrics), f, indent=4, separators=(',', ': '), sort_keys=True) |
def to_md(comment_dict):
doc = ''
if ('short_description' in comment_dict):
doc += comment_dict['short_description']
doc += '\n\n'
if ('long_description' in comment_dict):
doc += md_parse_line_break(comment_dict['long_description'])
doc += '\n'
if (('Args' in comment_dict... |
def dataset_exists(path, impl):
if (impl == 'raw'):
return IndexedRawTextDataset.exists(path)
elif (impl == 'mmap'):
return MMapIndexedDataset.exists(path)
else:
return IndexedDataset.exists(path) |
def compile_args(config):
if ('lr' in config):
lr = config['lr']
else:
lr = 0.001
args = {'optimizer': tf.keras.optimizers.Adam(lr), 'loss': 'mean_squared_error', 'metrics': ['mean_squared_error']}
return args |
class CombinedSample(AbstractSample):
def __init__(self, samples):
self.samples = samples
self.bases = ([0] + [s.numOptions() for s in self.samples[:(- 1)]])
def _sample(self, node, *args, **kwargs):
idx = len(node.children)
for (base, sample) in zip(self.bases, self.samples):
... |
def nth(iterator, n, default=None):
if (n is None):
return collections.deque(iterator, maxlen=0)
else:
return next(islice(iterator, n, None), default) |
class AdamW(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.01, amsgrad=False):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon value: {}'.fo... |
def get_plugin_instance(plugin_name):
if (is_plugin_enabled(plugin_name) and plugins[plugin_name]['instance']):
return plugins[plugin_name]['instance']
return None |
def _gen_mobilenet_v3_rw(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_e1_c16_nre_noskip'], ['ir_r1_k3_s2_e4_c24_nre', 'ir_r1_k3_s1_e3_c24_nre'], ['ir_r3_k5_s2_e3_c40_se0.25_nre'], ['ir_r1_k3_s2_e6_c80', 'ir_r1_k3_s1_e2.5_c80', 'ir_r2_k3_s1_e2.3_c80'], ['ir_r2_k3_s1_e6_c112... |
def rigid_align(coords_pred, coords_true, *, joint_validity_mask=None, scale_align=False, reflection_align=False):
if (joint_validity_mask is None):
joint_validity_mask = np.ones_like(coords_pred[(..., 0)], dtype=np.bool)
valid_coords_pred = coords_pred[joint_validity_mask]
valid_coords_true = coord... |
_grad()
def convert_models(model_path: str, output_path: str, opset: int, fp16: bool=False):
dtype = (torch.float16 if fp16 else torch.float32)
if (fp16 and torch.cuda.is_available()):
device = 'cuda'
elif (fp16 and (not torch.cuda.is_available())):
raise ValueError('`float16` model export i... |
def binary_block5x5(in_planes, out_planes, stride=1, **kwargs):
return b_utils.BinBlock(in_planes, out_planes, kernel_size=5, stride=stride, padding=2, bias=False, **kwargs) |
class TestLoadSoundFiles():
def test_load_stereo_ogg_vorbis(self):
(samples, sample_rate) = load_sound_file(os.path.join(DEMO_DIR, 'background_noises', 'hens.ogg'), sample_rate=None)
assert (samples.dtype == np.float32)
assert (samples.ndim == 1)
assert (samples.shape[0] >= 442575)
... |
class LocalAttention(nn.Module):
def __init__(self, local_context, softmax_temp=None, attention_dropout=0.0, device=None, dtype=None):
super().__init__()
self.local_context = local_context
self.softmax_temp = softmax_temp
self.dropout = nn.Dropout(attention_dropout)
def forward(s... |
class _RCSuperOp():
def __call__(self, discardNonchemical: bool=True, allowPartial: bool=True, enforceConstraints: bool=False) -> _RCSuperOpArgsBound:
return _RCSuperOpArgsBound(discardNonchemical, allowPartial, enforceConstraints)
def __rmul__(self, first: RCExpExp) -> _RCSuperOpFirstBound:
ret... |
def check_module(module_name: str) -> None:
if (module_name == 'onnxrt'):
module_name = 'onnxruntime'
if (module_name == 'pytorch'):
module_name = 'torch'
module = find_spec(module_name.lower())
if (module is None):
raise ClientErrorException(f'Could not find {module_name} module... |
def get_spnasnet(model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
init_block_channels = [32, 16]
final_block_channels = [320, 1280]
channels = [[24, 24, 24], [40, 40, 40, 40], [80, 80, 80, 80], [96, 96, 96, 96, 192, 192, 192, 192]]
kernels3 = [[1, 1, 1], [0, 1, 1... |
('refextract.app.extract_journal_reference', side_effect=KeyError('test message'))
def test_extract_journal_info_when_timeout_from_refextract(mock_extract_refs, app_client):
journal_kb_data = {'COMMUNICATIONS IN ASTEROSEISMOLOGY': 'Commun.Asteros.', 'PHYS REV': 'Phys.Rev.', 'PHYSICAL REVIEW': 'Phys.Rev.', 'PHYS REV... |
class MolInstance_BP_Dipole(MolInstance_fc_sqdiff_BP):
def __init__(self, TData_, Name_=None, Trainable_=True):
self.NetType = 'fc_sqdiff_BP'
MolInstance.__init__(self, TData_, Name_, Trainable_)
self.name = ((((((('Mol_' + self.TData.name) + '_') + self.TData.dig.name) + '_') + str(self.TDa... |
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1)
if batch_norm:
layers += [... |
class DPRReaderState(DPRState):
def load_dpr_model(self):
model = DPRReader(DPRConfig(**BertConfig.get_config_dict('bert-base-uncased')[0]))
print('Loading DPR reader from {}'.format(self.src_file))
saved_state = load_states_from_checkpoint(self.src_file)
state_dict = {'encoder.bert_... |
def new_job_auto_scaler(job_strategy, job_resource: JobResource, job_nodes: Dict[(str, Dict[(int, Node)])], job_optimizer: JobResourceOptimizer, speed_monitor: SpeedMonitor, ps_manager: ParameterServerManager, worker_manager: WorkerManager, node_scaler: Scaler):
if (job_strategy == DistributionStrategy.PS):
... |
(help='Generate list of LiDAR timestamps at which to evaluate the model.')
('--tbv-dataroot', required=True, help='Path to local directory where the TbV logs are stored.', type=click.Path(exists=True))
def run_generate_eval_timestamp_list(tbv_dataroot: str) -> None:
generate_eval_timestamp_list(tbv_dataroot=Path(tb... |
class ThreeNN(Function):
def forward(ctx, target: torch.Tensor, source: torch.Tensor) -> Tuple[(torch.Tensor, torch.Tensor)]:
target = target.contiguous()
source = source.contiguous()
(B, N, _) = target.size()
m = source.size(1)
dist2 = torch.cuda.FloatTensor(B, N, 3)
... |
def make_room_dict(rir_list):
room_dict = {}
for rir in rir_list:
if (rir.room_id not in room_dict):
room_dict[rir.room_id] = (lambda : None)
setattr(room_dict[rir.room_id], 'rir_list', [])
setattr(room_dict[rir.room_id], 'probability', 0)
room_dict[rir.room_i... |
class ParseDecodeCoco():
def __call__(self, sample):
feature_map = {'image/encoded': tf.compat.v1.FixedLenFeature([], dtype=tf.string, default_value=''), 'image/object/class/text': tf.compat.v1.VarLenFeature(dtype=tf.string), 'image/object/class/label': tf.compat.v1.VarLenFeature(dtype=tf.int64), 'image/sou... |
class RolloutJSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, np.ndarray):
return o.tolist()
if isinstance(o, np.bool_):
return bool(o)
if isinstance(o, np.floating):
return float(o)
if isinstance(o, np.number):
ret... |
(scope='module')
def example_explanation():
data = synthetic_classification()
explainer = LogisticRegression()
explainer.fit(data['train']['X'], data['train']['y'])
explanation = explainer.explain_local(data['test']['X'].head(), data['test']['y'].head())
return explanation |
def kitti_odom10_validation(img_height, img_width, batch_size, num_workers):
transforms = [tf.CreateScaledImage(True), tf.Resize((img_height, img_width), image_types=('color',)), tf.CreateColoraug(), tf.ToTensor(), tf.NormalizeZeroMean(), tf.AddKeyValue('domain', 'kitti_odom10_val_pose'), tf.AddKeyValue('purposes',... |
def evaluate(args, model, tokenizer, prefix=''):
eval_task_names = (('mnli', 'mnli-mm') if (args.task_name == 'mnli') else (args.task_name,))
eval_outputs_dirs = ((args.output_dir, (args.output_dir + '/MM')) if (args.task_name == 'mnli') else (args.output_dir,))
results = {}
for (eval_task, eval_output_... |
class PointerGenerator(nn.Module):
def __init__(self, encoder, decoder):
super(PointerGenerator, self).__init__()
self.encoder = encoder
self.decoder = decoder
def forward(self, src, lengths, tgt, dec_state=None):
tgt = tgt[:(- 1)]
(memory_bank, enc_final) = self.encoder(... |
def flatten_first_axis_tensor_dict(tensor_dict):
keys = list(tensor_dict.keys())
ret = dict()
for k in keys:
if isinstance(tensor_dict[k], dict):
ret[k] = flatten_first_axis_tensor_dict(tensor_dict[k])
else:
old_shape = tensor_dict[k].shape
ret[k] = tensor... |
def get_ppq5_jitter(frequencies, p_floor, p_ceil, max_p_factor):
counter = 0
cumsum = 0
mean_period = get_mean_period(frequencies, p_floor, p_ceil, max_p_factor)
for (freq1, freq2, freq3, freq4, freq5) in shifted_sequence(frequencies, 5):
if validate_frequencies([freq1, freq2, freq3, freq4, freq... |
def extract_cnn_feature(model, inputs, modules=None):
model.eval()
inputs = to_torch(inputs).cuda()
if (modules is None):
outputs = model(inputs)
outputs = outputs.data.cpu()
return outputs
outputs = OrderedDict()
handles = []
for m in modules:
outputs[id(m)] = No... |
_algo(name=RTN_WEIGHT_ONLY_QUANT)
def rtn_quantize_entry(model: torch.nn.Module, configs_mapping: Dict[(Tuple[(str, callable)], RTNWeightQuantConfig)], *args, **kwargs) -> torch.nn.Module:
from .weight_only.rtn import apply_rtn_on_single_module
for ((op_name, op_type), quant_config) in configs_mapping.items():
... |
def eval_func(model):
predictions = []
references = []
for batch in librispeech_test_clean:
audio = batch['audio']
input_features = processor(audio['array'], sampling_rate=audio['sampling_rate'], return_tensors='pt').input_features
reference = processor.tokenizer._normalize(batch['te... |
def unbatchify(x: Array, agents: List[str]) -> Dict[(str, Array)]:
return {agent: x[i] for (i, agent) in enumerate(agents)} |
def normalize_probs(probs: tc.Tensor) -> tc.Tensor:
return (probs / probs.sum(dim=(- 1), keepdim=True)) |
class Mulki2019(dataset.Dataset):
name = 'mulki2019'
url = '
hash = '3fc5e06ab624b47e404ac4894c323ca038e726ce6dd3d0e6a371e3'
files = [{'name': 'mulki2019ar.csv', 'language': 'ar', 'type': 'training', 'platform': 'twitter'}]
license = 'UNKNOWN'
def process(cls, tmp_file_path, dataset_folder, api_... |
_model
def gluon_resnet101_v1d(pretrained=False, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['gluon_resnet101_v1d']
model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes, in_chans=in_chans, stem_width=32, stem_type='deep', avg_down=True, **kwargs)
model.default_cfg = defa... |
class ControllerFromTrainruns():
pp = pprint.PrettyPrinter(indent=4)
def __init__(self, env: RailEnv, trainrun_dict: Dict[(int, Trainrun)]):
self.env: RailEnv = env
self.trainrun_dict: Dict[(int, Trainrun)] = trainrun_dict
self.action_plan: ActionPlanDict = [self._create_action_plan_for_... |
def average_weights_ns(w, ns):
w_avg = copy.deepcopy(w[0])
for key in w_avg.keys():
(w_avg[key] * ns[0])
for i in range(1, len(w)):
w_avg[key] += (ns[i] * w[i][key])
w_avg[key] = torch.div(w_avg[key], sum(ns))
return w_avg |
def replace_instance_num(cmd_str, instance):
return cmd_str.replace('INST_NUM=', ('INST_NUM=' + str(instance))) |
class AsyncInferenceTestCase(AsyncTestCase):
if (sys.version_info >= (3, 7)):
async def test_simple_inference(self):
if (not torch.cuda.is_available()):
import pytest
pytest.skip('test requires GPU and torch+cuda')
ori_grad_enabled = torch.is_grad_enab... |
class ExplainedVarianceDisplay():
def __init__(self, explained_variance_train, explained_variance_test=None, ratio=True, view_labels=None, **kwargs):
self.explained_variance_train = explained_variance_train
self.explained_variance_test = explained_variance_test
self.ratio = ratio
if ... |
def initialize_quad_double_tracker(target, start, fixedgamma=True, regamma=0.0, imgamma=0.0, vrblvl=0):
if (vrblvl > 0):
print('in initialize_quad_double_tracker', end='')
print(', fixedgamma :', fixedgamma, end='')
print(', regamma :', regamma, end='')
print(', imgamma :', imgamma)
... |
def test_can_instantiate_from_data_config(data_cfg, parser):
cfg_string = read_cfg(data_cfg)
parser.add_lightning_class_args(LightningDataModule, 'cfg', subclass_mode=True, required=True)
args = parser.parse_string(cfg_string)
assert ('class_path' in args.cfg), 'No class_path key in config root level'
... |
class AutoModelForTokenClassification():
def __init__(self):
raise EnvironmentError('AutoModelForTokenClassification is designed to be instantiated using the `AutoModelForTokenClassification.from_pretrained(pretrained_model_name_or_path)` or `AutoModelForTokenClassification.from_config(config)` methods.')
... |
class ConditionalGuidedModel(nn.Module):
def __init__(self, config):
super(ConditionalGuidedModel, self).__init__()
n_steps = (config.diffusion.timesteps + 1)
self.cat_x = config.model.cat_x
self.cat_y_pred = config.model.cat_y_pred
data_dim = config.model.y_dim
if se... |
class Point_Transformer_Last(nn.Module):
def __init__(self, args, channels=256):
super(Point_Transformer_Last, self).__init__()
self.args = args
self.conv1 = nn.Conv1d(channels, channels, kernel_size=1, bias=False)
self.conv2 = nn.Conv1d(channels, channels, kernel_size=1, bias=False)... |
(frozen=True)
class ValidationResult():
compilation_rate: float
plausible_rate: float
n_plausible_fixes: int |
def initialize_weights(modules, init_mode):
for m in modules:
if isinstance(m, nn.Conv2d):
if (init_mode == 'he'):
nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
elif (init_mode == 'xavier'):
nn.init.xavier_uniform_(m.weight.dat... |
class ViltImageProcessingTester(unittest.TestCase):
def __init__(self, parent, batch_size=7, num_channels=3, image_size=18, min_resolution=30, max_resolution=400, do_resize=True, size=None, size_divisor=2, do_normalize=True, image_mean=[0.5, 0.5, 0.5], image_std=[0.5, 0.5, 0.5]):
size = (size if (size is no... |
class RandomChooseData(RNGDataFlow):
def __init__(self, df_lists):
super(RandomChooseData, self).__init__()
if isinstance(df_lists[0], (tuple, list)):
assert (sum([v[1] for v in df_lists]) == 1.0)
self.df_lists = df_lists
else:
prob = (1.0 / len(df_lists))... |
def extract_axis_1(data, ind):
batch_range = tf.range(tf.shape(data)[0])
indices = tf.stack([batch_range, ind], axis=1)
res = tf.gather_nd(data, indices)
return res |
def test_add_loss():
(name, type) = ('test', 'loss')
(name, type)
class Test():
...
assert (name in LOSS_REG), 'Missing item from LOSS registry.'
LOSS_REG.pop(name) |
class SimpleDataset():
def __init__(self, data_file, transform, target_transform=identity, n_images=(- 1), n_classes=(- 1), seed=0):
with open(data_file, 'r') as f:
self.meta = json.load(f)
self.transform = transform
self.target_transform = target_transform
self.meta['ima... |
def _get_config(params, arg_name, subfolder):
config_name = None
for (_i, _v) in enumerate(params):
if (_v.split('=')[0] == arg_name):
config_name = _v.split('=')[1]
del params[_i]
break
if (config_name is not None):
with open(os.path.join(os.path.dirname(... |
def get_mask_pallete(npimg, dataset='detail'):
if (dataset == 'pascal_voc'):
npimg[(npimg == 21)] = 255
out_img = Image.fromarray(npimg.squeeze().astype('uint8'))
if (dataset == 'ade20k'):
out_img.putpalette(adepallete)
elif (dataset == 'citys'):
out_img.putpalette(citypallete)
... |
class Cider():
def __init__(self, n=4, df='corpus'):
self._n = n
self._df = df
self.cider_scorer = CiderScorer(n=self._n, df_mode=self._df)
def compute_score(self, gts, res):
self.cider_scorer.clear()
for res_id in res:
hypo = res_id['caption']
ref... |
def gen_evalset(args):
torch.manual_seed(args.eval_seed)
torch.cuda.manual_seed(args.eval_seed)
eval_ds = EMNIST(train=False, class_range=args.class_range)
eval_loader = torch.utils.data.DataLoader(eval_ds, batch_size=args.eval_batch_size, shuffle=False, num_workers=4)
batches = []
for (x, _) in... |
def imread_indexed(filename):
im = Image.open(filename)
annotation = np.atleast_3d(im)[(..., 0)]
return (annotation, np.array(im.getpalette()).reshape(((- 1), 3))) |
class ClapModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _return_context(value):
data = struct.pack('=q', value.v_int64)
arr = struct.unpack('=ii', data)
return TVMContext(arr[0], arr[1]) |
class CondConv2d(nn.Module):
__constants__ = ['in_channels', 'out_channels', 'dynamic_padding']
def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding='', dilation=1, groups=1, bias=False, num_experts=4):
super(CondConv2d, self).__init__()
self.in_channels = in_channels
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.