code stringlengths 101 5.91M |
|---|
def is_positive_semidefinite_matrix(mat, rtol=RTOL_DEFAULT, atol=ATOL_DEFAULT):
if (atol is None):
atol = ATOL_DEFAULT
if (rtol is None):
rtol = RTOL_DEFAULT
if (not is_hermitian_matrix(mat, rtol=rtol, atol=atol)):
return False
vals = np.linalg.eigvalsh(mat)
for v in vals:
... |
def _test():
import torch
pretrained = False
models = [(ror3_56_cifar10, 10), (ror3_56_cifar100, 100), (ror3_56_svhn, 10), (ror3_110_cifar10, 10), (ror3_110_cifar100, 100), (ror3_110_svhn, 10), (ror3_164_cifar10, 10), (ror3_164_cifar100, 100), (ror3_164_svhn, 10)]
for (model, num_classes) in models:
... |
_UTILS.register_module()
class OHEMSampler(BaseSampler):
def __init__(self, num, pos_fraction, context, neg_pos_ub=(- 1), add_gt_as_proposals=True, loss_key='loss_cls', **kwargs):
super(OHEMSampler, self).__init__(num, pos_fraction, neg_pos_ub, add_gt_as_proposals)
self.context = context
if ... |
def enable_dropout(m: torch.nn.Module) -> None:
for module in m.modules():
if (module.__class__.__name__ == 'LinearBlock'):
for submodule in module.modules():
if submodule.__class__.__name__.startswith('Dropout'):
submodule.train() |
def disable_running_stats(model):
def _disable(module):
if isinstance(module, _BatchNorm):
module.backup_momentum = module.momentum
module.momentum = 0
model.apply(_disable) |
def test(model, target_test_loader):
model.eval()
correct = 0
criterion = torch.nn.CrossEntropyLoss()
len_target_dataset = len(target_test_loader.dataset)
with torch.no_grad():
for (data, target) in target_test_loader:
(data, target) = (data.to(DEVICE), target.to(DEVICE))
... |
def minimizer_local(args):
from scipy.optimize import minimize
from .cem_function import posterior_function_local_for_minimization
from .parameter import ModelParameters
a = ModelParameters()
(changing_parameter, identifier, global_parameters, errors, elements) = args
res = minimize(fun=posterio... |
class ConsistencyModelPipeline(DiffusionPipeline):
model_cpu_offload_seq = 'unet'
def __init__(self, unet: UNet2DModel, scheduler: CMStochasticIterativeScheduler) -> None:
super().__init__()
self.register_modules(unet=unet, scheduler=scheduler)
self.safety_checker = None
def prepare_... |
def _locobot_camera_action_space():
return spaces.Dict({'set_pan': spaces.Box(low=(- np.inf), high=np.inf, shape=(1,)), 'set_tilt': spaces.Box(low=(- np.inf), high=np.inf, shape=(1,)), 'set_pan_tilt': spaces.Box(low=(- np.inf), high=np.inf, shape=(2,))}) |
def get_run_nums(ex_dir):
not_in = ['_sources', '.ipynb_checkpoints']
run_nums = [x for x in os.listdir(ex_dir) if (x not in not_in)]
return run_nums |
class RopchainJob(job_class):
def __init__(self):
super().__init__()
self.script_file = __file__
self.rop_tool = 'ropper'
def run_rop_tool(self):
rw_address = self.find_rw_section(self.binary)
rop_tool = Ropper(self.binary, self.input, self, self.ropchain, self.bad_chars)... |
def convert_net(net_name, conf, enable_micro):
option = cvt.ConverterOption()
option.name = net_name
option.order = conf.get(ModelKeys.order, 0)
if (ModelKeys.quantize_stat in conf):
option.quantize_stat = conf[ModelKeys.quantize_stat]
else:
option.quantize_stat = False
if (Model... |
def walk_data(nsteps: int, params: P, data: D, key: PRNGKey, metrop_step_fn: MetropolisStep[(P, D)]) -> Tuple[(chex.Numeric, D, PRNGKey)]:
def step_fn(carry, x):
del x
(accept_prob, data, key) = metrop_step_fn(params, carry[1], carry[2])
return (((carry[0] + accept_prob), data, key), None)
... |
class LinformerAttention(nn.Module):
def __init__(self, seq_len, k=256, share_kv=False, softmax_temp=None, attention_dropout=0.0, device=None, dtype=None):
super().__init__()
self.seq_len = seq_len
self.share_kv = share_kv
self.proj_k = nn.Parameter(torch.empty(seq_len, k, device=dev... |
class TestTorchModel(unittest.TestCase):
def setUpClass(self):
pass
def tearDownClass(self):
pass
def test_1(self):
pt_file = '/tf_dataset2/inc-ut/nlptoolkit_ut_model/bert_mini_fp32.pt'
if is_win():
pt_file = 'D:\\dataset\\nlptoolkit_ut_model\\bert_mini_fp32.pt'
... |
class RandomCropVideo(RandomCrop):
def __init__(self, size):
if isinstance(size, numbers.Number):
self.size = (int(size), int(size))
else:
self.size = size
def __call__(self, clip):
(i, j, h, w) = self.get_params(clip, self.size)
return F.crop(clip, i, j, ... |
class pspnet_res18(nn.Module):
def __init__(self, num_classes=19):
super(pspnet_res18, self).__init__()
config_path = './IFR/configs/_base_/models/pspnet_r18-d8.py'
cfg = Config.fromfile(config_path)
self.model = build_segmentor(cfg.model, train_cfg=cfg.get('train_cfg'), test_cfg=cfg... |
def unique_months(arr):
months = set()
for d in arr:
months.add(d[:7])
return sorted(months) |
class DepthWrapper():
def __init__(self, optimizer: Optimizer):
self.cloud_publisher = rospy.Publisher('/transformed_depth_clouds', PointCloud2, queue_size=5)
rospy.wait_for_service('preprocess_cloud')
self.preprocess_cloud = rospy.ServiceProxy('preprocess_cloud', PreprocessCloud)
se... |
def load_checkpoint_to_model(checkpoint, model):
with tempfile.NamedTemporaryFile(delete=False) as file:
torch.save(checkpoint, file.name)
del checkpoint
model.load_state_dict(torch.load(file.name), strict=False)
os.remove(file.name) |
def _load_library(filename, lib='op', load_fn=None):
f = inspect.getfile(sys._getframe(1))
f = os.path.join(os.path.dirname(f), filename)
suffix = get_suffix()
if os.path.exists((f + suffix)):
f = (f + suffix)
filenames = [f]
datapath = os.environ.get('TFPLUS_DATAPATH')
if (datapath ... |
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('', ':6.2f')
top5 = AverageMeter('', ':6.2f')
progress = ProgressMeter(len(val_loader), batch_time, losses, top1, top5, prefix='Test: ')
model.ev... |
class IBertPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class Adam_LBFGS(Optimizer):
def __init__(self, params, switch_epoch=10000, adam_param={'lr': 0.001, 'betas': (0.9, 0.999)}, lbfgs_param={'lr': 1, 'max_iter': 20}):
self.params = list(params)
self.switch_epoch = switch_epoch
self.adam = torch.optim.Adam(self.params, **adam_param)
sel... |
def train_neighbor_model(embedding_data, K=500):
neighbor_model = NearestNeighbors(n_neighbors=500, algorithm='kd_tree', n_jobs=(- 1))
neighbor_model.fit(embedding_data)
dump(neighbor_model, 'models/neighbor_model.joblib')
return neighbor_model |
def test_chained_config_scopes_can_access_preset():
def cfg1(c):
a = (10 + c)
def cfg2(a, c):
b = ((a * 2) + c)
(final_cfg, summary) = chain_evaluate_config_scopes([cfg1, cfg2], preset={'c': 32})
assert (set(final_cfg.keys()) == {'a', 'b', 'c'})
assert (final_cfg['a'] == 42)
asse... |
def wresnet38(x, momentum=0.9, eps=1e-05, use_global_stats=False, name=None, out_internals=False, lr_mult=1, reuse=None):
name = ('' if (name is None) else name)
internals = []
x = wResStem(x, 64, momentum, eps, use_global_stats, bn_data=True, name=name, lr_mult=lr_mult, reuse=reuse)
x = wResBlock(x, 3,... |
def resolve_act_layer(kwargs, default='relu'):
act_layer = kwargs.pop('act_layer', default)
if isinstance(act_layer, str):
act_layer = get_act_layer(act_layer)
return act_layer |
class TestCombineValidSubsets(unittest.TestCase):
def _train(self, extra_flags):
with self.assertLogs() as logs:
with tempfile.TemporaryDirectory('test_transformer_lm') as data_dir:
create_dummy_data(data_dir, num_examples=20)
preprocess_lm_data(data_dir)
... |
def test_group_reid():
n_samples = 30
n_features = 50
n_times = 10
sigma = 1.0
rho = 0.9
corr = toeplitz(np.geomspace(1, (rho ** (n_times - 1)), n_times))
cov = (np.outer(sigma, sigma) * corr)
support_size = 2
(X, Y, beta, noise) = multivariate_temporal_simulation(n_samples=n_samples... |
class SuperMobileSPADE(nn.Module):
def __init__(self, config_text, norm_nc, label_nc, nhidden=128):
super(SuperMobileSPADE, self).__init__()
assert config_text.startswith('spade')
parsed = re.search('spade(\\D+)(\\d)x\\d', config_text)
param_free_norm_type = str(parsed.group(1))
... |
def evaluate_method(gtFilePath, submFilePath, evaluationParams):
for (module, alias) in evaluation_imports().iteritems():
globals()[alias] = importlib.import_module(module)
def polygon_from_points(points):
num_points = len(points)
resBoxes = np.empty([1, num_points], dtype='float32')
... |
def PNBI_np(pred, true, mask_value=None):
if (mask_value != None):
mask = np.where((true > mask_value), True, False)
true = true[mask]
pred = pred[mask]
bias = (pred - true)
indicator = np.where((bias > 0), True, False)
return indicator.mean() |
_lr_scheduler('manual')
class ManualSchedule(LegacyFairseqLRScheduler):
def __init__(self, args, optimizer):
super().__init__(args, optimizer)
self.epoch2lr = self.parse_manuallr_args(args.epoch2lr)
self.update2lr = self.parse_manuallr_args(args.update2lr)
logger.info(' ManualSchedul... |
_module()
class Equalize(ColorTransform):
def _transform_img(self, results: dict, mag: float) -> None:
img = results['img']
results['img'] = mmcv.imequalize(img).astype(img.dtype) |
def comparison_negative(logical_line):
match = COMPARE_NEGATIVE_REGEX.search(logical_line)
if match:
pos = match.start(1)
if (match.group(2) == 'in'):
(yield (pos, "E713 test for membership should be 'not in'"))
else:
(yield (pos, "E714 test for object identity sh... |
def get_all_registered_configs() -> Dict[(str, BaseConfig)]:
return registered_configs.get(FRAMEWORK_NAME, {}) |
def build_categorical_aleatoric_loss(samples):
def categorical_aleatoric_loss(y_true, y_pred):
logits = y_pred[(..., 0)]
sigma = y_pred[(..., 1)]
simulations = ([None] * samples)
for sample in range(samples):
epsilon_t = K.random_normal(K.shape(sigma))
x = act... |
class SpeakerClassifier(nn.Module):
def __init__(self, c_in=512, c_h=512, n_class=8, dp=0.1, ns=0.01):
super(SpeakerClassifier, self).__init__()
(self.dp, self.ns) = (dp, ns)
self.conv1 = nn.Conv1d(c_in, c_h, kernel_size=5)
self.conv2 = nn.Conv1d(c_h, c_h, kernel_size=5)
self... |
_tf2
class TestTCNForecaster(TestCase):
def setUp(self):
from bigdl.chronos.forecaster.tf.tcn_forecaster import TCNForecaster
self.forecaster = TCNForecaster(past_seq_len=10, future_seq_len=2, input_feature_num=10, output_feature_num=2, num_channels=([15] * 7))
def tearDown(self):
del se... |
class TwoWayABlock(nn.Module):
def __init__(self):
super(TwoWayABlock, self).__init__()
in_channels = 384
self.branches = Concurrent()
self.branches.add_module('branch1', ConvSeqBranch(in_channels=in_channels, out_channels_list=(32, 48, 64), kernel_size_list=(1, 3, 3), strides_list=(... |
def get_available_video_models():
return [k for (k, v) in models.video.__dict__.items() if (callable(v) and (k[0].lower() == k[0]) and (k[0] != '_'))] |
def test_list_insert():
run_cell('lst = [0, 1, 2, 4, 5, 6]')
name = lookup_symbol(2).readable_name
assert (name == 'lst[2]'), ('got %s' % name)
name = lookup_symbol(4).readable_name
assert (name == 'lst[3]'), ('got %s' % name)
sym = lookup_symbol(3)
assert (sym is None)
run_cell('lst.ins... |
class NoopProgressBar(BaseProgressBar):
def __init__(self, iterable, epoch=None, prefix=None):
super().__init__(iterable, epoch, prefix)
def __iter__(self):
for obj in self.iterable:
(yield obj)
def log(self, stats, tag=None, step=None):
pass
def print(self, stats, ta... |
class BertTokenizer(PreTrainedTokenizer):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__(self, vocab_file, do_lower_case=True, do_basic_tokenize=True, never_split=None, unk_token='[... |
_module()
class StandardRoIHead(BaseRoIHead):
def init_assigner_sampler(self) -> None:
self.bbox_assigner = None
self.bbox_sampler = None
if self.train_cfg:
self.bbox_assigner = TASK_UTILS.build(self.train_cfg.assigner)
self.bbox_sampler = TASK_UTILS.build(self.train_... |
class CanineTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = CanineTokenizer
test_rust_tokenizer = False
def setUp(self):
super().setUp()
tokenizer = CanineTokenizer()
tokenizer.save_pretrained(self.tmpdirname)
_property
def canine_tokenizer(self):... |
def main():
g = Github(os.environ['GITHUB_TOKEN'])
repo = g.get_repo('huggingface/diffusers')
open_issues = repo.get_issues(state='open')
for issue in open_issues:
comments = sorted(issue.get_comments(), key=(lambda i: i.created_at), reverse=True)
last_comment = (comments[0] if (len(comm... |
class SmoothedValue():
def __init__(self, window_size=20, fmt=None):
if (fmt is None):
fmt = '{median:.4f} ({global_avg:.4f})'
self.deque = deque(maxlen=window_size)
self.total = 0.0
self.count = 0
self.fmt = fmt
def update(self, value, num=1):
self.de... |
_module()
_DATASETS.register_module()
class S3DISSegDataset(_S3DISSegDataset):
def __init__(self, data_root, ann_files, pipeline=None, classes=None, palette=None, modality=None, test_mode=False, ignore_index=None, scene_idxs=None):
ann_files = self._check_ann_files(ann_files)
scene_idxs = self._chec... |
class CarsDataModule(pl.LightningDataModule):
def __init__(self, args):
super().__init__()
self.data_root = args.data_root
self.batch_size = args.batch_size
self.num_workers = args.num_workers
self.train_dataset = CarsDataset(args.data_root, args.resolution, 'train', use_flip... |
def parameters():
params = TrackerParams()
params.debug = 0
params.visualization = False
params.use_gpu = True
params.net = NetWithBackbone(net_path='transt.pth', use_gpu=params.use_gpu)
return params |
def save_csv(f_name, names, *args):
with open(f_name, 'w') as f:
w = csv.writer(f)
valid_idx = [i for i in xrange(len(args)) if (args[i] is not None)]
valid_names = [names[i] for i in valid_idx]
valid_args = [args[i] for i in valid_idx]
w.writerow(valid_names)
w.write... |
def download_train_test_url_txt():
global FashionVideo_root_dir, FashionVideo_train_url_txt, FashionVideo_test_url_txt, TRAIN_URL, TEST_URL
success = download_from_url_to_file(TRAIN_URL, FashionVideo_train_url_txt)
if ((not success) or (not os.path.exists(FashionVideo_train_url_txt))):
raise_error(f... |
def _rename_conv_weights_for_deformable_conv_layers(state_dict, cfg):
import re
logger = logging.getLogger(__name__)
logger.info('Remapping conv weights for deformable conv weights')
layer_keys = sorted(state_dict.keys())
for (ix, stage_with_dcn) in enumerate(cfg.MODEL.RESNETS.STAGE_WITH_DCN, 1):
... |
class SegformerDecodeHead(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def main():
opt = TestOptions().parse()
opt.no_flip = True
opt.batchSize = 1
data_loader = CreateDataLoader(opt)
model = SingleGAN()
model.initialize(opt)
web_dir = os.path.join(opt.results_dir, 'test')
webpage = html.HTML(web_dir, 'task {}'.format(opt.name))
for (i, data) in enumera... |
def get_final_epoch(config):
cfg = mmcv.Config.fromfile(('./configs/' + config))
return cfg.total_epochs |
class Validator(object):
def __init__(self, state_vars, action_vars, plots=[], rows=1, cols=1):
self.threads = []
self.best_thread = []
self.best_thread = 0
self.next_thread = 0
self.state_vars = state_vars
self.action_vars = action_vars
self.plots = plots
... |
_module
class FusedSemanticHead(nn.Module):
def __init__(self, num_ins, fusion_level, num_convs=4, in_channels=256, conv_out_channels=256, num_classes=183, ignore_label=255, loss_weight=0.2, conv_cfg=None, norm_cfg=None):
super(FusedSemanticHead, self).__init__()
self.num_ins = num_ins
self.... |
class conv2DBatchNorm(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding, dilation, bias):
super().__init__()
self.conv = conv(in_channels, out_channels, kernel_size, stride, padding, dilation, bias=bias)
self.batchnorm = nn.BatchNorm2d((out_channels * fac... |
def test_moduledict_weight_init():
models_cfg = dict(foo_conv_1d=dict(type='FooConv1d', init_cfg=dict(type='Constant', layer='Conv1d', val=0.0, bias=1.0)), foo_conv_2d=dict(type='FooConv2d', init_cfg=dict(type='Constant', layer='Conv2d', val=2.0, bias=3.0)))
layers = {name: build_from_cfg(cfg, COMPONENTS) for (... |
class BNTranspose(nn.Module):
def __init__(self, num_features):
super(BNTranspose, self).__init__()
self.num_features = num_features
self.weight = nn.Parameter(torch.Tensor(num_features))
self.reset_parameters()
def reset_parameters(self):
pass
def forward(self, input... |
def english_cleaners(text, table=None):
text = convert_to_ascii(text)
text = lowercase(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
if (table is not None):
text = remove_punctuation(text, table)
text = collapse_whitespace(text)
return text |
def get_human_info(split):
data_root = cfg.virt_data_root
data_name = data_root.split('/')[(- 1)]
if (split == 'train'):
human_info = {'CoreView_313': {'begin_i': 0, 'i_intv': 1, 'ni': 60}, 'CoreView_315': {'begin_i': 0, 'i_intv': 6, 'ni': 400}, 'CoreView_377': {'begin_i': 0, 'i_intv': 30, 'ni': 300... |
def split_speaker(root, num_train):
speaker_list = os.listdir(root)
random.shuffle(speaker_list)
print(len(speaker_list))
with open(log_speaker_path, 'w', encoding='utf-8') as f:
f.write('train:\n')
for i in speaker_list[:num_train]:
f.write((i + ' '))
f.write('\n')
... |
class simam_module(torch.nn.Module):
def __init__(self, channels=None, e_lambda=0.0001):
super(simam_module, self).__init__()
self.activaton = nn.Sigmoid()
self.e_lambda = e_lambda
def __repr__(self):
s = (self.__class__.__name__ + '(')
s += ('lambda=%f)' % self.e_lambda)... |
def split_combined_args(kwargs):
new_kwargs = dict(kwargs)
for (key, value) in kwargs.items():
if key.startswith('__'):
keys = key.split('__')[1:]
values = value.split(';')
assert (len(keys) == len(values)), f"Combined arguments should have equal number of keys and va... |
def test_config_build_detector():
from mmcv import Config
from mmdet.models import build_detector
config_dpath = _get_config_directory()
print(f'Found config_dpath = {config_dpath}')
import glob
config_fpaths = list(glob.glob(join(config_dpath, '**', '*.py')))
config_fpaths = [p for p in con... |
def save_wav_full(save_dir, data_root, json_root):
json_paths = glob.glob(f'{json_root}/*.json')
os.makedirs(save_dir, exist_ok=True)
for json_path in tqdm.tqdm(json_paths):
song_name = os.path.basename(json_path).replace('.json', '')
with open(json_path, 'r') as json_file:
segme... |
def parse_sample(input_files):
inputs = []
for inp in input_files:
inp = utils.load_image_op(inp)
inp = utils.resize_image_op(inp, image_shape_original, conf.image_shape, interpolation=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
inp = utils.one_hot_encode_image_op(inp, conf.one_hot_palette_i... |
def p2():
return [[[[0.5, 0.5], [1.0, 0.0]], [[0.5, 0.5], [0.5, 0.5]]], [[[0.5, 0.5], [0.7, 0.3], [0.1, 0.9]], [[1.0, 0.0], [1.0, 0.0], [1.0, 0.0]]]] |
def train_autokeras(classes, alldata, labels, mtype, jsonfile, problemtype, default_features):
modelname = (jsonfile[0:(- 5)] + ('_autokeras_%s' % default_features))
TEST_FOLDER = modelname
(x_train, x_test, y_train, y_test) = train_test_split(alldata, labels, train_size=0.75, test_size=0.25)
x_train = ... |
def test_categorical_new():
rng = np.random.RandomState(2)
precision = 4
shape = (20, 3, 5)
weights = (rng.random((np.prod(shape), 4)) + 1)
ps = (weights / np.sum(weights, axis=(- 1), keepdims=True))
data = np.reshape([rng.choice(4, p=p) for p in ps], shape)
weights = np.reshape(weights, (sh... |
def _change_reference_point(algorithm: SMPSORP):
number_of_reference_points = len(algorithm.reference_points)
number_of_objectives = algorithm.problem.number_of_objectives
while True:
print(f'Enter {number_of_reference_points}-points of dimension {number_of_objectives}: ')
read = [float(x) f... |
class SparseDispatcher(object):
def __init__(self, num_experts, gates):
self._gates = gates
self._num_experts = num_experts
where = tf.to_int32(tf.where((tf.transpose(gates) > 0)))
(self._expert_index, self._batch_index) = tf.unstack(where, num=2, axis=1)
self._part_sizes_ten... |
class PFNN(NN):
def __init__(self, layer_sizes, activation, kernel_initializer, split_mask=None):
super().__init__()
self.activation = activation_dict[activation]
initializer = initializer_dict[kernel_initializer]
initializer_zero = initializer_dict['zeros']
self.split_mask =... |
class TranAD_SelfConditioning(nn.Module):
def __init__(self, feats):
super(TranAD_SelfConditioning, self).__init__()
self.name = 'TranAD_SelfConditioning'
self.lr = lr
self.batch = 128
self.n_feats = feats
self.n_window = 10
self.n = (self.n_feats * self.n_win... |
class Cider():
def __init__(self, test=None, refs=None, n=4, sigma=6.0):
self._n = n
self._sigma = sigma
def compute_score(self, gts, res):
assert (gts.keys() == res.keys())
imgIds = gts.keys()
cider_scorer = CiderScorer(n=self._n, sigma=self._sigma)
for id in img... |
def get_stem_fun(stem_type):
stem_funs = {'res_stem_cifar': ResStemCifar, 'res_stem_in': ResStemIN, 'simple_stem_in': SimpleStemIN}
assert (stem_type in stem_funs.keys()), "Stem type '{}' not supported".format(stem_type)
return stem_funs[stem_type] |
def tf_efficientnet_l2_ns(pretrained=False, **kwargs):
kwargs['bn_eps'] = BN_EPS_TF_DEFAULT
kwargs['pad_type'] = 'same'
model = _gen_efficientnet('tf_efficientnet_l2_ns', channel_multiplier=4.3, depth_multiplier=5.3, pretrained=pretrained, **kwargs)
return model |
class PSPDec(nn.Module):
def __init__(self, in_features, out_features, downsize, upsize=(64, 128)):
super(PSPDec, self).__init__()
self.features = nn.Sequential(nn.AvgPool2d(downsize, stride=downsize), nn.Conv2d(in_features, out_features, 1, bias=False), nn.BatchNorm2d(out_features, momentum=0.95), ... |
class CBBNorm2d(_CBBNorm):
def _check_input_dim(self, input):
if (input.dim() != 4):
raise ValueError('expected 4D input (got {}D input)'.format(input.dim())) |
def main():
ui_scores = {1: {11: 3, 12: 4, 13: 5, 14: 6, 15: 7}}
gt = {1: [11, 15]}
evaluate_all(ui_scores, gt, 5) |
def test_sgd_classification_small_example():
(w0, w, V, y, X) = get_test_problem(task='classification')
X_test = X.copy()
X_train = sp.csc_matrix(X)
fm = sgd.FMClassification(n_iter=1000, init_stdev=0.1, l2_reg_w=0, l2_reg_V=0, rank=2, step_size=0.1)
fm.fit(X_train, y)
y_pred = fm.predict(X_test... |
class PytorchONNXRuntimeINCMetic(ONNXRuntimeINCMetic):
def stack(self, preds, labels):
(preds, labels) = super().stack(preds, labels)
preds = torch.from_numpy(preds)
labels = torch.from_numpy(labels)
return (preds, labels)
def to_scalar(self, tensor):
return tensor.item() |
class Transweather_base(nn.Module):
def __init__(self, path=None, **kwargs):
super(Transweather_base, self).__init__()
self.Tenc = Tenc()
self.convproj = convprojection_base()
self.clean = ConvLayer(8, 3, kernel_size=3, stride=1, padding=1)
self.active = nn.Tanh()
if ... |
def ProcessRoundDescriptor(segment, parent_node_name, affix, edge_attributes=None):
dot_graph = []
label = 'Round ({0})'.format(segment['arguments'][1])
style = None
if (edge_attributes is not None):
if ('label' in edge_attributes):
label = '{0} {1}'.format(edge_attributes['label'], ... |
def build_dataset(args, rank=0, is_test=False):
tok = get_tokenizer(args)
feat_db_train = ImageFeaturesDB(args.img_ft_file, args.image_feat_size, args.img_aug_ft_file)
feat_db_val = ImageFeaturesDB(args.img_ft_file, args.image_feat_size)
if (args.dataset == 'r2r_back'):
dataset_class = R2RBackBa... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-file_type', default='text', choices=['text', 'field'], required=True, help="Options for vocabulary creation.\n The default is 'text' where the user passes\n a corpus or a list of corp... |
class BatchSampler(Sampler):
def __init__(self, dataset: OxfordDataset, batch_size: int, batch_size_limit: int=None, batch_expansion_rate: float=None):
if (batch_expansion_rate is not None):
assert (batch_expansion_rate > 1.0), 'batch_expansion_rate must be greater than 1'
assert (ba... |
()
('--outdir', help='Where to save the results', metavar='DIR', required=True)
('--cfg', help='Base configuration', type=click.Choice(['fastgan', 'fastgan_lite', 'stylegan2']), required=True)
('--data', help='Training data', metavar='[ZIP|DIR]', type=str, required=True)
('--gpus', help='Number of GPUs to use', metavar... |
def get_num_classes(dataset: str):
if (dataset == 'imagenet'):
return 1000
elif (dataset == 'cifar10'):
return 10
elif (dataset == 'mnist'):
return 10 |
class MMIFrameScorer(PartialScorerInterface):
def __init__(self, lang, device, idim, sos_id, rank, use_segment, char_list, weight_path):
self.lang = lang
self.device = device
self.lexicon = Lexicon(lang)
self.oov = self.oovid = open((self.lang / 'oov.txt')).read().strip()
sel... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, lr_scheduler: torch.optim.lr_scheduler, max_norm: float=0, k_one2many: int=1, lambda_one2many: float=1.0, use_wandb: bool=False, use_fp16: bool=False, scaler... |
.parametrize('func,args', [(foo, [1]), (bariza, [1, 2, 3, 4]), (complex_function_name, [1, 2, 3, 4]), (old_name, [1, 2]), (renamed, [1, 2])])
def test_construct_arguments_with_unexpected_args_raises_typeerror(func, args):
unexpected = re.compile('.*unexpected.*')
with pytest.raises(TypeError) as excinfo:
... |
class ImagesFromDataList(data.Dataset):
def __init__(self, images, transform=None):
if (len(images) == 0):
raise RuntimeError('Dataset contains 0 images!')
self.images = images
self.transform = transform
def __getitem__(self, index):
img = self.images[index]
i... |
class CloudpickleWrapper():
def __init__(self, fn: Callable):
self.fn = fn
def __getstate__(self):
import cloudpickle
return cloudpickle.dumps(self.fn)
def __setstate__(self, ob):
import pickle
self.fn = pickle.loads(ob)
def __call__(self):
return self.fn(... |
def get_incomplete_data(voxels, p=0.3):
num_points = int(np.prod(voxels.shape))
num_ones = int((num_points * p))
mask = np.append(np.ones(num_ones), np.zeros((num_points - num_ones)))
np.random.shuffle(mask)
mask = mask.reshape(*voxels.shape)
voxel_mean = (np.sum((voxels * mask)) / np.sum(mask))... |
def data_transforms(dataset_type='train', normlize_type='-1-1'):
transforms = {'train': Compose([ReSize(size=0.97), Reshape(), Normalize(normlize_type), Retype()]), 'val': Compose([ReSize(size=0.97), Reshape(), Normalize(normlize_type), Retype()])}
return transforms[dataset_type] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.