code stringlengths 101 5.91M |
|---|
class MultiSingingSpeechMixValidation(Dataset):
dataset_name = 'multi_singing_with_speech_valid'
def __init__(self, data_dir, sample_rate=24000, n_src=2, segment=6, augment=True):
self.source_1_paths = []
self.source_2_data_root = []
self.metadata_list = []
for data_dir_set in da... |
def create_env(env_id, args, rank=(- 1)):
if ('v0' in env_id):
import ENV.DigitalPose2DBase as poseEnv
else:
import ENV.DigitalPose2D as poseEnv
env = poseEnv.gym.make(env_id, args.render_save)
return env |
def splitlines(lines: list[str], sep: ty.N[str]=None) -> list[list[str]]:
return [l.split(sep) for l in lines] |
class Apollo(Optimizer):
def __init__(self, params, lr, beta=0.9, eps=0.0001, rebound='constant', warmup=500, init_lr=None, weight_decay=0, weight_decay_type=None):
if (not (0.0 < lr)):
raise ValueError('Invalid learning rate value: {}'.format(lr))
if (not (0.0 <= eps)):
rais... |
def test_default_args():
run_cell('\n x = 7\n def foo(y=x):\n return y + 5\n ')
run_cell('a = foo()')
assert_not_detected()
run_cell('x = 10')
assert_not_detected()
run_cell('b = foo()')
assert_detected('Should have detected stale dependency of fn foo() on x') |
class BatchWhiten(Module):
def __init__(self, num_features: int, momentum: float=0.1, track_running_stats: bool=True, device=None, dtype=None) -> None:
factory_kwargs = {'device': device, 'dtype': dtype}
super(BatchWhiten, self).__init__()
self.num_features = num_features
self.moment... |
def continue_training(logdir):
hypes = utils.load_hypes_from_logdir(logdir)
modules = utils.load_modules_from_logdir(logdir)
with tf.Session() as sess:
with tf.name_scope('Queues'):
queue = modules['input'].create_queues(hypes, 'train')
tv_graph = core.build_training_graph(hypes,... |
class ImageTransformer(object):
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
self.output_size = output_size
def __call__(self, sample):
images = sample['images']
resized_images = []
for image in images:
(height, width) = image.... |
class SimpleModel(Model):
def __init__(self, output_dim=2, hidden_sizes=(4, 4), name=None):
super().__init__(name)
self._output_dim = output_dim
self._hidden_sizes = hidden_sizes
def network_output_spec(self):
return ['state', 'action']
def _build(self, obs_input, name=None):... |
def test_chunk_text_preprocessor():
df = pd.read_csv(os.path.join(data_folder, fname))
text_processor = TextPreprocessor(text_col=text_col, n_cpus=1, maxlen=10, max_vocab=50)
X_text = text_processor.fit_transform(df)
chunk_text_processor = ChunkTextPreprocessor(text_col=text_col, n_chunks=n_chunks, n_cp... |
def evaluate(args, model, tokenizer, prefix=''):
eval_task_names = (('mnli', 'mnli-mm') if (args.task_name == 'mnli') else (args.task_name,))
eval_outputs_dirs = ((args.output_dir, (args.output_dir + '-MM')) if (args.task_name == 'mnli') else (args.output_dir,))
results = {}
for (eval_task, eval_output_... |
def check_has_diff_elements(given_set: (list or set), universal_set: (list or set), msg: str=''):
diff_set = (set(given_set) - set(universal_set))
if (len(diff_set) > 0):
raise ValueError((msg % {'diff_set': diff_set})) |
def multi_gpu_test(model, data_loader, tmpdir=None, gpu_collect=False, pre_eval=False):
results = single_gpu_test(model, data_loader, pre_eval=True)
return results |
def guassian_rev_tozero_tolinear(x, prec=tf.float64):
a = 0.5
b = (- 0.)
x0 = 0.
step1 = tf.where(tf.greater(x, 0.0), (1.0 - tf.exp(((- x) * x))), tf.zeros_like(x))
return tf.where(tf.greater(x, x0), ((a * x) + b), step1) |
class DataIterator():
def __init__(self, dataset, batch_size, batch_by_tokens, max_src_length, max_tgt_length, buffer_multiple_size, device, model_path, len_diff=(- 1), len_ratio=(- 1), multi_scale=1, corpus='train', bucket_data=True, rank=(- 1), num_replicas=0):
self.train = False
self.device = dev... |
class SpatialMaxPooling(Layer):
def __init__(self, kw, kh, dw, dh, pad_w=0, pad_h=0, to_ceil=False, format='NCHW', bigdl_type='float'):
super(SpatialMaxPooling, self).__init__(None, bigdl_type, kw, kh, dw, dh, pad_w, pad_h, to_ceil, format) |
class World():
def __init__(self, bullet_client, gravity, timestep, frame_skip):
self._p = bullet_client
self.gravity = gravity
self.timestep = timestep
self.frame_skip = frame_skip
self.numSolverIterations = 5
self.clean_everything()
def clean_everything(self):
... |
class ShaResUnit(nn.Module):
def __init__(self, in_channels, out_channels, stride, bottleneck, conv1_stride, shared_conv=None):
super(ShaResUnit, self).__init__()
self.resize_identity = ((in_channels != out_channels) or (stride != 1))
if bottleneck:
self.body = ShaResBottleneck(i... |
def main(not_parsed_args):
if (len(not_parsed_args) > 1):
print(('Unknown args:%s' % not_parsed_args))
exit()
print('Building Y channel data...')
training_filenames = util.get_files_in_directory((((FLAGS.data_dir + '/') + FLAGS.dataset) + '/'))
target_dir = (((FLAGS.data_dir + '/') + FLA... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--config', default='', help='Config path.')
args = parser.parse_args()
with open(args.config) as f:
opt = yaml.load(f)
opt = EasyDict(opt['common'])
opt.learning_rate = (opt.learning_rate * (128.0 / opt.batch_size))
... |
class WatermarkLogitsProcessor(WatermarkBase, LogitsProcessor):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def _calc_greenlist_mask(self, scores: torch.FloatTensor, greenlist_token_ids) -> torch.BoolTensor:
green_tokens_mask = torch.zeros_like(scores)
for b_id... |
class FastGeLUFunction(torch.autograd.Function):
def forward(ctx, input):
ctx.save_for_backward(input)
return gelu_fwd(input)
def backward(ctx, grad_output):
(input,) = ctx.saved_tensors
tmp = gelu_bwd(grad_output, input)
return tmp |
def load_CIFAR10(data_root):
transform_train = transforms.Compose([transforms.AutoAugment(transforms.AutoAugmentPolicy.CIFAR10), transforms.ToTensor(), transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.201))])
transform_test = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.49... |
def load_torch_model_from_checkpoint(checkpoint: Union[(str, Path)], model: torch.nn.Module, map_location: str=None) -> torch.nn.Module:
if (not torch.cuda.is_available()):
map_location = 'cpu'
state_dict = torch.load(checkpoint, map_location=map_location)
if isinstance(state_dict, DataParallel):
... |
class SystemResponse(Event):
def __init__(self, session_token: str=None):
super().__init__(session_token)
self.type = 'SYSTEM_RESPONSE'
self.latency = None
def tick(self):
self._start_time = time.time()
return self
def tock(self):
assert hasattr(self, '_start_... |
(version='2.0')
def set_all_env_var(conf, overwrite_existing=False):
cpu_counts = psutil.cpu_count(logical=False)
if (not conf):
conf = {}
conf['num_of_instance'] = 1
conf['cores_per_instance'] = cpu_counts
if ('cores_per_instance' in conf):
assert ((conf['cores_per_instance'... |
_function
def conv2d_resample(x, w, f=None, up=1, down=1, padding=0, groups=1, flip_weight=True, flip_filter=False):
assert (isinstance(x, torch.Tensor) and (x.ndim == 4))
assert (isinstance(w, torch.Tensor) and (w.ndim == 4) and (w.dtype == x.dtype))
assert ((f is None) or (isinstance(f, torch.Tensor) and ... |
def get_nx_graph(file_path, full_node_list, sep='\t'):
df = pd.read_csv(file_path, sep=sep)
if (df.shape[1] == 2):
df['weight'] = 1.0
graph = nx.from_pandas_edgelist(df, 'from_id', 'to_id', edge_attr='weight', create_using=nx.Graph)
graph.add_nodes_from(full_node_list)
graph.remove_edges_fro... |
def load(config):
cls_name = config.trainer.name
try:
cls = globals()[cls_name]
return cls(config)
except KeyError:
raise Exception('No such trainer: {}'.format(cls_name)) |
def extract_raw_features(ds, path_data, layer, max_dim, mode='keyframes'):
path_raw_features = os.path.join(path_data, ds.dataset, 'conv_features', mode, layer, str(max_dim))
if (mode == 'keyframes'):
list_images = ds.keyframes
else:
list_images = ds.q_keyframes
path_raw_features = compu... |
def run_main():
if (not os.path.isdir(PATH_SCTTESTING)):
logger.warning(f'''
This folder does not exist: {PATH_SCTTESTING}''')
logger.warning('Please change the path at the top of this file')
subj_lst = [os.path.join(PATH_SCTTESTING, s, 'anat') for s in os.listdir(PATH_SCTTESTING) if os.path.isd... |
class FlaxEncoderDecoderModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class VanEncoder(nn.Module):
def __init__(self, config: VanConfig):
super().__init__()
self.stages = nn.ModuleList([])
patch_sizes = config.patch_sizes
strides = config.strides
hidden_sizes = config.hidden_sizes
depths = config.depths
mlp_ratios = config.mlp_r... |
class LSegmentationModule(pl.LightningModule):
def __init__(self, data_path, dataset, batch_size, base_lr, max_epochs, **kwargs):
super().__init__()
self.data_path = data_path
self.batch_size = batch_size
self.base_lr = ((base_lr / 16) * batch_size)
self.lr = self.base_lr
... |
def _resnet(arch, block, layers, pretrained, progress, **kwargs):
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_dict(state_dict, strict=False)
return model |
def heatmap(s, fax=None, fill_value=None, nxticks=8, nyticks=6, cbar_label=None, scaling=1.0, vmin=None, vmax=None, with_cbar=True, transpose=True, cmap='viridis', cbar_pad=0.05, cbar_ax=None, remove_day_label=True):
if (type(s) == pd.DataFrame):
if (len(s.columns) != 1):
raise ValueError(f'Expe... |
class RoIAlignFunction(Function):
def forward(ctx, features, rois, out_size, spatial_scale, sample_num=0):
if isinstance(out_size, int):
out_h = out_size
out_w = out_size
elif isinstance(out_size, tuple):
assert (len(out_size) == 2)
assert isinstance(o... |
class EncoderImageFull(nn.Module):
def __init__(self, embed_size, finetune=False, cnn_type='vgg19', use_abs=False, no_imgnorm=False):
super(EncoderImageFull, self).__init__()
self.embed_size = embed_size
self.no_imgnorm = no_imgnorm
self.use_abs = use_abs
self.cnn = self.get_... |
def evaluate(model, device, params, silent=True):
assert (len(params.eval_database_files) == len(params.eval_query_files))
stats = {}
for (database_file, query_file) in zip(params.eval_database_files, params.eval_query_files):
location_name = database_file.split('_')[0]
temp = query_file.spl... |
def build_model(frames=172, shingles=8, bands=40, channels=1, codebook=2000):
input_shape = (bands, frames, channels)
kernel = (bands, shingles)
model = Sequential([Convolution2D(codebook, kernel, strides=(1, shingles), padding='same', activation=None, input_shape=input_shape)])
return model |
def load_h5_data_label_seg(h5_filename):
f = h5py.File(h5_filename)
data = f['data'][:]
label = f['label'][:]
seg = f['pid'][:]
return (data, label, seg) |
def test_isotropic_eddington_dehnencore_in_nfw_beta_directint():
pot = potential.NFWPotential(amp=2.3, a=1.3)
denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
dfp = eddingtondf(pot=pot, denspot=denspot)
tol = 1e-08
check_beta_directint(dfp, tol, rmin=(pot._scale / 10.0), rmax=(pot._... |
class Feature(object):
def __init__(self, config, probase, nlp=None):
self.pretrain_embeddings = config.pretrain_embeddings
self.data_type = config.data_type
self.X = {d: {} for d in self.data_type}
self.y = {}
self.vectors = []
self.load_vectors_from_path(self.pretra... |
def parse_args():
parser = ArgumentParser(description='Training script: StyleGAN2 with DataParallel.')
parser.add_argument('gin_config', type=str, help='Path to the gin configuration file')
parser.add_argument('architecture', type=str, help='Architecture')
parser.add_argument('--mode', default='std', ty... |
def train_network(config: MuZeroConfig, storage: SharedStorage, replay_buffer: ReplayBuffer):
network = Network(config.action_space_size).to(device)
while True:
optimizer = optim.SGD(network.parameters(), lr=0.01, weight_decay=config.lr_decay_rate, momentum=config.momentum)
while (not (len(repla... |
def main():
parser = argparse.ArgumentParser(description='Save musdb-XL-train wave files from the downloaded sample-wise gain parameters')
parser.add_argument('--root', type=str, default='/path/to/musdb18hq', help='Root directory')
parser.add_argument('--musdb_XL_train_npy_root', type=str, default='/path/to... |
def who_collided(sim_context: SimContext) -> FrozenSet[PlayerName]:
return frozenset(chain.from_iterable(map((lambda report: report.players.keys()), sim_context.collision_reports))) |
def calc_vocab_num(predicts):
vocab = []
for sentence in predicts:
g = word_tokenize(sentence.lower())
for word in g:
if (word not in vocab):
vocab.append(word)
return vocab |
class BaselineRunner():
def __init__(self, args, config):
self.args = args
self.config = config
def get_optimizer(self, parameters):
if (self.config.optim.optimizer == 'Adam'):
return optim.Adam(parameters, lr=self.config.optim.lr, weight_decay=self.config.optim.weight_decay,... |
class MRCNERDataLoader(object):
def __init__(self, config, data_processor, label_list, tokenizer, mode='train', allow_impossible=True, entity_scheme='bes'):
self.data_dir = config.data_dir
self.data_mode = config.data_mode
self.lang_type = config.lang_type
self.save_cache_path = os.p... |
class InitWeights_XavierUniform(object):
def __init__(self, gain=1):
self.gain = gain
def __call__(self, module):
if (isinstance(module, nn.Conv3d) or isinstance(module, nn.Conv2d) or isinstance(module, nn.ConvTranspose2d) or isinstance(module, nn.ConvTranspose3d)):
module.weight = n... |
def annotation_contains(a1: Annotation, a2: Annotation):
if ((a1.evidence_start <= a2.evidence_start) and (a2.evidence_start <= a1.evidence_end) and (a1.evidence_end >= a2.evidence_end)):
return True
return False |
def ToOneHot2D(f, dim):
if (len(f.shape) == 1):
f = np.expand_dims(f, (- 1))
assert (len(f.shape) == 2)
shape = (f.shape + (dim,))
oh = np.zeros(shape)
for i in range(f.shape[0]):
for j in range(f.shape[1]):
idx = f[(i, j)]
if (idx >= 0):
oh[(i... |
class TestCircuitDrawer(QiskitTestCase):
def test_default_output(self):
with unittest.mock.patch('qiskit.user_config.get_config', return_value={}):
circuit = QuantumCircuit()
out = visualization.circuit_drawer(circuit)
self.assertIsInstance(out, text.TextDrawing)
(vis... |
class DeadlockPunishmentConfig(RewardConfig):
def __init__(self, value):
self.value = value
def create_reward_shaper(self):
return DeadlockPunishment(self.value) |
def _check_value(name, src, supported_type, supported_value=[]):
if (isinstance(src, list) and any([(not isinstance(i, supported_type)) for i in src])):
assert False, 'Type of {} items should be {} but not {}'.format(name, str(supported_type), [type(i) for i in src])
elif ((not isinstance(src, list)) an... |
def _update_optimizer_with_manual_step_learning_rate(optimizer, initial_learning_rate, learning_rate_scaling):
manual_lr = optimizer.learning_rate.manual_step_learning_rate
manual_lr.initial_learning_rate = initial_learning_rate
for i in range(3):
schedule = manual_lr.schedule.add()
schedule... |
class ClearMLCallback(TrainerCallback):
def __init__(self):
if is_clearml_available():
import clearml
self._clearml = clearml
else:
raise RuntimeError("ClearMLCallback requires 'clearml' to be installed. Run `pip install clearml`.")
self._initialized = Fal... |
def process_joint(args):
split = 'train_raw'
root = Path(args.data_root).absolute()
lang = args.tgt_lang
cur_root = (root / f'en-{lang}')
if (not cur_root.is_dir()):
print(f'{cur_root.as_posix()} does not exist. Skipped.')
df = load_df_from_tsv((cur_root / f'{split}.tsv'))
train_text... |
class TestQuantization(unittest.TestCase):
def setUpClass(self):
self.constant_graph = build_fake_model()
self.test_graph = create_test_graph()
def tearDownClass(self):
shutil.rmtree('saved', ignore_errors=True)
def test_run_mse_one_trial(self):
from neural_compressor.config ... |
def blackify(code):
has_indent = (len(get_indent(code)) > 0)
if has_indent:
code = f'''class Bla:
{code}'''
mode = black.Mode(target_versions={black.TargetVersion.PY37}, line_length=119)
result = black.format_str(code, mode=mode)
(result, _) = style_docstrings_in_code(result)
return (res... |
def main():
parser = argparse.ArgumentParser(description='Run VOT.')
parser.add_argument('tracker_name', type=str)
parser.add_argument('tracker_param', type=str)
parser.add_argument('--run_id', type=int, default=None)
args = parser.parse_args()
run_vot(args.tracker_name, args.tracker_param, args... |
def plot_metrics(data, labels, colors, wpgen, planner, maps, param_list, quantity, metrics, legendsoff, show, classic, withclassic, byplanner, nosubtitle):
barwidth = 0.1
other_quantity = np.array([*param_list.keys()])[[(x != quantity) for x in [*param_list.keys()]]][0]
new_index = pd.MultiIndex.from_arrays... |
class DGRecLayer(nn.Module):
def __init__(self, args):
super().__init__()
self.k = args.k
self.sigma = args.sigma
self.gamma = args.gamma
def similarity_matrix(self, X, sigma=1.0, gamma=2.0):
dists = th.cdist(X, X)
sims = th.exp(((- dists) / (sigma * dists.mean(di... |
def save_to_cache(path, obj):
path = Path(path)
logger = logging.getLogger(__name__)
logger.info(f'Saving to cache at {str(path)}')
path.parent.mkdir(exist_ok=True)
with open(path, 'wb') as f:
pickle.dump(obj, f) |
def compute_doc_freq(crefs):
document_frequency = defaultdict(float)
for refs in tqdm(crefs, ncols=100, desc='compute_doc_freq'):
for ngram in set([ngram for ref in refs for (ngram, count) in ref.items()]):
document_frequency[ngram] += 1
return document_frequency |
def main():
if args.tensorboard:
configure(('runs/%s' % args.name))
if args.augment:
transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4), transforms.RandomHorizontalFlip(), transforms.ToTensor()])
else:
transform_train = transforms.Compose([transforms.ToTensor(... |
def is_existed_rec(name, obj):
if isinstance(obj, list):
for s in obj:
assert os.path.exists(s), f'{name}:{s} does not exist'
fsize = (os.path.getsize(s) / float((1024 * 1024)))
print(s, round(fsize, 2))
elif isinstance(obj, str):
assert os.path.exists(obj), f... |
class RewardSwitchSTDP(Learner):
def __init__(self, trainable=None, **kwargs):
super(RewardSwitchSTDP, self).__init__(trainable=trainable, **kwargs)
self.trainable = trainable
self.prefered_backend = ['pytorch']
self.name = 'Reward_Switch_STDP'
self._constant_variables = dict... |
def compute_cumulative(df: pd.DataFrame, feature_max_dict: Dict[(str, float)]) -> pd.DataFrame:
df_sorted = df.sort_values(by=['feature', 'cutoff'], ascending=True)
df_sorted['running_sum'] = df_sorted.groupby('feature')['points'].transform((lambda x: x[::(- 1)].cumsum()[::(- 1)]))
df_interval = df_sorted[[... |
class MAE(PytorchMetric):
def __init__(self):
self.total = torch.tensor(0)
self.sum_abs_error = torch.tensor(0.0)
def __call__(self, preds, targets):
_check_same_shape(preds, targets)
self.sum_abs_error += torch.sum(torch.abs(torch.sub(preds, targets)))
self.total += targ... |
def parse_requirements(fname='requirements/runtime.txt', with_version=True):
import sys
from os.path import exists
require_fpath = fname
def parse_line(line):
if line.startswith('-r '):
target = line.split(' ')[1]
for info in parse_require_file(target):
(y... |
def process_event(events: dict[(str, Any)], labels_dictionary: dict[(str, int)]):
new_annotation = {}
for (element, value) in events.items():
if (element == 'label'):
new_annotation[element] = labels_dictionary[value]
elif (element == 'frame'):
new_annotation[element] = i... |
def get_device_map(n_layers, devices):
layers = list(range(n_layers))
n_blocks = int(ceil((n_layers / len(devices))))
layers_list = [layers[i:(i + n_blocks)] for i in range(0, n_layers, n_blocks)]
return dict(zip(devices, layers_list)) |
def fid_inception_v3():
inception = models.inception_v3(num_classes=1008, aux_logits=False, pretrained=False, init_weights=False)
inception.Mixed_5b = FIDInceptionA(192, pool_features=32)
inception.Mixed_5c = FIDInceptionA(256, pool_features=64)
inception.Mixed_5d = FIDInceptionA(288, pool_features=64)
... |
class VATLoss(nn.Module):
def __init__(self, xi=10.0, eps=1.0, prop_eps=0.25, ip=1, distance_func=KL_div(reduce=True)):
super(VATLoss, self).__init__()
self.xi = xi
self.eps = eps
self.ip = ip
self.prop_eps = prop_eps
self.distance_func = distance_func
def forward... |
def ggml_convert_fp32(tensor: torch.Tensor, weight_shape: tuple, k: int, qtype: int):
invalidInputError((tensor.dtype == torch.uint8), 'Input tensor must be uint8')
src_ptr = ctypes.c_void_p(tensor.data.data_ptr())
dst_size = k
dst_tensor = torch.empty(weight_shape, dtype=torch.float)
dst_ptr = ctyp... |
def make_diff(file, original, reformatted):
return list(difflib.unified_diff(original, reformatted, fromfile='{}\t(original)'.format(file), tofile='{}\t(reformatted)'.format(file), n=3)) |
class BYTETracker(object):
def __init__(self, args, frame_rate=30):
self.tracked_stracks = []
self.lost_stracks = []
self.removed_stracks = []
self.frame_id = 0
self.args = args
self.det_thresh = (args.track_thresh + 0.1)
self.buffer_size = int(((frame_rate / ... |
def process(device, model, model_type, image, input_size, target_size, optimize, use_camera):
global first_execution
if ('openvino' in model_type):
if (first_execution or (not use_camera)):
print(f' Input resized to {input_size[0]}x{input_size[1]} before entering the encoder')
... |
def remove_ignore_keys_(state_dict):
ignore_keys = ['encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', 'decoder.output_projection.weight', '_float_tensor', 'encoder.embed_positions._float_tensor', 'decoder.embed_positions._float_tensor']
for k in ignore_keys:
state_d... |
def cupy_kernel(strFunction, objectVariables):
strKernel = globals()[strFunction]
while True:
objectMatch = re.search('(SIZE_)([0-4])(\\()([^\\)]*)(\\))', strKernel)
if (objectMatch is None):
break
intArg = int(objectMatch.group(2))
strTensor = objectMatch.group(4)
... |
def symmetric_cross_entropy(alpha, beta):
def loss(y_true, y_pred):
y_true_1 = y_true
y_pred_1 = y_pred
y_true_2 = y_true
y_pred_2 = y_pred
y_pred_1 = tf.clip_by_value(y_pred_1, 1e-07, 1.0)
y_true_2 = tf.clip_by_value(y_true_2, 0.0001, 1.0)
return ((alpha * tf... |
def compute_input_streams(elec_pos: Array, ion_pos: Optional[Array]=None, include_2e_stream: bool=True, include_ei_norm: bool=True, ei_norm_softening: chex.Scalar=0.0, include_ee_norm: bool=True, ee_norm_softening: chex.Scalar=0.0) -> InputStreams:
(input_1e, r_ei) = compute_electron_ion(elec_pos, ion_pos, include_... |
def flatten_str_dict(hierarchical_dict):
flatten_dict = OrderedDict()
for (k, v) in hierarchical_dict.items():
if isinstance(v, dict):
flatten_v = flatten_str_dict(v)
for (kk, vv) in flatten_v.items():
flatten_dict[(k + kk)] = vv
else:
flatten_... |
class MobilenetV2(Model):
def model_url(self) -> str:
return '
def package_name(self) -> str:
return 'mobilenet_v2_1.0_224.tgz' |
class IOUEntropyDataset(BaseDataset):
def initialize(self, opt):
self.with_conf_map = False
(image_src_paths, image_rec_paths, label_paths, pred_paths, entropy_paths, conf_map_paths) = self.get_paths(opt)
util.natural_sort(image_src_paths)
util.natural_sort(image_rec_paths)
u... |
class Multinomial(object):
def __init__(self, n_variables, mean=None):
self.n_variables = n_variables
self.mean = mean
self._sample = None
self._cuda_device = None
def sample(self, n_samples=1, resample=False):
pass
def log_prob(self, sample):
maxval = torch.m... |
def multi_resolution_spectrogram_mse(gt, est, n_fft=[2048, 1024, 512], n_hop=[512, 256, 128]):
assert (gt.shape == est.shape)
assert (len(n_fft) == len(n_hop))
score = 0.0
for i in range(len(n_fft)):
gt_spec = librosa.magphase(librosa.stft(gt, n_fft=n_fft[i], hop_length=n_hop[i]))[0]
est... |
class syncbatchnorm_(Function):
def forward(cls, ctx, x, gamma, beta, running_mean, running_var, extra, sync=True, training=True, momentum=0.1, eps=1e-05, activation='none', slope=0.01):
cls._parse_extra(ctx, extra)
ctx.sync = sync
ctx.training = training
ctx.momentum = momentum
... |
def run_webcam(tracker_name, tracker_param, debug=None, visdom_info=None):
visdom_info = ({} if (visdom_info is None) else visdom_info)
tracker = Tracker(tracker_name, tracker_param)
tracker.run_webcam(debug, visdom_info) |
def lua_recursive_source(module):
s = []
for m in module.modules:
name = type(m).__name__
real = m
if (name == 'TorchObject'):
name = m._typename.replace('cudnn.', '')
m = m._obj
if (name == 'SpatialConvolution'):
if (not hasattr(m, 'groups')):... |
class LeadTimeEval():
def __init__(self, len_seq_in=4, bins_to_predict=32, n_channels=3):
self.len_seq = len_seq_in
self.n_bins = bins_to_predict
self.n_channels = n_channels
self.errors = {}
self.index = ['day_in_year', 'in_start_id', 'channel']
self.cols = (self.ind... |
def test_objective_sum():
(_, _, add_info) = compute_objective_sum(indices=np.array([0, 10, 6]), new_data={'objective': np.array([1.0, 5.0, 3.0])}, add_info={}, extra_args={'objective_sum': 10.0}, occupied=np.array([True, False, True]), cur_data={'objective': np.array([0.0, 2.0, 4.0])})
assert ('objective_sum' ... |
def repeat_generator(x_gen: 'DataGenerator', y_gen: 'DataGenerator', x_repeats: int=0, y_repeats: int=0) -> 'DataGenerator':
def repeat_outputs(_x, _y):
if (x_repeats > 0):
_x = ([_x] * (x_repeats + 1))
if (y_repeats > 0):
_y = ([_y] * (y_repeats + 1))
return (_x, _y)... |
def infer(valid_queue, model, criterion):
objs = utils.AverageMeter()
top1 = utils.AverageMeter()
top5 = utils.AverageMeter()
model.eval()
with torch.no_grad():
for (step, (input, target)) in enumerate(valid_queue):
input = Variable(input.cuda())
target = Variable(tar... |
def sample(preds, temperature=1.0):
preds = np.asarray(preds).astype('float64')
preds = (np.log(preds) / temperature)
exp_preds = np.exp(preds)
preds = (exp_preds / np.sum(exp_preds))
probas = np.random.multinomial(1, preds, 1)
return np.argmax(probas) |
def show_img_by_class(data_loader, classes):
class_images = {}
class_labels = {}
while (len(class_images) < len(classes)):
(images, labels) = next(data_loader)
for (i, label) in enumerate(labels):
if ((label.item() not in class_images) and (len(class_images) < len(classes))):
... |
class BasicBlock(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, fist_dilation=1, multi_grid=1):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=3, bias=False)
self.bn1 = nn.BatchNorm2d(planes)
... |
def regularization_loss(scope_name):
collection_regularization = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)
loss = []
for item in collection_regularization:
if (scope_name in item.name):
loss.append(item)
return tf.reduce_sum(loss) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.