code stringlengths 101 5.91M |
|---|
def train_one_epoch(epoch, model, loader, optimizer, loss_fn, args, lr_scheduler=None, saver=None, output_dir='', amp_autocast=suppress, loss_scaler=None, model_ema=None, mixup_fn=None, optimizers=None):
assert isinstance(loss_scaler, ApexScaler)
if (args.mixup_off_epoch and (epoch >= args.mixup_off_epoch)):
... |
def traveltime(origin_id, destination_id, meters_per_minute, locations):
dist = np.sqrt((((locations.at[(destination_id, 'x')] - locations.at[(origin_id, 'x')]) ** 2) + ((locations.at[(destination_id, 'y')] - locations.at[(origin_id, 'y')]) ** 2)))
tt = np.ceil((dist / meters_per_minute))
return tt |
def learn(buffer, agent, actor_optimizer, critic_optimizer, target_entropy, critic_target_improvement, max_critic_updates_per_step, batch_size, gamma, critic_clip, actor_clip):
per = isinstance(buffer, replay.PrioritizedReplayBuffer)
if per:
(batch, imp_weights, priority_idxs) = buffer.sample(batch_size... |
class PersistentValue(Command):
def __init__(self, value):
super().__init__(duration=0)
if (abs(value) > 1):
raise PulseError('Absolute value of PV amplitude exceeds 1.')
self._value = complex(value)
def value(self):
return self._value
def __eq__(self, other):
... |
class FixedLengthBatchSampler(Sampler):
def __init__(self, data_source, batch_size, include_partial=False, rng=None, maxlen=None, length_to_size=None):
self.data_source = data_source
self.active = False
if (rng is None):
rng = np.random.RandomState(seed=11)
self.rng = rng... |
def add_our_config(cfg):
cfg.ORACLE = False
cfg.PSEUDO = False
cfg.PSEUDO_WITH_PRIOR = True
cfg.PSEUDO_REJECT_THRESHOLD = 0.0
cfg.TEST.SLIDING_WINDOW = False
cfg.TEST.SLIDING_TILE_SIZE = 224
cfg.TEST.SLIDING_OVERLAP = (2 / 3.0)
cfg.PSEUDO_FLAG_NAME = 'trainable_flag'
cfg.SOLVER.TEST_... |
class Timeslot():
def __init__(self, interval: Interval, channel: Channel):
self._interval = interval
self._channel = channel
def interval(self):
return self._interval
def channel(self):
return self._channel
def shift(self, time: int) -> 'Timeslot':
return Timeslo... |
def show_parameters(vrblvl=0):
if (vrblvl > 0):
print('in show_parameters ...')
phc = get_phcfun()
aaa = pointer(c_int32(0))
bbb = pointer(c_int32(0))
ccc = pointer(c_double(0.0))
vrb = c_int32(vrblvl)
if (vrblvl > 0):
print('-> show_parameters calls phc', end='')
retval ... |
class BoxPredictor(object):
def __init__(self, is_training, num_classes):
self._is_training = is_training
self._num_classes = num_classes
def num_classes(self):
return self._num_classes
def predict(self, image_features, num_predictions_per_location, scope, **params):
with tf.... |
def calculate_bleu(tgt, logits, vocab):
word_map = vocab.word2idx
pred = logits.max(2)[1]
references = list()
hypotheses = list()
img_caps = tgt.tolist()
img_captions = list(map((lambda c: [w for w in c if (w not in {word_map['<start>'], word_map['<end>'], word_map['<pad>']})]), img_caps))
r... |
def _extract_images(filename, num_images):
print('Extracting images from: ', filename)
with gzip.open(filename) as bytestream:
bytestream.read(16)
buf = bytestream.read((((_IMAGE_SIZE * _IMAGE_SIZE) * num_images) * _NUM_CHANNELS))
data = np.frombuffer(buf, dtype=np.uint8)
data = ... |
class AverageMeter():
def __init__(self, dataset):
self.benchmark = dataset.benchmark
self.class_ids_interest = dataset.class_ids
self.class_ids_interest = torch.tensor(self.class_ids_interest).cuda()
if (self.benchmark == 'pascal'):
self.nclass = 20
elif (self.be... |
def get_type(element):
for tag in element.findall('tag'):
if (tag.get('k') == 'type'):
return tag.get('v')
return None |
def save_args_txt(args, acc=None):
log_path = os.path.join(os.path.join(args.log_dir, 'args.txt'))
if (acc and is_main_process()):
with open(log_path, 'a') as f:
f.write('\n')
f.write(f'Final Best Acc: {acc:.2f}%')
return
with open(log_path, 'w') as f:
for (ke... |
class AttentionStore(AttentionControl):
def __init__(self):
super(AttentionStore, self).__init__()
self.step_store = self.get_empty_store()
self.attention_store = {}
def get_empty_store():
return {'down_cross': [], 'mid_cross': [], 'up_cross': [], 'down_self': [], 'mid_self': [],... |
def download_diagnostic(data_dir):
print('Downloading and extracting diagnostic...')
if (not os.path.isdir(os.path.join(data_dir, 'diagnostic'))):
os.mkdir(os.path.join(data_dir, 'diagnostic'))
data_file = os.path.join(data_dir, 'diagnostic', 'diagnostic.tsv')
urllib.request.urlretrieve(TASK2PAT... |
class Pytorch1_11():
def test_bf16_pytorch_1_11(self):
model = resnet18(num_classes=10)
x = torch.rand((10, 3, 256, 256))
with pytest.raises(RuntimeError, match='Require torch>=1.12 to obtain bfloat16 acceleration.'):
bf16_model = InferenceOptimizer.quantize(model, precision='bf1... |
def caltech256():
return collect_download_configs((lambda : datasets.Caltech256(ROOT, download=True)), name='Caltech256') |
def get_batch(data_iterator, timers):
keys = ['text', 'types', 'is_random', 'mask', 'mask_labels', 'pad_mask']
datatype = torch.int64
timers('data loader').start()
if (data_iterator is not None):
data = next(data_iterator)
else:
data = None
timers('data loader').stop()
data_b... |
def plot_embedding(X, Y):
(x_min, x_max) = (np.min(X, 0), np.max(X, 0))
X = ((X - x_min) / (x_max - x_min))
plt.figure(figsize=(10, 10))
for i in xrange(X.shape[0]):
plt.text(X[(i, 0)], X[(i, 1)], str(Y[i]), color=plt.cm.Set1((Y[i] / 10.0)), fontdict={'weight': 'bold', 'size': 12})
plt.savef... |
class Operation():
def __init__(self, print_symbol, target_state, verbosity):
self.print_symbol = print_symbol
self.target_state = target_state
self.verbosity = verbosity
def execute(self, tape):
tape.write(self.print_symbol)
r = False
if self.target_state:
... |
def create_dag_metadata() -> Dict[(int, Dict[(str, Union[(List[int], List[str], Dict[(str, Dict[(str, str)])])])])]:
flow_ = flow()
cell_num_to_used_imports: Dict[(int, Set[Symbol])] = defaultdict(set)
cell_num_to_inputs: Dict[(int, Set[Symbol])] = defaultdict(set)
cell_num_to_outputs: Dict[(int, Set[Sy... |
def decompositCommand(command_string):
command_list = []
each_command = []
num_select = ''
for idx in range(0, len(command_string)):
if command_string[idx].isdigit():
num_select += command_string[idx]
else:
each_command.append(num_select)
each_command.... |
def title2anchor(name):
return re.sub('-+', '-', re.sub('[^a-zA-Z0-9]', '-', name.strip().lower())).strip('-') |
class TestWrappers(unittest.TestCase):
def test_A_matrix_stub(self):
model_labels = {'observations': {'grass_observation': ['wet', 'dry'], 'weather_observation': ['clear', 'rainy', 'cloudy']}, 'states': {'weather_state': ['raining', 'clear'], 'sprinkler_state': ['on', 'off']}}
num_hidden_state_facto... |
class BertForMaskedLM():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def _aatype_to_str_sequence(aatype):
return ''.join([residue_constants.restypes_with_x[aatype[i]] for i in range(len(aatype))]) |
def download_pretrained_weights():
import urllib.request
import tarfile
logging.info(f'Downloading ImageNet pretrained weights for {FLAGS.architecture}')
filename = f'{FLAGS.architecture}_2017_04_14.tar.gz'
target_path = f'{paths.DATA_ROOT}/pretrained/{FLAGS.architecture}_2017_04_14/{filename}'
... |
def gen_iterator(out_path, dataset, gen_p):
global gen
gen = gen_p
if (not os.path.exists(out_path)):
os.makedirs(out_path)
print(out_path)
loader = dataset.get_loader(shuffle=True)
for (i, data) in tqdm(enumerate(loader)):
path = os.path.normpath(data['path'][0])
export_... |
def train(P, opt, train_fn, models, optimizers, train_loader, logger):
(generator, discriminator, g_ema) = models
(opt_G, opt_D) = optimizers
losses = {'G_loss': [], 'D_loss': [], 'D_penalty': [], 'D_real': [], 'D_gen': [], 'D_r1': []}
metrics = {}
metrics['image_grid'] = ImageGrid(volatile=P.no_gif... |
_model
def ese_vovnet39b(pretrained=False, **kwargs):
return _vovnet('ese_vovnet39b', pretrained=pretrained, **kwargs) |
class AttributeDatasetArgs():
dataset_name: str = field(metadata={'alias': '-d', 'help': 'The type of dataset to be loaded for attribution.'})
input_text_field: Optional[str] = field(metadata={'alias': '-f', 'help': 'Name of the field containing the input texts used for attribution.'})
generated_text_field:... |
class ProjectionUpdater(nn.Module):
def __init__(self, instance, feature_redraw_interval):
super().__init__()
self.instance = instance
self.feature_redraw_interval = feature_redraw_interval
self.register_buffer('calls_since_last_redraw', torch.tensor(0))
def fix_projections_(self... |
class VQADataset():
def __init__(self, dataset_type, questions_path, answers_path, images_path, tokenizer_path, vocab_size=20000, question_max_len=None):
if isinstance(dataset_type, DatasetType):
self.dataset_type = dataset_type
else:
raise TypeError('dataset_type has to be o... |
def linear_flops_counter_hook(module, input, output):
input = input[0]
batch_size = input.shape[0]
module.__flops__ += ((batch_size * input.shape[1]) * output.shape[1]) |
def _get_p_r_f1(tp, fp, fn):
p = round(((tp / (tp + fp)) if ((tp > 0) or (fp > 0)) else 0.0), ndigits=4)
r = round(((tp / (tp + fn)) if ((tp > 0) or (fn > 0)) else 0.0), ndigits=4)
f1 = round(((((2 * p) * r) / (p + r)) if ((p > 0) or (r > 0)) else 0.0), ndigits=4)
return (p, r, f1) |
def load_state_dict_flexible(model, state_dict):
try:
model.load_state_dict(state_dict)
except:
print('Full loading failed!! Try partial loading!!')
own_state = model.state_dict()
for (name, param) in state_dict.items():
if (name not in own_state):
print(('Skipped: ' ... |
def train_atari(args):
gin.parse_config_file(args.config)
def make_env():
return super_sac.wrappers.load_atari(args.game, frame_skip=4)
train_env = super_sac.wrappers.Uint8Wrapper(super_sac.wrappers.ParallelActors(make_env, args.parallel_actors))
test_env = super_sac.wrappers.Uint8Wrapper(make_e... |
def generate_aug_list(merged_list, excluded_list):
return list((set(merged_list) - set(excluded_list))) |
class TestInsertInputOuputData(unittest.TestCase):
def setUpClass(self):
pass
def tearDownClass(self):
pass
def test_input_output_data(self):
graph = Graph()
graph.framework_modeling_config['framework'] = 'onnxruntime'
input_data_node = OPERATORS['ONNXINPUT']()
... |
def expand_minimum_ndim(a, target_dim, axis=(- 1)):
if is_tf_data(a):
cur_dim = len(a.get_shape())
b = a
for i in range(cur_dim, target_dim):
b = tf.expand_dims(b, axis=axis)
else:
if isinstance(a, np.ndarray):
b = a
else:
b = np.array(... |
class ElectraConfig(PretrainedConfig):
model_type = 'electra'
def __init__(self, vocab_size=30522, embedding_size=128, hidden_size=256, num_hidden_layers=12, num_attention_heads=4, intermediate_size=1024, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, ... |
class FlaxPNDMScheduler(FlaxSchedulerMixin, ConfigMixin):
_compatibles = [e.name for e in FlaxKarrasDiffusionSchedulers]
dtype: jnp.dtype
pndm_order: int
def has_state(self):
return True
_to_config
def __init__(self, num_train_timesteps: int=1000, beta_start: float=0.0001, beta_end: floa... |
def args(mode):
assert (mode in ['train', 'test', 'debug'])
parser = argparse.ArgumentParser()
if (mode == 'train'):
parser.add_argument('--optim', default='SGD', help='set the optimizer of model [Adadelta, Adagrad, Adam, SparseAdam, Adamax, ASGD, LBFGS, RMSprop, Rprop, SGD]')
parser.add_arg... |
def clarin_corpora_sorted_by_size(base_directory: Path) -> List[GermanClarinCorpus]:
return [sc1(base_directory), pd2(base_directory), ziptel(base_directory), sc10(base_directory), GermanClarinCorpus('all.HEMPEL.4.cmdi.11610.', base_directory), GermanClarinCorpus('all.PD1.3.cmdi.16312.', base_directory), GermanClar... |
def append_embedding_input_for_ranking(column_name, input_tensors):
append_tensor_to_collection(RANKING_SERVICE_EMBEDDING, column_name, 'input', input_tensors) |
def main_validation(default_evaluation_params_fn, validate_data_fn):
try:
p = dict([s[1:].split('=') for s in sys.argv[1:]])
evalParams = default_evaluation_params_fn()
if ('p' in p.keys()):
evalParams.update((p['p'] if isinstance(p['p'], dict) else json.loads(p['p'][1:(- 1)])))
... |
class GPT2TokenizerFast(metaclass=DummyObject):
_backends = ['tokenizers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tokenizers']) |
def operator_getitem(a, b):
def to_concrete(t):
if isinstance(t, torch.Tensor):
concrete = torch.ones_like(t, device=_DEVICE)
if (concrete.dtype in [torch.float16, torch.float32, torch.float64, torch.int32]):
concrete = concrete.to(torch.int64)
return conc... |
def _compute_all_nbb(img_dir, conf_th, max_bb, min_bb, nproc):
files = glob.glob(f'{img_dir}/*.npz')
with mp.Pool(nproc) as pool:
fname2nbb = dict(pool.imap_unordered(_compute_item(conf_th, max_bb, min_bb), tqdm(files), chunksize=2048))
return fname2nbb |
class ClassificationHead(nn.Sequential):
def __init__(self, in_channels, classes, pooling='avg', dropout=0.2, activation=None):
if (pooling not in ('max', 'avg')):
raise ValueError("Pooling should be one of ('max', 'avg'), got {}.".format(pooling))
pool = (nn.AdaptiveAvgPool2d(1) if (poo... |
_ingredient.named_config
def cars():
name = 'cars'
data_path = 'data/CARS_196'
resize = (256, 256)
color_jitter = (0.3, 0.3, 0.3, 0.1)
ratio = (1, 1) |
def generate_data_fn2(rows, cnt, x_low, x_high, fn):
x_array = []
y_array = []
while (len(x_array) < rows):
args = ([np.random.uniform(x_low, x_high)] * cnt)
try:
y = fn(*args)
if (not math.isnan(y)):
x_array.append(args)
y_array.append... |
class BertGenerationDecoder(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class MuLBertTrainer(BaseTrainer):
def __init__(self, config, logger):
super().__init__(config, logger)
self.bert_config = self.config.model_config.bert
self.load()
self.scaler = torch.cuda.amp.GradScaler()
def load_dataset(self):
self.logger.write('Loading dataset')
... |
def stable_cumsum(arr, rtol=1e-05, atol=1e-08):
out = np.cumsum(arr, dtype=np.float64)
expected = np.sum(arr, dtype=np.float64)
if (not np.allclose(out[(- 1)], expected, rtol=rtol, atol=atol)):
raise RuntimeError('cumsum was found to be unstable: its last element does not correspond to sum')
ret... |
class DBLP4k(BaseData):
def __init__(self, data_root: Optional[str]=None):
super().__init__('dblp_4k', data_root)
self._content = {'num_classes': 4, 'num_vertices': 4057, 'num_paper_edges': 14328, 'num_term_edges': 7723, 'num_conf_edges': 20, 'dim_features': 334, 'features': {'upon': [{'filename': '... |
def predict(audio_path, question):
print('audio path, ', audio_path)
begin_time = time.time()
if (audio_path != None):
(cur_audio_input, cur_input) = load_audio_trans(audio_path)
if (torch.cuda.is_available() == False):
pass
else:
cur_audio_input = cur_audio_i... |
_module()
class GANLoss(nn.Module):
def __init__(self, gan_type, real_label_val=1.0, fake_label_val=0.0, loss_weight=1.0):
super().__init__()
self.gan_type = gan_type
self.real_label_val = real_label_val
self.fake_label_val = fake_label_val
self.loss_weight = loss_weight
... |
class LogF1PrecRecHeatmap(Callback):
def __init__(self, class_names: List[str]=None):
self.preds = []
self.targets = []
self.ready = True
def on_sanity_check_start(self, trainer, pl_module):
self.ready = False
def on_sanity_check_end(self, trainer, pl_module):
self.re... |
def calculate_fid_given_paths(paths, batch_size, cuda, dims):
for p in paths:
if (not os.path.exists(p)):
raise RuntimeError(('Invalid path: %s' % p))
block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[dims]
model = InceptionV3([block_idx])
if cuda:
model.cuda()
print('calculate ... |
class VectorizedGP(VectorizedModel):
def __init__(self, input_dim, feature_dim=2, covar_module_str='SE', mean_module_str='constant', mean_nn_layers=(32, 32), kernel_nn_layers=(32, 32), nonlinearlity=torch.tanh):
super().__init__(input_dim, 1)
self._params = OrderedDict()
self.mean_module_str... |
def make_keras_picklable():
import keras.models
def __getstate__(self):
model_str = ''
with tempfile.NamedTemporaryFile(suffix='.hdf5', delete=True) as fd:
keras.models.save_model(self, fd.name, overwrite=True)
model_str = fd.read()
return {'model_str': model_str}... |
class PPOTrainer(Trainer):
policy_class = PPOPolicy
def __init__(self, tensorboard_log_dir: Optional[str]=None, ppo_epoch: int=4, num_mini_batch: int=32, clip_param: float=0.2, use_clipped_value_loss: bool=True, use_linear_lr_decay: bool=False, lr: float=0.0007, eps: float=1e-05, value_loss_coef: float=0.5, ent... |
class ColorJitter(_BasicTransform):
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.hue = hue
def get_params(brightness, contrast, saturation, hue):
transforms = []
... |
def _merge_a_into_b(a, b, stack=None):
assert isinstance(a, AttrDict), 'Argument `a` must be an AttrDict'
assert isinstance(b, AttrDict), 'Argument `b` must be an AttrDict'
for (k, v_) in a.items():
full_key = ((('.'.join(stack) + '.') + k) if (stack is not None) else k)
if (k not in b):
... |
def rotate_batch(batch, label):
if (label == 'rand'):
labels = torch.randint(4, (len(batch),), dtype=torch.long)
elif (label == 'expand'):
labels = torch.cat([torch.zeros(len(batch), dtype=torch.long), (torch.zeros(len(batch), dtype=torch.long) + 1), (torch.zeros(len(batch), dtype=torch.long) + ... |
class RoIAlignAvg(Module):
def __init__(self, aligned_height, aligned_width, spatial_scale, sampling_ratio):
super(RoIAlignAvg, self).__init__()
self.aligned_width = int(aligned_width)
self.aligned_height = int(aligned_height)
self.spatial_scale = float(spatial_scale)
self.sa... |
class ComponentEncoder(nn.Module):
def __init__(self, body, final_shape, sigmoid=False):
super().__init__()
self.body = nn.ModuleList(body)
self.final_shape = final_shape
self.sigmoid = sigmoid
def forward(self, x):
ret_feats = {}
for (i, layer) in enumerate(self.... |
class ScriptArguments():
model_name: Optional[str] = field(default='./output_threat_type', metadata={'help': 'the model name'})
output_name: Optional[str] = field(default=None, metadata={'help': 'the model name'}) |
def parse_pgb_tree(bins, nodes_idx, nodes_split_bin, nodes_split_feature, leaves_idx, leaves_mu, learning_rate, lt_op=0, is_float32=False):
children_left = []
children_right = []
feature = []
threshold = []
leaf_vals = []
if (np.sum(nodes_idx) == 0):
leaf_vals.append(((- leaves_mu[0]) * ... |
('slow_tv')
class SlowTvDataset(MdeBaseDataset):
VALID_DATUM = 'image support K'
SHAPE = (720, 1280)
def __init__(self, split: str, mode: str, **kwargs):
super().__init__(**kwargs)
self.split = split
self.mode = mode
(self.split_file, self.items_data) = self.parse_items()
... |
def hypertree_model(images=None, vectors=None, image_shapes=None, vector_shapes=None, dropout_rate=None, activation='sigmoid', final_pooling=None, include_top=True, top='segmentation', top_block_filters=64, classes=1, output_shape=None, create_image_tree_roots_fn=None, create_vector_tree_roots_fn=None, create_tree_trun... |
class DistilBertOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task == 'multiple-choice'):
dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
dynamic_axis = {0: 'batch', 1: 'sequence'}
return OrderedDict([('input_i... |
class MPNetModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def fmeasure_from_file(golden_file, predict_file, label_type='BMES'):
print('Get f measure from file:', golden_file, predict_file)
print('Label format:', label_type)
(golden_sent, golden_labels) = readSentence(golden_file)
(predict_sent, predict_labels) = readSentence(predict_file)
(P, R, F) = get_n... |
def convert_to_skopt_space(method, space):
return [convert_param_to_skopt(param, name=name) for (name, param) in space[method].items()] |
def get_model_tuning_dict_results():
tuning_result_dict = {}
framework_version = get_framework_version(shlex.quote(args.framework))
if os.path.exists(tuning_log):
print('tuning log found')
tmp = {'fp32_acc': 0, 'int8_acc': 0, 'tuning_trials': 0}
with open(tuning_log, 'r') as f:
... |
def get_session_classes(args, session):
class_list = np.arange((args.base_class + (session * args.way)))
return class_list |
class Logger(object):
'Reference:
def __init__(self, fn, subdir=None, resume=None):
if (not os.path.exists('./logs/')):
os.mkdir('./logs/')
if resume:
logdir = resume
else:
logdir = self._make_dir(fn, subdir)
if (not os.path.exists(logdir)... |
def densenet201(pretrained=False, **kwargs):
model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 48, 32), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['densenet201']), strict=False)
return model |
def display_alongside_source_image(images):
res = np.concatenate([np.array(image) for image in images], axis=1)
return Image.fromarray(res) |
def query_cluster(db_path: str):
conn = sqlite3.connect(f'{db_path}')
cursor = conn.cursor()
cursor.execute('select * from cluster')
conn.commit()
results = cursor.fetchall()
table = PrettyTable()
table.field_names = [i[0] for i in cursor.description]
for row in results:
table.ad... |
_model
def ecaresnext50t_32x4d(pretrained=False, **kwargs):
model_args = dict(block=Bottleneck, layers=[2, 2, 2, 2], cardinality=32, base_width=4, stem_width=32, stem_type='deep_tiered', avg_down=True, block_args=dict(attn_layer='eca'), **kwargs)
return _create_resnet('ecaresnext50t_32x4d', pretrained, **model_... |
class HDF5Datamodule_2d(pl.LightningDataModule):
def __init__(self, name='h5_datamodule_2d', train_path='/content/drive/MyDrive/MILA/snapshots.h5', val_path='/content/drive/MyDrive/MILA/snapshots.h5', test_path='/content/drive/MyDrive/MILA/snapshots.h5', nt_train=128, res_train=256, nt_val=128, res_val=256, nt_test... |
def create_regularization_fns(args):
regularization_fns = []
regularization_coeffs = []
for (arg_key, reg_fn) in six.iteritems(REGULARIZATION_FNS):
if (args[arg_key] is not None):
regularization_fns.append(reg_fn)
regularization_coeffs.append(args[arg_key])
regularization... |
class GELU(nn.Module):
def forward(self, x):
return ((0.5 * x) * (1 + torch.tanh((math.sqrt((2 / math.pi)) * (x + (0.044715 * torch.pow(x, 3))))))) |
class MXNetModel(BaseModel):
def __init__(self, model, **kwargs):
self.q_config = None
self._model = model
self.calib_cache = {}
def framework(self):
return 'mxnet'
def model(self):
return self._model
def model(self, model):
self._model = model
def sav... |
class Proposal(Layer):
def __init__(self, pre_nms_topn, post_nms_topn, ratios, scales, rpn_pre_nms_topn_train=12000, rpn_post_nms_topn_train=2000, bigdl_type='float'):
super(Proposal, self).__init__(None, bigdl_type, pre_nms_topn, post_nms_topn, ratios, scales, rpn_pre_nms_topn_train, rpn_post_nms_topn_trai... |
def parse_numpy_printoption(kv_str):
k_v_str = kv_str.split('=', 1)
if ((len(k_v_str) != 2) or (not k_v_str[0])):
raise argparse.ArgumentTypeError(("'%s' is not in the form k=v." % kv_str))
(k, v_str) = k_v_str
printoptions = np.get_printoptions()
if (k not in printoptions):
raise ar... |
(InducingImages, Conv2d)
def _Kuu_conv2d(feat: InducingImages, kern: Conv2d, jitter: float=0.0):
_Kuu = kern.kernel.K(feat.as_patches)
return tf.linalg.set_diag(_Kuu, (tf.linalg.diag_part(_Kuu) + jitter)) |
def build_model(vocab, embed_dim: int=100, hid_dim: int=100, min_dec_step: int=2, max_decoding_steps: int=3, fix_edu_num: int=(- 1), use_elmo: bool=False, dropout=0.5, dropout_emb=0.2, span_encoder_type='self_attentive', attn_type='dot', schedule_ratio_from_ground_truth=0.7, pretrain_embedding=None, nenc_lay: int=1, mu... |
def test_single_char_arguments():
def toobig_message(r):
return 'Character code point not in range({0:#x})'.format(r)
toolong_message = 'Expected a character, but multi-character string found'
assert (m.ord_char(u'a') == 97)
assert (m.ord_char_lv(u'b') == 98)
assert (m.ord_char(u'e') == 233)... |
class FLANN():
__rn_gen = _rn.RandomState()
_as_parameter_ = property((lambda self: self.__curindex))
def __init__(self, **kwargs):
self.__rn_gen.seed()
self.__curindex = None
self.__curindex_data = None
self.__curindex_type = None
self.__flann_parameters = FLANNParam... |
def ycbcr2bgr(img):
img_type = img.dtype
img = (_convert_input_type_range(img) * 255)
out_img = ((np.matmul(img, [[0., 0., 0.], [0., (- 0.), 0], [0, (- 0.), 0.]]) * 255.0) + [(- 276.836), 135.576, (- 222.921)])
out_img = _convert_output_type_range(out_img, img_type)
return out_img |
def smart_round(x, base=None):
if (base is None):
if (x > (32 * 8)):
round_base = 32
elif (x > (16 * 8)):
round_base = 16
else:
round_base = 8
else:
round_base = base
return max(round_base, (round((x / float(round_base))) * round_base)) |
def calculate_FrameAccuracy(pred, true):
compare_array = np.all(((pred - true) == 0), axis=(- 1))
hit = np.sum(compare_array.astype(int))
sample_nb = true.shape[0]
accuracy_frame = ((hit * 1.0) / sample_nb)
return accuracy_frame |
def test_vector(doc):
l = m.cast_vector()
assert (l == [1])
l.append(2)
assert m.load_vector(l)
assert m.load_vector(tuple(l))
assert (m.cast_bool_vector() == [True, False])
assert m.load_bool_vector([True, False])
assert (doc(m.cast_vector) == 'cast_vector() -> List[int]')
assert (d... |
def add_head(code_split_dir, source_path, new_split_path):
code_split_list = os.listdir(code_split_dir)
source_file = open(source_path, encoding='utf-8')
source_lines = source_file.readlines()
new_file = open(new_split_path, 'w', encoding='utf-8')
os.chdir(code_split_dir)
for f in tqdm(code_spli... |
class DenseModel(nn.Module):
def __init__(self, feature_size: int, output_shape: tuple, layers: int, hidden_size: int, dist='normal', activation=nn.ELU):
super().__init__()
self._output_shape = output_shape
self._layers = layers
self._hidden_size = hidden_size
self._dist = di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.