code stringlengths 101 5.91M |
|---|
class XmodForQuestionAnswering(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def read(*names, **kwargs):
with io.open(join(dirname(__file__), *names), encoding=kwargs.get('encoding', 'utf8')) as fh:
return fh.read() |
def tensor2im(input_image, imtype=np.uint8):
if isinstance(input_image, torch.Tensor):
input_image = F.upsample(input_image, size=(256, 256), mode='bilinear')
image_tensor = input_image.data
else:
return input_image
image_numpy = image_tensor[0].cpu().float().numpy()
if (image_nu... |
.ml_cpu_only
.parametrize('batch_size', [2, 3, 8])
def test_radius_search_batches(ml, batch_size):
dtype = np.float32
metric = 'L2'
p_norm = {'L1': 1, 'L2': 2, 'Linf': np.inf}[metric]
ignore_query_point = False
return_distances = True
normalize_distances = True
rng = np.random.RandomState(12... |
def dobldobl_laursys_solve(pols, topdim=(- 1), filter=True, factor=True, tasks=0, verbose=True):
from phcpy.phcpy2c3 import py2c_dobldobl_laursys_solve
from phcpy.phcpy2c3 import py2c_copy_dobldobl_laursys_witset
from phcpy.solver import number_of_symbols
from phcpy.interface import store_dobldobl_laure... |
def get_model(config):
class SimpleModel(gluon.Block):
def __init__(self, **kwargs):
super(SimpleModel, self).__init__(**kwargs)
self.fc1 = nn.Dense(20)
self.fc2 = nn.Dense(10)
def forward(self, x):
x = self.fc1(x)
x = self.fc2(x)
... |
def default_compute_objective(metrics: Dict[(str, float)]) -> float:
metrics = copy.deepcopy(metrics)
loss = metrics.pop('eval_loss', None)
_ = metrics.pop('epoch', None)
speed_metrics = [m for m in metrics.keys() if (m.endswith('_runtime') or m.endswith('_per_second') or m.endswith('_compilation_time')... |
def nevergrad_get_setting(self):
method = self._method_chooser.ask()
params = self._optimizers[method.args[0]].ask()
return {'method_token': method, 'method': method.args[0], 'params_token': params, 'params': params.args[0]} |
class ResNet(Model):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
self._norm_lay... |
class RMSLELoss(nn.Module):
def __init__(self):
super().__init__()
self.mse = nn.MSELoss()
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return torch.sqrt(self.mse(torch.log((input + 1)), torch.log((target + 1)))) |
def train():
if (args.model == 'QRNN'):
model.reset()
total_loss = 0
start_time = time.time()
ntokens = len(corpus.dictionary)
hidden = model.init_hidden(args.batch_size)
(batch, i) = (0, 0)
while (i < ((train_data.size(0) - 1) - 1)):
bptt = (args.bptt if (np.random.random() ... |
def k_fold(dataset, folds=10):
skf = StratifiedKFold(folds, shuffle=True, random_state=12345)
(train_indices, test_indices) = ([], [])
ys = dataset.data.y
for (train, test) in skf.split(torch.zeros(len(dataset)), ys):
train_indices.append(torch.from_numpy(train).to(torch.long))
test_indi... |
def reconstruction_error_vis(S1, S2, reduction='mean', visible_kpts=None):
assert (visible_kpts is not None)
S1_hat = compute_similarity_transform_batch(S1, S2)
re = ((np.sqrt(((S1_hat - S2) ** 2).sum(axis=(- 1))) * visible_kpts).sum(axis=(- 1)) / visible_kpts.sum(axis=(- 1)))
return re |
def load_model_from_config(config, ckpt, verbose=False):
print(f'Loading model from {ckpt}')
pl_sd = torch.load(ckpt, map_location='cpu')
if ('global_step' in pl_sd):
print(f"Global Step: {pl_sd['global_step']}")
sd = pl_sd['state_dict']
model = instantiate_from_config(config.model)
(m, ... |
def load_extrinsics(path_trajectory, config):
extrinsics = []
if path_trajectory.endswith('log'):
data = o3d.io.read_pinhole_camera_trajectory(path_trajectory)
for param in data.parameters:
extrinsics.append(param.extrinsic)
elif path_trajectory.endswith('json'):
data = o... |
class Test_angle_sequence(unittest.TestCase):
def test_poly2laurent_1(self):
pcoefs = np.array([((- 3) - 2j), 0.0, (26 + 10j), 0.0, ((- 24) - 8j)])
expected = (np.array([((- 3) - 1j), (1 + 1j), 2.0, (1 + 1j), ((- 3) - 1j)]) / 2.0)
result = poly2laurent(pcoefs)
self.assertAlmostEqual(... |
def nfsp_oshi_ppo_avg_policy_params_two_layers_no_valid_actions_model(env: MultiAgentEnv) -> Dict[(str, Any)]:
params = nfsp_leduc_avg_policy_params(env=env)
params['model']['custom_model'] = None
params['model']['fcnet_hiddens'] = [64, 64]
return params |
class Registry(object):
def __init__(self, name):
self._name = name
self._module_dict = dict()
def __repr__(self):
format_str = (self.__class__.__name__ + '(name={}, items={})'.format(self._name, list(self._module_dict.keys())))
return format_str
def name(self):
retur... |
('/update_log.xml')
def products_xml(competitions=competitions):
num_largest = 2
comps_pubtime = np.array([int(i['pubtime'].replace('-', '')) for i in competitions])
time_largest = heapq.nlargest(num_largest, np.unique(comps_pubtime))
index_largest = [np.where((comps_pubtime == largest_value))[0].tolist... |
class EpisodeIterator(Iterator):
def __init__(self, episodes: List[T], cycle: bool=True, shuffle: bool=False, group_by_scene: bool=True, max_scene_repeat_episodes: int=(- 1), max_scene_repeat_steps: int=(- 1), num_episode_sample: int=(- 1), step_repetition_range: float=0.2, seed: int=None):
if seed:
... |
def _test():
import torch
pretrained = False
models = [vgg11, vgg13, vgg16, vgg19, bn_vgg11, bn_vgg13, bn_vgg16, bn_vgg19, bn_vgg11b, bn_vgg13b, bn_vgg16b, bn_vgg19b]
for model in models:
net = model(pretrained=pretrained)
net.eval()
weight_count = _calc_width(net)
print(... |
class Exp_Basic(object):
def __init__(self, args):
self.args = args
self.device = self._acquire_device()
self.model = self._build_model().to(self.device)
def _build_model(self):
raise NotImplementedError
return None
def _acquire_device(self):
if self.args.use_... |
def vqa_collate(inputs):
(qids, input_ids, attn_masks_txt, img_input_ids, img_feats, img_pos_feats, attn_masks_img, targets) = map(list, unzip(inputs))
txt_lens = [i.size(0) for i in input_ids]
input_ids = pad_sequence(input_ids, batch_first=True, padding_value=0)
position_ids = torch.arange(0, input_id... |
def y_true_header(outcome, underscore=False):
return ((str(outcome) + ('_' if underscore else '-')) + 'y_true0') |
class TestNativeCheckpointableIterator(unittest.TestCase, TestCheckpointableIterator):
def setUp(self):
self.expected_result = list(range(53))
self.iterator = NativeCheckpointableIterator(self.expected_result)
def test_iterator_exception(self):
self.assertRaises(ValueError, NativeCheckpo... |
def resize_n_crop(image, M, dsize=112):
return warp_affine(image, M, dsize=(dsize, dsize), align_corners=True) |
class GMAUpdateBlock(nn.Module):
def __init__(self, args, hidden_dim=128):
super().__init__()
self.args = args
self.encoder = BasicMotionEncoder(args)
self.gru = SepConvGRU(hidden_dim=hidden_dim, input_dim=((128 + hidden_dim) + hidden_dim))
self.flow_head = FlowHead(hidden_di... |
def _find_miopen_config(rocm_install_path):
def miopen_version_numbers(path):
possible_version_files = ['include/miopen/version.h', 'miopen/include/miopen/version.h']
version_file = None
for f in possible_version_files:
version_file_path = os.path.join(path, f)
if os.... |
def preprocess(image):
image = tf.image.resize(image, (346, 346))
image = tf.image.crop_to_bounding_box(image, ((346 - 289) // 2), ((346 - 289) // 2), 289, 289)
return image |
def load_data(fpath, entities, w2i, system_acts):
data = []
with open(fpath, 'r') as f:
lines = f.readlines()
(x, y, c, b, p, f) = ([], [], [], [], [], [])
context = ([0] * len(entities.keys()))
for (idx, l) in enumerate(lines):
l = l.rstrip()
if (l == '')... |
class BaseExp(metaclass=ABCMeta):
def __init__(self):
self.seed = None
self.output_dir = './YOLOX_outputs'
self.print_interval = 100
self.eval_interval = 10
def get_model(self) -> Module:
pass
def get_data_loader(self, batch_size: int, is_distributed: bool) -> Dict[(s... |
def load_optimized_unet(cache_dir=None, unet_attributes=None, accelerator='openvino', ipex=True, precision='float32', device='CPU', low_memory=False, lora_name=None, additional_suffix=None):
t_start = time.perf_counter()
if ((cache_dir is None) and (unet_attributes is None)):
print(f'You should provide ... |
class MCLayer(nn.Module):
def __init__(self, size_in, size_out):
super().__init__()
(self.size_in, self.size_out) = (size_in, size_out)
weights = torch.Tensor(size_out, size_in)
self.weights = nn.Parameter(weights)
bias = torch.Tensor(size_out)
self.bias = nn.Paramete... |
def getTrainIndex(n):
trainIndex = list()
for i in range((n * n)):
row = math.floor((i / n))
col = np.mod(i, n)
if (((row % 2) == 0) or ((col % 2) == 0)):
trainIndex.append(i)
return trainIndex |
class ResEncoder(nn.Module):
def __init__(self, in_channels, out_channels):
super(ResEncoder, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1)
self.bn1 = nn.BatchNorm2d(out_channels)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel... |
def merge_hparams(policy: dict, hparams: dict):
op = PIPELINES.get(policy['type'])
assert (op is not None), f"""Invalid policy type "{policy['type']}"."""
for (key, value) in hparams.items():
if (policy.get(key, None) is not None):
continue
if (key in inspect.getfullargspec(op.__... |
def main():
for epoch in range(start_epoch, (start_epoch + 40)):
(train_loss, train_err) = train(epoch)
(test_loss, test_err) = test(epoch)
draw_curve(epoch, train_loss, train_err, test_loss, test_err)
if (((epoch + 1) % 20) == 0):
lr_decay() |
class IPAdapterXL(IPAdapter):
def generate(self, pil_image, prompt=None, negative_prompt=None, scale=1.0, num_samples=4, seed=(- 1), num_inference_steps=30, **kwargs):
self.set_scale(scale)
if isinstance(pil_image, Image.Image):
num_prompts = 1
else:
num_prompts = len... |
def compute_avg_return(environment, policy, num_episodes=10):
total_return = 0.0
for _ in range(num_episodes):
time_step = environment.reset()
episode_return = 0.0
while (not time_step.is_last()):
action_step = policy.action(time_step)
time_step = environment.step... |
def class2onehot(idx, class_num):
assert (torch.max(idx).item() < class_num)
onehot = torch.zeros(idx.size(0), class_num).to(idx.device)
onehot.scatter_(1, idx, 1)
return onehot |
class GTScaleDown(object):
def __init__(self, factor=8):
self.factor = factor
def __call__(self, img):
(w, h) = img.size
if (self.factor == 1):
return img
tmp = ((np.array(img.resize(((w // self.factor), (h // self.factor)), Image.BICUBIC)) * self.factor) * self.facto... |
class history():
def __init__(self):
self.num_runs = int(0)
self.total_num_search = int(0)
self.fx = np.zeros(MAX_SEARCH, dtype=float)
self.chosen_actions = np.zeros(MAX_SEARCH, dtype=int)
self.terminal_num_run = np.zeros(MAX_SEARCH, dtype=int)
self.time_total_ = np.z... |
def train_cv_poison(helper, model, poison_optimizer, criterion):
total_loss = 0.0
num_data = 0.0
for x1 in helper.poisoned_train_data:
(inputs_p, labels_p) = x1
inputs = inputs_p
for pos in range(labels_p.size(0)):
labels_p[pos] = helper.params['poison_label_swap']
... |
_model
def scalable_vit_small(pretrained=False, **kwargs):
img_size = 224
model = ScalableViT(img_size=img_size, patch_size=4, embed_dims=[64, 128, 256, 512], num_heads=[2, 4, 8, 16], mlp_ratios=[4, 4, 4, 4], qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-06), depths=[2, 2, 20, 2], wss=[7, 7, 7, 7], sr_... |
_module()
class ClsHead(nn.Module):
def __init__(self, num_classes: int, in_channels: int, mlps: List[int]=[256], norm_args: dict=None, act_args: dict={'act': 'relu'}, dropout: float=0.5, global_feat: str=None, point_dim: int=2, **kwargs):
super().__init__()
if kwargs:
logging.warning(f'... |
def vilmedic_collate(batch, multi_image=None):
if ((not multi_image) or (multi_image == 1)):
return {'images': torch.stack([s['image'][0] for s in batch]), 'images_mask': None}
new_batch = []
new_masks = []
for sample in batch:
sample_images = sample['image']
if (len(sample_image... |
class BasicTokenizer(object):
def __init__(self, do_lower_case=True):
self.do_lower_case = do_lower_case
def tokenize(self, text):
text = self._clean_text(text)
text = self._tokenize_chinese_chars(text)
orig_tokens = whitespace_tokenize(text)
split_tokens = []
for... |
def cstr(arg, arg_name, default, custom_str=False):
not_default = (arg != default)
if (not custom_str):
custom_str = f'_{arg_name}{arg}'
return (custom_str if not_default else '') |
def preresnetbc26b(**kwargs):
return get_preresnet(blocks=26, bottleneck=True, conv1_stride=False, model_name='preresnetbc26b', **kwargs) |
def export_intrinsics(save_root: Path, overwrite: bool=False) -> None:
out_dir = (save_root / 'calibs')
if ((not overwrite) and out_dir.is_dir()):
print(f'-> Skipping LMDB calibrations...')
return
print(f"""-> Exporting intrinsics "{(save_root / 'calibs')}"...""")
data = {seq: stv.load_i... |
.parametrize('gpu2gpu', [False, True])
def test_rl_vectorized_envs(gpu2gpu):
import habitat_sim
if (gpu2gpu and (not habitat_sim.cuda_enabled)):
pytest.skip('GPU-GPU requires CUDA')
(configs, datasets) = _load_test_data()
for config in configs:
config.defrost()
config.SIMULATOR.H... |
class TensorflowGraph(tf.Graph):
def __init__(self, flags):
super().__init__()
self.name = ''
self.dropout_rate = flags.dropout_rate
self.activator = flags.activator
self.batch_norm = flags.batch_norm
self.cnn_size = flags.cnn_size
self.cnn_stride = 1
... |
def visualize_result(df, filename):
ax = sns.lineplot(data=df, dashes=False)
ax.figure.savefig(filename, dpi=250)
plt.close() |
def cifar100_val_loader(dataset_name, val_batch_size, num_workers=4, pin_memory=True, normalize=None):
if (normalize is None):
normalize = transforms.Normalize(mean=mean[dataset_name], std=std[dataset_name])
val_dataset = datasets.ImageFolder('data/cifar100_org/test/{}'.format(dataset_name), transforms.... |
class MixerBlock(nn.Module):
def __init__(self, num_patches: int, num_channels: int, tokens_hidden_dim: int, channels_hidden_dim: int):
super().__init__()
self.token_mixing = nn.Sequential(nn.LayerNorm(num_channels), Rearrange('b p c -> b c p'), MLPBlock(num_patches, tokens_hidden_dim), Rearrange('b... |
class MultiNLI():
def __init__(self, options):
print('preparing the dataset for training...')
self.TEXT = Field(lower=True, tokenize='spacy', batch_first=True)
self.LABEL = Field(sequential=False, unk_token=None, is_target=True)
(self.train, self.dev, self.test) = datasets.MultiNLI.s... |
class TestOutput():
def test_position_raises_value_error_more(self):
output_seq = output.OutputSeq(tokens=[0, 0], n_input_tokens=1)
with pytest.raises(ValueError):
output_seq.position(position=4)
def test_position_raises_value_error_less(self):
output_seq = output.OutputSeq(t... |
class ChannelAttentionBlock3d(nn.Module):
def __init__(self, in_channels):
super(ChannelAttentionBlock3d, self).__init__()
self.gamma = nn.Parameter(torch.zeros(1))
self.softmax = nn.Softmax(dim=(- 1))
def forward(self, x):
(B, C, H, W, D) = x.size()
proj_query = x.view(B... |
class UserCommands(BaseTransformersCLICommand):
def register_subcommand(parser: ArgumentParser):
login_parser = parser.add_parser('login', help='Log in using the same credentials as on huggingface.co')
login_parser.set_defaults(func=(lambda args: LoginCommand(args)))
whoami_parser = parser.a... |
def normalize_answer(s):
def white_space_fix(text):
return ' '.join(text.split())
def lower(text):
return text.lower()
return white_space_fix(lower(s)) |
def TestTraining():
a = GenerateData()
TreatedAtoms = a.AtomTypes()
PARAMS['NetNameSuffix'] = 'training_sample'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 15
PARAMS['batch_size'] = 100
PARAMS['test_freq'] = 5
PARAMS['tf_prec'] = 'tf.float64'
P... |
class BaseProgressBar(object):
def __init__(self, iterable, epoch=None, prefix=None):
self.iterable = iterable
self.offset = getattr(iterable, 'offset', 0)
self.epoch = epoch
self.prefix = ''
if (epoch is not None):
self.prefix += 'epoch {:03d}'.format(epoch)
... |
def main(args):
filepaths = [os.path.join(args.csv_dir, v) for v in os.listdir(args.csv_dir) if ('features' in v)]
for csv_filepath in filepaths:
util.green_print(csv_filepath)
filepath = util.create_output_path(csv_filepath)
(emb_array, labels) = util.readEmb_csv(csv_filepath)
t... |
class Constraint(object):
def __init__(self, constraint=None):
self._constraint = constraint
self._ccontents = self._constraint.contents
def _get_max_force(self):
return self._ccontents.maxForce
def _set_max_force(self, f):
self._ccontents.maxForce = f
max_force = propert... |
def reduce_states(rssm_states: list, dim, func):
return RSSMState(*[func([getattr(state, key) for state in rssm_states], dim=dim) for key in rssm_states[0].__dict__.keys()]) |
def restore_model(pkl_file, checkpoint=None, train=False, fp16=None):
info = load_pickle(pkl_file)
init = info['init']
name = info['name']
search_in = join(CoTr.__path__[0], 'training', 'network_training')
tr = recursive_find_python_class([search_in], name, current_module='CoTr.training.network_trai... |
def modelSize(net):
params = 0
for e in net.parameters():
params += np.prod(e.size())
params = int((params / 1000))
print('Network has ', params, 'K params') |
class ClassBalancedRandomSampling():
class_index_cache = None
class_num_cache = None
def sample(cls, buffer_x, buffer_y, n_smp_cls, excl_indices=None, device='cpu'):
if (excl_indices is None):
excl_indices = set()
sample_ind = torch.tensor([], device=device, dtype=torch.long)
... |
def ReadFileGS(x_axis, tthread, batchInterval, NUM_ITEMS, NUM_ACCESS, key_skewness, overlap_ratio, abort_ratio, isCyclic, complexity):
(w, h) = (3, len(x_axis))
y = [[] for _ in range(w)]
if (isCyclic == 'true'):
for NUM_ACCESS in x_axis:
inputEvents = (tthread * batchInterval)
... |
def download_dataset(data_path, file_ids):
for (file_name, file_id) in file_ids.items():
save_path = osp.abspath(osp.join(data_path, file_name))
if osp.exists(save_path):
user_response = input(f'{file_name} already exist. Do you want to cover it? Y/N ')
if (user_response.lo... |
class BaseModel(nn.Module):
def __init__(self, backbone: str='MiT-B0', num_classes: int=19, modals: list=['rgb', 'depth', 'event', 'lidar']) -> None:
super().__init__()
(backbone, variant) = backbone.split('-')
self.backbone = eval(backbone)(variant, modals)
self.modals = modals
... |
def le_net_cifar(pretrained: bool=False, progress: bool=True, num_classes: int=10):
return LeNetCIFAR() |
class HUD(object):
def __init__(self, name, width, height):
self.name = name
self.dim = (width, height)
self._init_hud_params()
self._init_data_params()
def start(self):
def _init_hud_params(self):
font_name = ('courier' if (os.name == 'nt') else 'mono')
fonts... |
def preprocess_image(image, device):
image = ((torch.from_numpy(image).float() / 127.5) - 1)
image = rearrange(image, 'h w c -> 1 c h w')
image = image.to(device)
return image |
def frontend(x, is_training, yInput, num_filt, type):
expand_input = tf.expand_dims(x, 3)
normalized_input = tf.compat.v1.layers.batch_normalization(expand_input, training=is_training)
if ('timbral' in type):
input_pad_7 = tf.pad(normalized_input, [[0, 0], [3, 3], [0, 0], [0, 0]], 'CONSTANT')
... |
class Conv3dGaussian(ConvNdGaussianMixin, torch.nn.Conv3d):
def forward(self, input):
return self._forward_impl(input, F.conv3d) |
class ImageDataManager(DataManager):
data_type = 'image'
def __init__(self, args):
root = args.datadir
sources = args.data_train.lower().split('+')
targets = args.data_test.lower().split('+')
height = args.height
width = args.width
transforms = ['random_flip', 'ra... |
def ReadFileSL(x_axis, batchInterval, NUM_ITEMS, deposit_ratio, key_skewness, overlap_ratio, abort_ratio, isCyclic, complexity):
(w, h) = (3, len(x_axis))
y = [[] for _ in range(w)]
deposit_ratio_range = [25, 50, 75]
key_skewness_range = [25, 50, 75]
abort_ratio_range = [1, 10, 100]
NUM_ITEMS_ra... |
def FORCESNLPsolver_normal_solve(params_arg):
global _lib
params_py = FORCESNLPsolver_normal_params_ctypes()
for par in params_arg:
try:
if isinstance(getattr(params_py, par), ctypes.Array):
params_arg[par] = np.require(params_arg[par], dtype=FORCESNLPsolver_normal_params... |
def _is_discrete(space: jaxmarl_spaces.Space) -> bool:
return isinstance(space, (gymnax_spaces.Discrete, jaxmarl_spaces.Discrete)) |
class SpladeEvaluater(Trainer):
rounding_func = torch.round
def prediction_step(self, model, inputs: Dict[(str, Union[(torch.Tensor, Any)])], prediction_loss_only: bool, ignore_keys: Optional[List[str]]=None) -> Tuple[(Optional[torch.Tensor], Optional[torch.Tensor], Optional[torch.Tensor])]:
assert (pre... |
class IndepAnisotropicGaussianUVLoss(nn.Module):
def __init__(self, sigma_lower_bound: float):
super(IndepAnisotropicGaussianUVLoss, self).__init__()
self.sigma_lower_bound = sigma_lower_bound
self.log2pi = math.log((2 * math.pi))
def forward(self, u: torch.Tensor, v: torch.Tensor, sigma... |
.slow
def test_harmonic_oscillator_vmc_ibp(caplog):
model_omega = 5
spring_constant = 1.5
nchains = (100 * jax.local_device_count())
nburn = 100
nepochs = 100
nsteps_per_param_update = 5
std_move = 0.25
learning_rate = 0.001
(log_psi_model, params, random_particle_positions, amplitud... |
class BaseMock():
def __init__(self, *args, **kwargs):
self.base_state = mock.MagicMock()
self.base_state.bumper = False
def go_to_relative(self, *args, **kwargs):
pass |
class L2Regularization(Regularizer):
def __init__(self, model, value=0.001, filter={'parameter_name': is_not_bias, 'module': is_not_bn}, pre_op=True, post_op=False, **kwargs):
super(L2Regularization, self).__init__(model, value, filter=filter, **kwargs)
self.pre_op = pre_op
self.post_op = po... |
class BottomUpEnsembling(BaseEstimator):
def __init__(self, model='l2', custom_cost=None, min_size=2, jump=5, params=None):
if ((custom_cost is not None) and isinstance(custom_cost, BaseCost)):
self.cost = custom_cost
elif (params is None):
self.cost = cost_factory(model=mode... |
def named_relevance(module, prefix='', **kwargs):
for (name, mod) in module.named_modules(prefix=prefix):
if isinstance(mod, BaseARD):
(yield (name, mod.relevance(**kwargs).detach())) |
def test_concat_cell():
inputs_x = torch.randn([2, 256, 32, 32])
inputs_y = torch.randn([2, 256, 16, 16])
concat_cell = ConcatCell(256, 256)
output = concat_cell(inputs_x, inputs_y, out_size=inputs_x.shape[(- 2):])
assert (output.size() == inputs_x.size())
output = concat_cell(inputs_x, inputs_y... |
def rla_resnet152(rla_channel=32):
print('Constructing rla_resnet152......')
model = RLA_ResNet(RLA_Bottleneck, [3, 8, 36, 3])
return model |
def power_analysis_dataset(system_scores, sample_nums=None, trial_num=1000, num_workers=32, verbose=False):
if (sample_nums is None):
sample_nums = [10, 50, 100, 200, 300, 500, 700, 1000, 10000]
systems = system_scores.keys()
systems = sorted(list(systems))
all_system_pairs = list(combinations(s... |
class SSDMobileNetV1FeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):
def __init__(self, is_training, depth_multiplier, min_depth, pad_to_multiple, conv_hyperparams, batch_norm_trainable=True, reuse_weights=None):
super(SSDMobileNetV1FeatureExtractor, self).__init__(is_training, depth_multiplier, min_dep... |
.parametrize('training', [True, False, None])
def test_cplx_concatenated_casting_float_onnx_export(training):
module = torch.nn.Sequential(casting.ConcatenatedRealToCplx(), nn.CplxIdentity(), casting.CplxToConcatenatedReal())
input = torch.randn(2, 16, 256)
do_onnx_export_test(module.float(), input.float(),... |
class VizWizDataset(VQA2Dataset):
def __init__(self, dataset_type, imdb_file_index, config, *args, **kwargs):
super().__init__(dataset_type, imdb_file_index, config, *args, **kwargs)
self._name = 'vizwiz'
def load_item(self, idx):
sample = super().load_item(idx)
sample_info = sel... |
def reject_outliers(data, m=3):
stdev = np.std(data)
mean = np.mean(data)
mask_min = (mean - (stdev * m))
mask_max = (mean + (stdev * m))
outliers = [d for d in data if ((d < mask_min) or (d > mask_max))]
print(f'Warning: removing {len(outliers)} outliers:')
print(outliers)
return [d for... |
def resnet50(pretrained=False, **kwargs):
model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
if pretrained:
os.makedirs(default_cache_path, exist_ok=True)
model.load_state_dict(torch.load(download_from_url(model_urls['resnet50'], root=default_cache_path)))
return model |
()
def main(source: LoaderSwitch, split: str='test', model: str=None, seed: int=42):
tf.random.set_seed(seed)
codebook_model = load_model(model)
def get_reconstructed_image(batch):
x = tf.image.convert_image_dtype(batch['frames'], 'float32')
x = codebook_model(x)[0]
x = tf.clip_by_va... |
def resnext50_32x4d(pretrained: bool=False, progress: bool=True, **kwargs) -> nn.Module:
kwargs['groups'] = 32
kwargs['width_per_group'] = 4
return _resnet('resnext50_32x4d', Bottleneck, [3, 4, 6, 3], pretrained, progress, **kwargs) |
class Factory(BaseFactory):
def pt_defaults_scope_value():
return {'activation_fn': default_activation.current_value, 'batch_normalize': True, 'learned_moments_update_rate': 0.0003, 'variance_epsilon': 0.001, 'scale_after_normalization': True}
default_patch_feature_dim = 8
def __init__(self, output_... |
class SideOnly(MergeOperator):
def __call__(self, base_encoding, side_encoding, additional_encodings=[]):
return side_encoding |
class HistoryManager():
def __init__(self, coin_number, end, volume_average_days=1, volume_forward=0, online=True):
self.initialize_db()
self.__storage_period = FIVE_MINUTES
self._coin_number = coin_number
self._online = online
if self._online:
self._coin_list = C... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.