code stringlengths 101 5.91M |
|---|
def test_cache_directory_set(mkdir: MagicMock) -> None:
my_dir: str = '~/my_dir'
cache.config.cache_directory = my_dir
assert (cache.config.cache_directory == my_dir)
assert mkdir.called_once_with(my_dir) |
def clip_by_tensor(t, t_min, t_max):
t = t.float()
result = (((t >= t_min).float() * t) + ((t < t_min).float() * t_min))
result = (((result <= t_max).float() * result) + ((result > t_max).float() * t_max))
return result |
def init_model(model, opt, argv):
if (hasattr(opt, 'weight_init') and (opt.weight_init == 'xavier')):
network_weight_xavier_init(model)
elif (hasattr(opt, 'weight_init') and (opt.weight_init == 'MSRAPrelu')):
network_weight_MSRAPrelu_init(model)
elif (hasattr(opt, 'weight_init') and (opt.wei... |
def mhgls_params_from_sums(sums, YY, ybar):
(C, S, CC, CS, SS, YC, YS) = sums
nharms = len(C)
A = np.block([[CC, CS], [CS.T, SS]])
b = np.concatenate((YC, YS))
theta = np.linalg.solve(A, b)
cn = theta[:nharms]
sn = theta[nharms:]
offset = (ybar - (np.dot(cn, C) + np.dot(sn, S)))
retu... |
def get_loader(image_root, gt_root, batchsize, trainsize, test_root, test_gt_root, shuffle=True, num_workers=12, pin_memory=True):
dataset = SalObjDataset(image_root, gt_root, trainsize)
data_loader = data.DataLoader(dataset=dataset, batch_size=batchsize, shuffle=shuffle, num_workers=num_workers, pin_memory=pin... |
def main():
init_ivadomed()
parser = get_parser()
args = parser.parse_args()
visualize_and_compare_models(args.ofolders, args.metric, args.metadata) |
def wrap_if_pmap(p_func: Callable) -> Callable:
def p_func_if_pmap(obj, axis_name):
try:
core.axis_frame(axis_name)
return p_func(obj, axis_name)
except NameError:
return obj
return p_func_if_pmap |
class Experiment(object):
def __init__(self, L, E):
self.Loader = L
self.Eval = E
self.Model = L.Model
if ((L.MODE in 'test') or (L.mode == 'ft')):
self.Model.load_state_dict(torch.load(L.mpath, map_location='cpu'))
self.Model = (self.Model.eval() if (L.MODE == 't... |
def generate_predicted_files():
symbol_file_path = '../symbol_farm/symbol_64_512_16L_3scales_v1_deploy.json'
model_file_path = '../saved_model/configuration_64_512_16L_3scales_v1_2019-09-29-13-41-44/train_64_512_16L_3scales_v1_iter_600000.params'
my_predictor = Predict(mxnet=mxnet, symbol_file_path=symbol_f... |
def stop_gradient_if_not(cond, *args):
outputs = []
for v in args:
outputs.append(tf.reshape(tf.where(cond, v, tf.stop_gradient(v)), get_shape(v)))
if (len(outputs) == 0):
outputs = None
elif (len(outputs) == 1):
outputs = outputs[0]
else:
outputs = tuple(outputs)
... |
class SingleEdgeGraphFormatter(BaseGraphFormatter):
def __init__(self, config, name='SingleEdgeGraphFormatter'):
self.name = name
self.config = config
BaseGraphFormatter.__init__(self, config, name)
def format(self, item_json, vocab_dicts):
(token_vd, node_vd, target_vd, word_vd)... |
class AnyDataset(Dataset):
def __init__(self, root=None, file=None, split=None, processing=None, name=None, **kwargs):
assert (split is not None), 'Argument split cannot be None'
self.root = root
self.file = file
self.split = split
self.name = (name or 'any')
self.pro... |
class ImageFolder(DatasetFolder):
def __init__(self, root, transform=None, target_transform=None, loader=default_loader):
super(ImageFolder, self).__init__(root, loader, IMG_EXTENSIONS, transform=transform, target_transform=target_transform)
self.imgs = self.samples |
class IN22KDATASET(data.Dataset):
def __init__(self, root, ann_file='', transform=None, target_transform=None):
super(IN22KDATASET, self).__init__()
self.data_path = root
self.ann_path = os.path.join(self.data_path, ann_file)
self.transform = transform
self.target_transform =... |
def mixconv1x1_block(in_channels, out_channels, kernel_count, stride=1, groups=1, bias=False, use_bn=True, bn_eps=1e-05, activation=(lambda : nn.ReLU(inplace=True))):
return MixConvBlock(in_channels=in_channels, out_channels=out_channels, kernel_size=([1] * kernel_count), stride=stride, padding=([0] * kernel_count)... |
def _pad_num_var_param(rstart=1, max=None):
r = rstart
ret = []
while (r <= __MAX_RANK__):
h = (r * 2)
if ((max is not None) and (h > max)):
break
ret.append(h)
r += 1
return ret |
def get_last_checkpoint_if_any(checkpoint_folder):
os.makedirs(checkpoint_folder, exist_ok=True)
files = glob('{}/*.h5'.format(checkpoint_folder), recursive=True)
if (len(files) == 0):
return None
return natural_sort(files)[(- 1)] |
.ml_torch_only
.parametrize('seed', [123, 456])
def test_ragged_to_dense_random(dtype, ml, seed):
rng = np.random.RandomState(seed)
values = rng.random(size=(10000,)).astype(dtype)
row_splits = [0]
while (row_splits[(- 1)] < values.shape[0]):
row_splits.append((row_splits[(- 1)] + rng.randint(0,... |
def get_down_block(down_block_type: str, num_layers: int, in_channels: int, out_channels: int, temb_channels: int, add_downsample: bool, resnet_eps: float, resnet_act_fn: str, num_attention_heads: int, resnet_groups: Optional[int]=None, cross_attention_dim: Optional[int]=None, downsample_padding: Optional[int]=None, du... |
def get_inception_score():
all_samples = []
for i in range(10):
all_samples.append(session.run(samples_100))
all_samples = np.concatenate(all_samples, axis=0)
all_samples = ((all_samples + 1.0) * (255.0 / 2)).astype('int32')
all_samples = all_samples.reshape(((- 1), 3, 32, 32)).transpose(0, ... |
class SmallScore(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
nef = (config.model.nef * 4)
self.u_net = nn.Sequential(nn.Conv2d(config.data.channels, nef, 4, stride=2, padding=1), nn.GroupNorm(4, nef), nn.ELU(), nn.Conv2d(nef, (nef * 2), 3, stride=1... |
def get_all_results():
all_results = {}
for cfg in tqdm(cfgs):
robot_config_str = cfg.experiment_name.split('-')[0]
if (robot_config_str not in all_results):
all_results[robot_config_str] = {}
cutoff = all_cutoffs[robot_config_str][cfg.env_name]
curves = extend_curves... |
def actor_rollout(obs, action, last, model, actor, critic, config):
n_agents = obs.shape[2]
with FreezeParameters([model]):
embed = model.observation_encoder(obs.reshape((- 1), n_agents, obs.shape[(- 1)]))
embed = embed.reshape(obs.shape[0], obs.shape[1], n_agents, (- 1))
prev_state = mo... |
class ResUNet2SP(ME.MinkowskiNetwork):
NORM_TYPE = None
BLOCK_NORM_TYPE = 'BN'
CHANNELS = [None, 32, 64, 128, 256]
TR_CHANNELS = [None, 32, 64, 64, 128]
REGION_TYPE = ME.RegionType.HYPER_CUBE
def __init__(self, in_channels=3, out_channels=32, bn_momentum=0.1, conv1_kernel_size=3, normalize_featu... |
_grad()
def concat_all_gather_without_backprop(x: Tensor, dim: int=0) -> Tensor:
if (dist.is_available() and dist.is_initialized()):
tensors_gather = [torch.ones_like(x) for _ in range(torch.distributed.get_world_size())]
torch.distributed.all_gather(tensors_gather, x, async_op=False)
output... |
class GeneratorTest(unittest.TestCase):
depth_base = 25.0
depth_step = 0.25
batch_size = 2
dataset_path = '/Volumes/Bahia/kitti-dataset'
def test_generate_batch(self):
generator = KittiGenerator(self.dataset_path, self.depth_base, self.depth_step)
start_time = time.time()
num... |
def test_isotropic_eddington_selfconsist_dehnencore_dens_directint():
pot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
dfp = eddingtondf(pot=pot)
tol = 0.01
check_dens_directint(dfp, pot, tol, (lambda r: pot.dens(r, 0)), rmin=(pot._scale / 10.0), rmax=(pot._scale * 10.0), bins=31)
retur... |
class Classifier_Module(nn.Module):
def __init__(self, dilation_series, padding_series, num_classes):
super(Classifier_Module, self).__init__()
self.conv2d_list = nn.ModuleList()
for (dilation, padding) in zip(dilation_series, padding_series):
self.conv2d_list.append(nn.Conv2d(20... |
class NormalizeImageDict(object):
def __init__(self, image_keys, normalizeRange=True):
self.image_keys = image_keys
self.normalizeRange = normalizeRange
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
def __call__(self, sample):
for ke... |
class MomentumUpdaterHook(Hook):
def __init__(self, by_epoch=True, warmup=None, warmup_iters=0, warmup_ratio=0.9):
if (warmup is not None):
if (warmup not in ['constant', 'linear', 'exp']):
raise ValueError(f'"{warmup}" is not a supported type for warming up, valid types are "con... |
def create_gaussian_diffusion(*, steps=1000, learn_sigma=False, sigma_small=False, noise_schedule='linear', use_kl=False, predict_xstart=False, rescale_timesteps=False, rescale_learned_sigmas=False, timestep_respacing='', use_entropy_scale=False):
betas = gd.get_named_beta_schedule(noise_schedule, steps)
if use... |
def evalfxn(val_method, model, dataloader, criterion, args, num_classes, **kwargs):
batch_time = AverageMeter('Time', ':6.3f')
data_time = AverageMeter('Data', ':6.3f')
losses = AverageMeter('Loss', ':.4f')
top1 = AverageMeter('', ':6.2f')
if (num_classes >= 5):
top5 = AverageMeter('', ':6.2... |
class ToSpaceBGR(object):
def __init__(self, is_bgr):
self.is_bgr = is_bgr
def __call__(self, tensor):
if self.is_bgr:
new_tensor = tensor.clone()
new_tensor[0] = tensor[2]
new_tensor[2] = tensor[0]
tensor = new_tensor
return tensor |
def main(args):
dataset = load_dataset(args.dataset, split='train')
def truncate(sample):
sample['input_ids'] = sample['input_ids'][0:args.truncate]
sample['labels'] = sample['labels'][0:args.truncate]
sample['attention_mask'] = sample['attention_mask'][0:args.truncate]
return sa... |
def server():
parser = argparse.ArgumentParser()
options.add_server_args(parser)
options.add_data_args(parser)
args = parser.parse_args()
simuleval.online.start_server(args) |
def get_feature_names(df):
ks = list(df.keys())
feat_names = [k for k in ks if ((not k.startswith('y')) and (not k.startswith('Y')) and (not k.startswith('Z')) and (not k.startswith('pixel')) and (not (k in ['catIdx', 'cell_num', 'pid', 'valid', 'X', 'X_pvals', 'x_pos', 'X_starts', 'X_ends', 'X_extended', 'shor... |
def setup_training(mode, generator, discriminator, generator_batcher, discriminator_batcher):
train_dir = os.path.join(FLAGS.log_root, 'train')
if (not os.path.exists(train_dir)):
os.makedirs(train_dir)
if FLAGS.restore_best_model:
restore_best_model()
return
saver = tf.train.Sav... |
def load_tweet_users_posted_rumours():
with open(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'tweet_users_posted_rumours'), 'rb') as outfile:
rumour_users = pickle.load(outfile)
outfile.close()
return rumour_users |
def convert_to_trainID(maskpath, out_mask_dir, is_train, clsID_to_trID=full_clsID_to_trID, suffix=''):
mask = np.array(Image.open(maskpath))
mask_copy = (np.ones_like(mask, dtype=np.uint8) * 255)
for (clsID, trID) in clsID_to_trID.items():
mask_copy[(mask == clsID)] = trID
seg_filename = (osp.jo... |
def init_model(args, train_iter, flownmt):
flownmt.eval()
init_batch_size = args.init_batch_size
if (args.rank <= 0):
logging('Rank {}, init model: {} instances'.format(args.rank, init_batch_size), args.log)
else:
print('Rank {}, init model: {} instances'.format(args.rank, init_batch_siz... |
def pretend_to_be_nnUNetTrainer(folder, checkpoints=('model_best.model.pkl', 'model_final_checkpoint.model.pkl')):
pretend_to_be_other_trainer(folder, 'nnUNetTrainer', checkpoints) |
def get_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument('--entry-point', type=str, action='append', default=None)
parser.add_argument('--arguments', metavar='KEY=VALUE', nargs='+', action='append', help='Set kv pairs used as args for the entry point script.')
... |
def conv1x1(in_planes: int, out_planes: int, stride: int=1) -> HalutConv2d:
return HalutConv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) |
def create_arg_parser():
parser = argparse.ArgumentParser(description='Preprocess the europarl corpus for the die-dat task.')
parser.add_argument('--path', help='Path to the corpus file.', metavar='path', default='data/raw/europarl/europarl-v7.nl-en.nl')
parser.add_argument('--number', help='Number of examp... |
.xfail
.parametrize('mass', [30.0])
def test_horizon_with_network_against_single_detector(mass):
params = {'mass_1': mass, 'mass_2': mass, 'theta_jn': 0.0, 'psi': 0.0, 'phase': 0.0, 'geocent_time': 0.0, 'ra': 1.0, 'dec': 1.0}
et_ce_network = Network(['ET', 'CE1'], fisher_parameters=[], parameters=[])
et_net... |
class AFNB(nn.Module):
def __init__(self, low_in_channels, high_in_channels, channels, out_channels, query_scales, key_pool_scales, conv_cfg, norm_cfg, act_cfg):
super(AFNB, self).__init__()
self.stages = nn.ModuleList()
for query_scale in query_scales:
self.stages.append(SelfAtt... |
def build_criterion(cfg, device):
return registry.CRITERION[cfg.MODEL.CRITERION.NAME](cfg).to(device=device) |
def write_EHRinstance_to_example_files(seqs, max_seq_length, max_predictions_per_seq, masked_lm_prob, vocab, output_files, rng):
writers = []
for output_file in output_files:
writers.append(tf.python_io.TFRecordWriter(output_file))
writer_index = 0
total_written = 0
min_seq_l = max_seq_lengt... |
def setup_output_folder(save_dir: str, folder_only: bool=False):
log_filename = 'train_'
log_filename += time.strftime('%Y_%m_%dT%H_%M_%S')
log_filename += '.log'
log_folder = os.path.join(save_dir, 'logs')
if (not os.path.exists(log_folder)):
os.path.mkdirs(log_folder)
if folder_only:
... |
.dataclass
class FlaxBaseModelOutputWithPast(ModelOutput):
last_hidden_state: jnp.ndarray = None
past_key_values: Optional[Dict[(str, jnp.ndarray)]] = None
hidden_states: Optional[Tuple[jnp.ndarray]] = None
attentions: Optional[Tuple[jnp.ndarray]] = None |
def test_sparse_prior():
from mmdet.models.task_modules.prior_generators import MlvlPointGenerator
mlvl_points = MlvlPointGenerator(strides=[4, 10], offset=0)
prior_indexs = torch.Tensor([0, 2, 4, 5, 6, 9]).long()
featmap_sizes = [(3, 5), (6, 4)]
grid_anchors = mlvl_points.grid_priors(featmap_sizes=... |
def main():
args = parser.parse_args()
(model, val_loader, dictionary, w_matrix) = load_model(args)
return (model, val_loader, dictionary, w_matrix) |
def get_header(path):
with open(path) as f:
header = next(csv.reader(f))
return header |
class LIRCMOP7(LIRCMOP5):
def __init__(self, number_of_variables: int=30):
super(LIRCMOP7, self).__init__(number_of_variables)
def evaluate_constraints(self, solution: FloatSolution) -> FloatSolution:
constraints = [0.0 for _ in range(self.number_of_constraints())]
r = 0.1
theta ... |
class TestUpdateFunctions(object):
torch_values = {'sgd': [0., 0., 0.], 'momentum': [0., 0., 0.], 'nesterov_momentum': [0., 0., 0.], 'adagrad': [0., 0., 0.], 'rmsprop': [0., 0., 0.], 'adadelta': [0., 0., 0.], 'adam': [0., 0., 0.], 'adamax': [0., 0., 0.]}
def f(self, X):
return ([0.1, 0.2, 0.3] * (X ** 2... |
class ModelWithLoss(torch.nn.Module):
def __init__(self, model, loss):
super(ModelWithLoss, self).__init__()
self.model = model
self.loss = loss
def forward(self, batch):
outputs = self.model(batch['input'])
(loss, loss_stats) = self.loss(outputs, batch)
return (o... |
class NASNetTest(tf.test.TestCase):
def testBuildLogitsCifarModel(self):
batch_size = 5
(height, width) = (32, 32)
num_classes = 10
inputs = tf.random_uniform((batch_size, height, width, 3))
tf.train.create_global_step()
with slim.arg_scope(nasnet.nasnet_cifar_arg_sco... |
class Session(object):
def __init__(self, cfg):
self._cfg = cfg
self._sess_name = self._make_sess_name()
self._main_out_folder_abs = None
self._log_folder_abs = None
self._log = None
def _make_sess_name(self):
sess_name = (self._cfg[self._cfg.SESSION_NAME] if (sel... |
class PhobertTokenizer(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, merges_file, bos_token='<s>', eos_token='</s>', sep_token='</s>', cls_t... |
def run_episode(seed=None, policy=None):
env = generate_env(seed)
state = env.reset()
done = False
episode_reward = 0
while (not done):
action = policy.get_action(state)
(state, reward, done, info) = env.step(action)
episode_reward += reward
output = flatten_dict(info)
... |
class MaxoutDense(KerasLayer):
def __init__(self, output_dim, nb_feature=4, W_regularizer=None, b_regularizer=None, bias=True, input_dim=None, input_shape=None, **kwargs):
if input_dim:
input_shape = (input_dim,)
super(MaxoutDense, self).__init__(None, output_dim, nb_feature, W_regulariz... |
def get_microbiologyevents_extractors(data_dir, extractor_map):
extractors = []
table = 'microbiologyevents'
id_extractor = MultiExtractor(names=['subject_id', 'hadm_id'], sep='_')
outpath = os.path.join(data_dir, (table + '.tsv'))
charttime_ext = TimeExtractor(name='charttime', converter=time2str)
... |
def get(data_path, seed=0, pc_valid=0.1):
data = {}
taskcla = []
size = [3, 32, 32]
path = os.path.join(data_path, 'binary_cifar')
if (not os.path.isdir(path)):
os.makedirs(path)
mean = [(x / 255) for x in [125.3, 123.0, 113.9]]
std = [(x / 255) for x in [63.0, 62.1, 66.7]]
... |
class ScalableModule(BaseModule):
def __init__(self, width_scale=1.0, rescale_init=False, rescale_layer=False):
super(ScalableModule, self).__init__()
if rescale_layer:
self.scaler = Scaler(width_scale)
else:
self.scaler = nn.Identity()
self.rescale_init = res... |
class Value(nn.Module):
def __init__(self, num_inputs):
super(Value, self).__init__()
self.affine1 = nn.Linear(num_inputs, 64)
self.affine2 = nn.Linear(64, 64)
self.value_head = nn.Linear(64, 1)
self.value_head.weight.data.mul_(0.1)
self.value_head.bias.data.mul_(0.0)... |
def test_bwar_bat_return_all() -> None:
result = league_batting_stats.bwar_bat(return_all=True)
assert (result is not None)
assert (not result.empty)
bwar_bat_2019 = result.query('year_ID == 2019')
assert (len(bwar_bat_2019.columns) == 49)
assert (len(bwar_bat_2019) == 1567) |
class Cow(Object):
def __init__(self, world, pos):
super().__init__(world, pos)
self.health = 3
def texture(self):
return 'cow'
def update(self):
if (self.health <= 0):
self.world.remove(self)
if (self.random.uniform() < 0.5):
direction = self.... |
def get_parser():
parser = argparse.ArgumentParser(description='convert a json to a transcription file with a token dictionary', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('json', type=str, help='json files')
parser.add_argument('--num-spkrs', type=int, default=1, help='numb... |
def load_pickle_file(pkl_path):
with open(pkl_path, 'rb') as f:
data = pickle.load(f, encoding='latin1')
return data |
class RequestOutput():
def __init__(self, request_id: str, prompt: str, prompt_token_ids: List[int], outputs: List[CompletionOutput], finished: bool) -> None:
self.request_id = request_id
self.prompt = prompt
self.prompt_token_ids = prompt_token_ids
self.outputs = outputs
sel... |
def main():
os.system(f'rm -r $PWD/data')
print('')
print('Testing Classes')
dataset = VesselGraph(root='data', name=selected_dataset, pre_transform=T.LineGraph(force_directed=True))
print()
print(f'Dataset: {dataset}:')
print('')
print(f'Number of graphs: {len(dataset)}')
print(f'Nu... |
def _get_test_ids():
data = json.load(open(TEST_5K))
ids = {_get_img_id(d['filename']) for d in data}
return ids |
class AxB(nn.Module):
def __init__(self, nhid):
super(AxB, self).__init__()
self.nhid = nhid
def forward(self, nhA, nhB):
mat = torch.bmm(nhB.view((- 1), 100, self.nhid), nhA.view((- 1), self.nhid, 1))
return mat.view((- 1), 100) |
class ResShortCut_D_Dec(ResNet_D_Dec):
def __init__(self, block, layers, norm_layer=None, large_kernel=False, late_downsample=False):
super(ResShortCut_D_Dec, self).__init__(block, layers, norm_layer, large_kernel, late_downsample=late_downsample)
def forward(self, x, mid_fea):
(fea1, fea2, fea3... |
class LEDForQuestionAnswering(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def accuracy(scores, labels):
num_classes = scores.size((- 2))
predictions = torch.max(scores, dim=(- 2)).indices
accuracies = []
accuracy_mask = (predictions == labels)
for label in range(num_classes):
label_mask = (labels == label)
per_class_accuracy = (accuracy_mask & label_mask).... |
def FloatArrayToRgbImage(float_array, scale_factor=DEFAULT_RGB_SCALE_FACTOR, drop_blue=False):
float_array = np.squeeze(float_array)
scaled_array = np.floor(((float_array * scale_factor) + 0.5))
min_inttype = 0
max_inttype = ((2 ** 24) - 1)
scaled_array = ClipFloatValues(scaled_array, min_inttype, m... |
class TFXLNetForQuestionAnsweringSimple(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def read_model(path, ext):
if (ext == '.txt'):
cameras = read_cameras_text(os.path.join(path, ('cameras' + ext)))
images = read_images_text(os.path.join(path, ('images' + ext)))
points3D = read_points3D_text((os.path.join(path, 'points3D') + ext))
else:
cameras = read_cameras_bin... |
def plot_counter_dayline_from_node_id(node_id):
data = daily_counts[((daily_counts['node_id'] == str(node_id)) & (daily_counts['day'] == date))]
data = list(data['volume'])[0]
plot_counter_dayline(data) |
class DataCollector():
def __init__(self, full_data: bool, cur_dir):
self.pred_distributions = []
self.attentions = []
self.all_hidden_states = []
self.logits = []
self.input_doc = None
self.input_doc_mask = None
self.meta = None
self.full_data = full_... |
class ImageNetValData():
class ImageNetValDataX():
def __init__(self, dir, filenames, width, height, fashion, transform):
self._dir = dir
self._filenames = filenames
self._width = width
self._height = height
self._fashion = fashion
self... |
def trial_spinglass(inputs, output, size_dict, icool_fact=0.01, igamma=0.01, **kwargs):
return trial_igraph_partition(inputs, output, size_dict, method='spinglass', gamma=(1 - igamma), cool_fact=(1 - icool_fact), **kwargs) |
def main(args):
accuracies = 0.0
for i in range(10):
filepath = (args.result_file + str(i))
with open(filepath, 'r') as textfile:
all_file = textfile.read().split('\n')
all_file = [v for v in all_file if ('acc' in v)]
acc = [v.split('acc:')[1] for v in all_file]
... |
def binarize_masks(state_dict, masks):
with torch.no_grad():
new_state_dict = {}
for (name, par) in state_dict.items():
if ('weight' in name):
mask = (name.rsplit('weight', 1)[0] + 'mask')
if (mask in masks):
par = (par * masks[mask].to... |
class ELMo(object):
def __init__(self, parameters):
self._model = None
self._elmo_model = None
self.parameters = parameters
self.compile_elmo()
def __del__(self):
K.clear_session()
del self._model
def char_level_token_encoder(self):
charset_size = self... |
def mock_keypoint_rcnn_inference(tensor_mode, patched_module, use_heatmap_max_keypoint, check=True):
with mock.patch('{}.keypoint_rcnn_inference'.format(patched_module), side_effect=Caffe2KeypointRCNNInference(use_heatmap_max_keypoint)) as mocked_func:
(yield)
if check:
assert (mocked_func.call_... |
def metrics_generator(array, tolerance):
max_diff = np.max(array)
mean_diff = np.mean(array)
median_diff = np.median(array)
success_rate = (np.sum((array < tolerance)) / array.size)
return (max_diff, mean_diff, median_diff, success_rate) |
def wms_loss(distances, embeddings, d_alpha, d_beta, alpha=2.0, beta=50.0, lamb=1.0, eps=0.1, ms_mining=True, wfunction='exp', sumfunction='ms'):
embeddings = tf.nn.l2_normalize(embeddings, axis=1)
batch_size = embeddings.get_shape().as_list()[0]
if (wfunction == 'lin'):
mask_pos = tf.where((distanc... |
def build_grid(resolution):
ranges = [torch.linspace(0.0, 1.0, steps=res) for res in resolution]
grid = torch.meshgrid(*ranges)
grid = torch.stack(grid, dim=(- 1))
grid = torch.reshape(grid, [resolution[0], resolution[1], (- 1)])
grid = grid.unsqueeze(0)
return torch.cat([grid, (1.0 - grid)], di... |
class WeightDecay(L2Regularization):
def __init__(self, *kargs, **kwargs):
super(WeightDecay, self).__init__(*kargs, **kwargs) |
def set_dico_parameters(params, data, dico):
if ('dico' in data):
assert (data['dico'] == dico)
else:
data['dico'] = dico
n_words = len(dico)
bos_index = dico.index(BOS_WORD)
eos_index = dico.index(EOS_WORD)
pad_index = dico.index(PAD_WORD)
unk_index = dico.index(UNK_WORD)
... |
def densenet121(pretrained: bool=False, progress: bool=True, num_classes: int=1000, layer_config=None) -> DenseNet:
print('Converting Densenet-121 to {} mode'.format(MODE_STRING))
return create_torchvision_biomodel(models.densenet121, MODE, layer_config, pretrained, progress, num_classes) |
class BaseActor():
def __init__(self, net, objective):
self.net = net
self.objective = objective
def __call__(self, data: TensorDict):
raise NotImplementedError
def to(self, device):
self.net.to(device)
def train(self, mode=True):
self.net.train(mode)
prin... |
def gpt_init(meta_vocab_size=None, args=None):
n_layer = args.n_layer
n_head = args.n_head
n_embd = args.n_embd
block_size = args.block_size
bias = args.bias
dropout = args.dropout
model_args = dict(n_layer=n_layer, n_head=n_head, n_embd=n_embd, block_size=block_size, bias=bias, vocab_size=N... |
def split_into_sentences(text):
text = ((' ' + text) + ' ')
text = text.replace('\n', ' ')
text = re.sub(prefixes, '\\1<prd>', text)
text = re.sub(websites, '<prd>\\1', text)
if ('Ph.D' in text):
text = text.replace('Ph.D.', 'Ph<prd>D<prd>')
text = re.sub((('\\s' + alphabets) + '[.] '),... |
class SEBottleneck(nn.Module):
expansion = 2
def __init__(self, inplanes, planes, stride=1, downsample=None, reduction=16):
super(SEBottleneck, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
self.conv2 = nn.C... |
def _iwae(model, x, K):
(qz_x, px_z, zs) = model(x, K)
lpz = model.pz(*model.pz_params).log_prob(zs).sum((- 1))
lpx_z = (px_z.log_prob(x).view(*px_z.batch_shape[:2], (- 1)) * model.llik_scaling)
lqz_x = qz_x.log_prob(zs).sum((- 1))
return ((lpz + lpx_z.sum((- 1))) - lqz_x) |
def gendata(records, index, type):
for (k, v) in zip(records.keys(), records.values()):
(yield {'_index': index, '_id': k, '_source': v}) |
def get_num_min_class(labels):
argmax_labels = np.argmax(labels, axis=(- 1))
num_samples = labels.shape[0]
for i in range(labels.shape[(- 1)]):
lab_elems = np.sum((argmax_labels == i))
if (lab_elems < num_samples):
num_samples = lab_elems
return num_samples |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.