code stringlengths 101 5.91M |
|---|
class ElvenDagger(BaseDagger):
def __init__(self):
super().__init__('elven dagger', weight=10, damage=D.SingleDice(5), material=M.Wood) |
class OutputMode():
Temp = 1
Calib = 2
Orient = 4
Auxiliary = 8
Position = 16
Velocity = 32
Status = 2048
RAWGPS = 4096
RAW = 16384 |
('AGENT_8')
class AGENT_8(BaseAgent):
type = PolicyType.MLP
features_extractor_class = None
features_extractor_kwargs = None
net_arch = [64, 64, 64, 64, dict(pi=[64, 64], vf=[64, 64])]
activation_fn = nn.ReLU |
class Exponential(JavaValue):
def __init__(self, decay_step, decay_rate, stair_case=False, bigdl_type='float'):
JavaValue.__init__(self, None, bigdl_type, decay_step, decay_rate, stair_case) |
def is_initialized():
cls = (InProcessCommunicator if __use_threads else DistributedCommunicator)
return cls.is_initialized() |
def config_parser():
parser = configargparse.ArgumentParser()
parser.add_argument('--config', is_config_file=True, default='configs/shapenet_cars.txt', help='config file path')
parser.add_argument('--exp_name', type=str, default=None, help='Experiment name, used as folder name for the experiment. If left bl... |
def check_graphviz_support(caller_name):
try:
import graphviz
except ImportError:
raise ImportError(f'{caller_name} requires rdata. Please install pyreadr using `pip install rdata`') |
class GDANET(nn.Module):
def __init__(self):
super(GDANET, self).__init__()
self.bn1 = nn.BatchNorm2d(64, momentum=0.1)
self.bn11 = nn.BatchNorm2d(64, momentum=0.1)
self.bn12 = nn.BatchNorm1d(64, momentum=0.1)
self.bn2 = nn.BatchNorm2d(64, momentum=0.1)
self.bn21 = nn... |
def vectorize1(func, args=(), vec_func=False):
if vec_func:
def vfunc(x):
return func(x, *args)
else:
def vfunc(x):
if numpy.isscalar(x):
return func(x, *args)
x = numpy.asarray(x)
y0 = func(x[0], *args)
n = len(x)
... |
def save_model(mean_IOU, best_iou, save_dir, save_prefix, train_loss, test_loss, recall, precision, epoch, net):
if (mean_IOU > best_iou):
save_mIoU_dir = (((('result/' + save_dir) + '/') + save_prefix) + '_best_IoU_IoU.log')
save_other_metric_dir = (((('result/' + save_dir) + '/') + save_prefix) + ... |
class TestFGFieldingData():
ALL_DATA_COLUMNS_COUNT = (len(FangraphsFieldingStats.ALL()) + 2)
DEFAULT_MAX_RESULTS = 10
def test_fg_fielding_data(self) -> None:
season = 2019
data = fg_fielding_data(season, max_results=self.DEFAULT_MAX_RESULTS)
assert (data is not None)
assert ... |
class Trainer():
def __init__(self, args, loader, my_model, my_loss, ckp):
self.args = args
self.scale = args.scale
self.ckp = ckp
self.loader_train = loader.loader_train
self.loader_test = loader.loader_test
self.model = my_model
self.loss = my_loss
s... |
class LibriTransDataset(torch.utils.data.Dataset):
def __init__(self, args, split, sample_rate):
super().__init__()
self.args = args
self.sample_rate = sample_rate
self.tokenizer = whisper.tokenizer.get_tokenizer(True, language=args.language, task='transcribe')
self.data = []... |
def make_dataset(input_dir, split):
plyfiles = []
for dirs in os.listdir(input_dir):
tempDir = os.path.join(input_dir, dirs)
for input in glob.iglob(os.path.join(tempDir, '*.npy')):
input = os.path.basename(input)
root_filename = input[:(- 4)]
plyinput = (((di... |
def usps(tnum=2):
channel_stats = dict(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
train_transformation = data.TransformNTimes(transforms.Compose([transforms.ToTensor(), transforms.Normalize(**channel_stats)]), n=tnum)
eval_transformation = transforms.Compose([transforms.ToTensor(), transforms.Normalize(**ch... |
def main():
parser = argparse.ArgumentParser(description='Train a fastText baseline for X-Stance')
parser.add_argument('--data-dir', type=str, required=True)
parser.add_argument('--pred', type=str, required=True)
parser.add_argument('--pretrained-vectors', type=str, default='')
parser.add_argument('... |
def main():
plotname = os.path.basename(sys.argv[1])
here = os.path.dirname(__file__)
plot_func = plots.get(plotname, None)
if (not plot_func):
sys.stderr.write('Plot {} not found. Supported: \n{}'.format(plotname, plots.keys()))
return 1
out = plot_func()
out_path = os.path.join... |
_config
def model_unet_hetero_pooled():
cfg = {'learner': {'model': 'UNetHeteroscedasticPooled', 'model_kwargs': {'downsample': 6}}} |
def safe_save_model_for_hf_trainer(trainer: transformers.Trainer, output_dir: str, give_rw_access=True, rank0_only=True):
now = time.perf_counter()
if (trainer.fsdp is not None):
cfg = FullStateDictConfig(offload_to_cpu=True, rank0_only=rank0_only)
with FSDP.state_dict_type(trainer.model, StateD... |
class TestStageCascadeRPNHead(TestCase):
def test_cascade_rpn_head_loss(self):
cascade_rpn_head = CascadeRPNHead(**cascade_rpn_config)
s = 256
feats = [torch.rand(1, 1, (s // stride[1]), (s // stride[0])) for stride in cascade_rpn_head.stages[0].prior_generator.strides]
img_metas = {... |
def chunk_layer(layer: Callable, inputs: Dict[(str, Any)], chunk_size: int, no_batch_dims: int, low_mem: bool=False, _out: Any=None, _add_into_out: bool=False) -> Any:
if (not (len(inputs) > 0)):
raise ValueError('Must provide at least one input')
initial_dims = [shape[:no_batch_dims] for shape in _fetc... |
class FIDInceptionA(torchvision.models.inception.InceptionA):
def __init__(self, in_channels, pool_features):
super(FIDInceptionA, self).__init__(in_channels, pool_features)
def forward(self, x):
branch1x1 = self.branch1x1(x)
branch5x5 = self.branch5x5_1(x)
branch5x5 = self.branc... |
class AE_Decoder(nn.Module):
def __init__(self):
super(AE_Decoder, self).__init__()
self.cov5 = Cov5()
self.cov6 = Cov6()
self.cov7 = Cov7()
def forward(self, feature_1, feature_2, feature_B, feature_D):
Output1 = self.cov5(torch.cat([feature_B, feature_D], 1))
Ou... |
def save_trained_matrix_to_file(matrix_path, matrix):
with open(matrix_path, 'w') as f:
for i in range(matrix.shape[0]):
s = np.format_float_scientific(matrix[i][0], unique=False, precision=18)
for j in range(1, matrix.shape[1]):
s += (' %s' % np.format_float_scientif... |
def yolo_config():
head_cfg = dict(anchor_generator=dict(type='YOLOAnchorGenerator', base_sizes=[[(116, 90), (156, 198), (373, 326)], [(30, 61), (62, 45), (59, 119)], [(10, 13), (16, 30), (33, 23)]], strides=[32, 16, 8]), bbox_coder=dict(type='YOLOBBoxCoder'))
test_cfg = mmcv.Config(dict(deploy_nms_pre=0, min_b... |
def save_pickle(d, path):
print('save pickle to', path)
with open(path, mode='wb') as f:
pickle.dump(d, f) |
def combined_roidb(imdb_names, training=True):
print(imdb_names)
def get_training_roidb(imdb):
if cfg.TRAIN.USE_FLIPPED:
print('Appending horizontally-flipped training examples...')
imdb.append_flipped_images()
print('done')
print('Preparing training data...')... |
def idct_2D(x):
x = tf.transpose(x, [0, 5, 1, 2, 3, 4])
x = tf.signal.idct(x, norm='ortho')
x = tf.transpose(x, [0, 1, 2, 3, 5, 4])
x = tf.signal.idct(x, norm='ortho')
x = tf.transpose(x, [0, 1, 2, 3, 5, 4])
x = tf.transpose(x, [0, 2, 3, 4, 5, 1])
return x |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--seed', type=int, default=0)
parser.add_argument('--method', choices=['Seafaring', 'Random', 'SmallExact'], default='MaxMax')
parser.add_argument('--env', choices=['OpenImage', 'Flickr'], default='OpenImage')
parser.add_argument('-... |
_cache()
def setup_logger(name, save_dir, distributed_rank, filename='log.txt', color=True, abbrev_name=None):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
logger.propagate = False
if (abbrev_name is None):
abbrev_name = ('domain adaptation' if (name == 'domain adaptation') el... |
class DynamicPad2d(nn.Module):
def __init__(self, kernel_size, stride, dilation, value=0):
super().__init__()
if isinstance(kernel_size, int):
kernel_size = (kernel_size, kernel_size)
if isinstance(stride, int):
stride = (stride, stride)
if isinstance(dilation... |
def transform(program):
index_to_result = dict()
variable_counter = 0
for (i, op) in enumerate(program):
op_type = get_op_type(op)
if (op_type == 'scene'):
variable_counter += 1
index_to_result[i] = ('', f'x{variable_counter}')
elif (op_type in ('filter_size',... |
class FasterRCNNResnetV1FeatureExtractor(faster_rcnn_meta_arch.FasterRCNNFeatureExtractor):
def __init__(self, architecture, resnet_model, is_training, first_stage_features_stride, batch_norm_trainable=False, reuse_weights=None, weight_decay=0.0):
if ((first_stage_features_stride != 8) and (first_stage_feat... |
def close2dest(vehicle, destination):
return (destination.location.distance(vehicle.get_location()) < 20) |
def step_resnet50_tidy(model: ModelWrapper, cfg: DataflowBuildConfig):
model = model.transform(GiveUniqueParameterTensors())
model = model.transform(InferShapes())
model = model.transform(FoldConstants())
model = model.transform(RemoveStaticGraphInputs())
model = model.transform(GiveUniqueNodeNames(... |
def loadtxt_str(path: PathOrStr) -> np.ndarray:
with open(path, 'r') as f:
lines = f.readlines()
return np.array([l.strip() for l in lines]) |
def get_ood_model_performance_path(args):
if args['test']:
mkdir(os.path.join((args['OOD_model_performance_output_dir'] + '_test'), os.path.basename(args['checkpoint'])))
output_path = os.path.join((args['OOD_model_performance_output_dir'] + '_test'), os.path.basename(args['checkpoint']), (os.path.b... |
class MmiTrainingGraphCompiler(object):
def __init__(self, lexicon: Lexicon, device: torch.device, oov: str='<UNK>'):
self.lexicon = lexicon
L_inv = self.lexicon.L_inv.to(device)
if ((L_inv.properties & k2.fsa_properties.ARC_SORTED) != 0):
L_inv = k2.arc_sort(L_inv)
asser... |
def repeatBlock(conv, repeat_times, all_strides=None, all_expansions=None, feature_maps_downsample=False):
if ((all_strides is not None) and (all_expansions is not None)):
assert (isinstance(all_strides, tuple) or isinstance(all_strides, list))
assert (isinstance(all_expansions, tuple) or isinstance... |
class vgg16avg_zfnet():
def __init__(self, c, w1, b1, i1, outlayer1, w2, b2, i2, outlayer2):
with tf.variable_scope('vgg16avg_zfnet'):
self.c = []
codebook = []
for i in range(15):
codebook.append(tf.Variable(c[i], dtype=tf.float32))
self.c... |
def list_pretrained(as_str: bool=False):
return [(':'.join([k, t]) if as_str else (k, t)) for k in _PRETRAINED.keys() for t in _PRETRAINED[k].keys()] |
class GANLoss(nn.Module):
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
super(GANLoss, self).__init__()
self.register_buffer('real_label', torch.tensor(target_real_label))
self.register_buffer('fake_label', torch.tensor(target_fake_label))
self.gan_mode ... |
def comment_out_line(filepath, code):
modified_lines = []
with open(filepath, 'r') as file:
lines = file.readlines()
file.seek(0)
for line in lines:
if re.match(code, line.strip()):
line = ('#' + line)
modified_lines.append(line)
with open(file... |
class DdpCheckpoinerTest(unittest.TestCase):
def setUp(self) -> None:
DdpCheckpointSaver._saver_instance = None
DdpCheckpointSaver.start_async_saving_ckpt()
def tearDown(self) -> None:
if DdpCheckpointSaver._saver_instance:
DdpCheckpointSaver._saver_instance.close()
def t... |
def create_run(experiment, command_name, config_updates=None, named_configs=(), force=False):
sorted_ingredients = gather_ingredients_topological(experiment)
scaffolding = create_scaffolding(experiment, sorted_ingredients)
prefixes = sorted([s.split('.') for s in scaffolding if (s != '')], reverse=True, key... |
def pnv_write_eval_stats(file_name, prefix, stats):
s = prefix
ave_1p_recall_l = []
ave_recall_l = []
with open(file_name, 'a') as f:
for ds in stats:
ave_1p_recall = stats[ds]['ave_one_percent_recall']
ave_1p_recall_l.append(ave_1p_recall)
ave_recall = stats[... |
def test_modal_datamodule_train_data(fs, mocker):
dm = kick_modal_datamodule(fs, mocker)
dm.setup('fit')
train_loader = dm.train_dataloader()
assert isinstance(train_loader, DataLoader)
_ = mocker.patch(f'{TESTED_MODULE}.torchaudio.load', return_value=(torch.rand(1, dm.num_samples), dm.sample_rate))... |
def accuracy(output, target, topk=(1,)):
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))
res = []
for k in topk:
... |
class ResNet(nn.Module):
def __init__(self, block, layers, zero_init_residual=False, groups=1, widen=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None, normalize=False, output_dim=0, hidden_mlp=0, nmb_prototypes=0, eval_mode=False):
super(ResNet, self).__init__()
if (norm_lay... |
def get_train_val_paths(all_paths, path_to_train_val_pkl):
path_to_train_val_pkl = pathlib.Path(path_to_train_val_pkl)
with open(path_to_train_val_pkl) as f:
train_val_split = json.load(f)
train_paths = [path for path in all_paths if any((((patient_id + '_ct.nii.gz') in str(path[0])) for patient_id ... |
def download(label, name, path):
label = label.replace(' ', '_')
path_data = os.path.join(path, label)
if (not os.path.exists(path_data)):
os.makedirs(path_data)
link_prefix = '
print(name)
filename = (os.path.join(path_data, name) + '.mp4')
link = (link_prefix + name)
if os.path... |
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.... |
class RobertaTokenizerFast(GPT2TokenizerFast):
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, errors='replace', bos_token='<s>', eos_token='</s>', sep... |
def load_prior_model(*loadpath, epoch=None, device='cuda:0'):
loadpath = os.path.join(*loadpath)
config_path = os.path.join(loadpath, 'prior_model_config.pkl')
if (epoch is 'latest'):
epoch = get_latest_epoch(loadpath, 'prior_')
print(f'[ utils/serialization ] Loading model epoch: {epoch}')
... |
def create_app():
app = Flask(__name__)
app.config.from_pyfile('config.cfg', silent=True)
('/extract_journal_info', methods=['POST'])
_args({'publication_infos': fields.List(fields.Dict, required=True), 'journal_kb_data': fields.Dict(required=True)}, locations=('json',))
def extract_journal_info(arg... |
_comparison(baseline_images=['3d_sorted'], remove_text=False, extensions=['png'])
def test_3d_sorted(grid_archive_3d):
plt.figure(figsize=(8, 6))
parallel_axes_plot(grid_archive_3d, sort_archive=True) |
class Config():
vis = False
debug = False
trainset_3d = ['InterHand26M']
trainset_2d = []
testset = 'InterHand26M'
hand_resnet_type = 50
input_img_shape = (256, 256)
input_hm_shape = (64, 64, 64)
output_hm_shape = (8, 8, 8)
bbox_3d_size = 0.3
sigma = 2.5
lr = 0.0001
l... |
class Encoder(Model):
def __init__(self):
super(Encoder, self).__init__()
self.base_model = DenseNet169(input_shape=(None, None, 3), include_top=False, weights='imagenet')
print('Base model loaded {}'.format(DenseNet169.__name__))
outputs = [self.base_model.outputs[(- 1)]]
fo... |
def resnet101(**kwargs):
model = ResNet(hidden_size, Bottleneck, [3, 4, 23, 3], **kwargs)
model.apply(init_param)
return model |
def set_logging(save_dir, gpu, rerun=False):
os.makedirs(save_dir, exist_ok=rerun)
log_format = f'%(asctime)s (GPU {gpu}: {save_dir}) %(message)s'
logging.basicConfig(stream=sys.stdout, level=logging.INFO, format=log_format, datefmt='[%y/%m/%d %H:%M:%S]')
fh = logging.FileHandler(f'{save_dir}/log.txt')
... |
class HintLoss(nn.Module):
def __init__(self):
super(HintLoss, self).__init__()
self.crit = nn.MSELoss()
def forward(self, f_s, f_t):
loss = self.crit(f_s, f_t)
return loss |
class GlobalAttention(torch.nn.Module):
def __init__(self, decoder_hidden_size, encoder_hidden_size, attention):
super(GlobalAttention, self).__init__()
self.decoder_hidden_size = decoder_hidden_size
self.encoder_hidden_size = encoder_hidden_size
self.attention = attention
se... |
_grad()
def accuracy(output, target, topk=(1,)):
if (target.numel() == 0):
return [torch.zeros([], device=output.device)]
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))
... |
def main():
f = sys.argv[1]
d = pandas.read_csv(f)
d.columns = ['Course', 'Code']
counts = {}
for (_, course_code) in d.iterrows():
(course, code) = course_code.tolist()
counts.setdefault(course, {})
ql = set()
for l in code.split('\n'):
s = l.strip().spli... |
_module()
class ABILanguageDecoder(BaseDecoder):
def __init__(self, d_model=512, n_head=8, d_inner=2048, n_layers=4, max_seq_len=40, dropout=0.1, detach_tokens=True, num_chars=90, use_self_attn=False, pad_idx=0, init_cfg=None, **kwargs):
super().__init__(init_cfg=init_cfg)
self.detach_tokens = detac... |
def test_CBPM_spearman(X_iris: pd.DataFrame, y_iris: pd.DataFrame) -> None:
X_pos = ['sepal_length', 'petal_length', 'petal_width']
X_neg = ['sepal_width']
trans_posneg = CBPM(corr_method=spearmanr, agg_method=np.mean).fit_transform(X_iris, y_iris)
trans_man_pos = X_iris[X_pos].values.mean(axis=1)
t... |
class GaussianNoise(Transform):
def __init__(self, var_limit=(0, 0.1), mean=0, always_apply=False, p=0.5):
super().__init__(always_apply, p)
self.var_limit = var_limit
self.mean = mean
def apply(self, img, var):
return F.gaussian_noise(img, var=var, mean=self.mean)
def get_pa... |
def svm_load_model(model_file_name):
model = libsvm.svm_load_model(model_file_name.encode())
if (not model):
print(("can't open model file %s" % model_file_name))
return None
model = toPyModel(model)
return model |
def customized_collate_fn(batch):
(batch, targets) = zip(*batch)
batch = torch.stack(batch, dim=0)
targets = torch.stack(targets, dim=0)
batch = batch.permute(0, 3, 1, 2).contiguous()
return (batch, targets) |
class SimpleRNN(ZooKerasLayer):
def __init__(self, output_dim, activation='tanh', return_sequences=False, go_backwards=False, W_regularizer=None, U_regularizer=None, b_regularizer=None, input_shape=None, **kwargs):
super(SimpleRNN, self).__init__(None, output_dim, activation, return_sequences, go_backwards,... |
class LibraryAPIDef():
def __init__(self, library_name=''):
self.library = library_name
self.id = ''
self.name: str = ''
self.typ: APIType = None
self.alias: List[str] = []
self.description: str = ''
self.declaration: str = ''
self.detail_desc: str = '... |
def pretend_to_be_other_trainer(folder, new_trainer_name, checkpoints=('model_best.model.pkl', 'model_latest.model.pkl', 'model_final_checkpoint.model.pkl')):
folds = subdirs(folder, prefix='fold_', join=False)
if isdir(join(folder, 'all')):
folds.append('all')
for c in checkpoints:
for f in... |
def latest_torch_ckpt(train_ckpt_dir):
files = os.listdir(train_ckpt_dir)
ckpt_list = [f for f in files if f.endswith('.pth')]
if (len(ckpt_list) == 0):
return None
ckpt_list.sort(key=natural_keys)
ckpt_name = ckpt_list[(- 1)]
return os.path.join(train_ckpt_dir, ckpt_name) |
class PlainC(nn.Module):
def __init__(self, labels_num, context_size):
super(PlainC, self).__init__()
self.out_mesh_dstrbtn = nn.Linear(context_size, labels_num)
nn.init.xavier_uniform_(self.out_mesh_dstrbtn.weight)
def forward(self, context_vectors):
output_dstrbtn = self.out_me... |
class cnn_cifar10(nn.Module):
def __init__(self):
super(cnn_cifar10, self).__init__()
self.n_cls = 10
self.conv1 = torch.nn.Conv2d(in_channels=3, out_channels=64, kernel_size=5)
self.conv2 = torch.nn.Conv2d(in_channels=64, out_channels=64, kernel_size=5)
self.pool = torch.nn.... |
def test_modal_datamodule_init():
data = ModalDataModule()
assert isinstance(data, ModalDataModule)
assert isinstance(data, AudioDataModule) |
class AltDiffusionPipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_pretrained(cl... |
def load_torch_data(load_data_func):
def torch_loader(dataset, data_path, batch_size, shuffle=True, cuda_device=None, num_workers=1):
((train_data, val_data), (train_labels, val_labels), label_names) = load_data_func(dataset, data_path)
kwargs = ({'num_workers': num_workers, 'pin_memory': True} if (... |
('smooth_quant')
class SmoothQuantSampler(TuningSampler):
def __init__(self, tuning_space: TuningSpace, tuning_order_lst: List[TuningOrder], initial_op_tuning_cfg: Dict, kwargs: Dict={}):
super().__init__(tuning_space, tuning_order_lst, initial_op_tuning_cfg, kwargs)
self._kwargs = kwargs
se... |
def red_string_matmul(t1: tf.Tensor, t2: tf.Tensor):
dim1 = len(t1.get_shape().as_list())
dim2 = len(t2.get_shape().as_list())
diff = (dim1 - dim2)
assert ((dim1 >= 2) and (dim2 >= 2))
chars = ['i', 'j', 'k', 'l', 'm', 'n', 'o', 'p']
str1 = ''.join(chars[:dim1])
if (diff >= 0):
str2 ... |
def loader(path, batch_size=16, num_workers=1, pin_memory=True):
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
return data.DataLoader(datasets.ImageFolder(path, transforms.Compose([transforms.Resize(256), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFli... |
def test_lovasz_loss():
from mmseg.models import build_loss
with pytest.raises(AssertionError):
loss_cfg = dict(type='LovaszLoss', loss_type='Binary', reduction='none', loss_weight=1.0, loss_name='loss_lovasz')
build_loss(loss_cfg)
with pytest.raises(AssertionError):
loss_cfg = dict(... |
def get_big_nav(vehicle, plan_map):
x = int(((scale * vehicle.get_location().x) + x_offset))
y = int(((scale * vehicle.get_location().y) + y_offset))
_nav = plan_map.crop(((x - 400), (y - 400), (x + 400), (y + 400)))
r = 20
draw = ImageDraw.Draw(_nav)
draw.ellipse((((_nav.size[0] // 2) - r), ((_... |
def test_textnet_save_and_load(corpus, tmp_path):
out = (tmp_path / 'out.textnet')
net = tn.Textnet(corpus.tokenized(), connected=True, doc_attrs={'test': {'New York Times': 1, 'Los Angeles Times': 3}})
net.save(out)
loaded = tn.load_textnet(out)
assert (net.nodes['id'] == loaded.nodes['id'])
as... |
def pointnet_sa_module(xyz, points, npoint, radius, nsample, mlp, mlp2, group_all, is_training, bn_decay, scope, bn=True, pooling='max', knn=False, use_xyz=True, use_nchw=False):
data_format = ('NCHW' if use_nchw else 'NHWC')
with tf.variable_scope(scope) as sc:
if group_all:
nsample = xyz.g... |
def mnist(batch_size=16, size=28, path_to_data='../../mnist_data'):
all_transforms = transforms.Compose([transforms.Resize(size), transforms.ToTensor()])
train_data = datasets.MNIST(path_to_data, train=True, download=True, transform=all_transforms)
test_data = datasets.MNIST(path_to_data, train=False, trans... |
class Bijection(nn.Module):
def __init__(self, x_shape, z_shape):
super().__init__()
self.x_shape = x_shape
self.z_shape = z_shape
def forward(self, inputs, direction, **kwargs):
if (direction == 'x-to-z'):
assert (inputs.shape[1:] == self.x_shape), f'Expected shape {... |
def get_optimizer(model, learning_rate=0.0002, beta1=0.5, beta2=0.99):
optimizer = optim.Adam(model.parameters(), lr=learning_rate, betas=(beta1, beta2))
return optimizer |
class _DGStrat_RepeatProxyBoundHolder():
def __init__(self, bound: int) -> None:
self.bound = bound
if (bound < 0):
raise ArgumentError(("The number of repetitions in a repeat strategy must be non-negative. Got '" + str(bound)))
def __call__(self, strat: DGStrat) -> DGStrat:
... |
def find_tokens(refexp, template, node_id, backtrack=True, partial_match=False):
def backtrack_previous_nodes(cur_id, is_root=True):
cur_tokens = []
function = template['nodes'][cur_id]['type']
if (function[:len('same_')] == 'same_'):
pos = refexp['refexp'].find(function.replace(... |
class HierarchyDecoder(nn.Module):
def __init__(self, num_classes):
super(HierarchyDecoder, self).__init__()
self.layer5 = DecoderHead(2048, 512)
self.layer_n1 = Node1(node1_cls=num_classes)
self.layer_n2 = Node2(node2_cls=3)
self.layer_n3 = Node3(node3_cls=2)
self.la... |
def get_num_args(func):
params = inspect.signature(func).parameters
return (len(params) - ('self' in params)) |
def _graph_network_no_global_update(graph_tuple):
update_node_fn = (lambda n, se, re, g: n)
update_edge_fn = (lambda e, sn, rn, g: e)
update_global_fn = None
net = nn.GraphNetwork(update_edge_fn, update_node_fn, update_global_fn)
return net(graph_tuple) |
def test_isotropic_nfw_sigmar():
pot = potential.NFWPotential(amp=2.3, a=1.3)
dfp = isotropicNFWdf(pot=pot)
numpy.random.seed(10)
samp = dfp.sample(n=1000000)
tol = 0.08
check_sigmar_against_jeans(samp, pot, tol, rmin=(pot._scale / 10.0), rmax=(pot._scale * 10.0), bins=31)
return None |
_model
def dla60x(pretrained=None, num_classes=1000, in_chans=3, **kwargs):
default_cfg = default_cfgs['dla60x']
model = DLA([1, 1, 1, 2, 3, 1], [16, 32, 128, 256, 512, 1024], block=DlaBottleneck, cardinality=32, base_width=4, num_classes=num_classes, in_chans=in_chans, **kwargs)
model.default_cfg = default... |
def load_tracked_dict(path, images, car_masks, semantics, backs, train_list):
for k in range(21):
frame_dir = (path + ('%02d/' % k))
if (not os.path.exists(frame_dir)):
continue
object_list = os.listdir(frame_dir)
object_list.sort()
object_ret = []
for o i... |
class MetaModule(nn.Module):
def params(self):
for (name, param) in self.named_params(self):
(yield param)
def named_leaves(self):
return []
def named_submodules(self):
return []
def named_params(self, curr_module=None, memo=None, prefix=''):
if (memo is None)... |
def weight_decay(model, decay=1e-05):
p1 = []
p2 = []
for (name, param) in model.named_parameters():
if (not param.requires_grad):
continue
if ((len(param.shape) == 1) or name.endswith('.bias')):
p1.append(param)
else:
p2.append(param)
return [... |
class TestSelectionMethod(unittest.TestCase):
class MySelectionMethod(model_selection.SelectionMethod):
def run_acc(self, run_records):
return {'val_acc': run_records[0]['env0_out_acc'], 'test_acc': run_records[0]['env0_in_acc']}
def test_sweep_acc(self):
sweep_records = Q([make_reco... |
def test_override(capture, msg):
class ExtendedExampleVirt(m.ExampleVirt):
def __init__(self, state):
super(ExtendedExampleVirt, self).__init__((state + 1))
self.data = 'Hello world'
def run(self, value):
print(('ExtendedExampleVirt::run(%i), calling parent..' % v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.