code stringlengths 101 5.91M |
|---|
def test_track_progress_list():
out = StringIO()
ret = mmcv.track_progress(sleep_1s, [1, 2, 3], bar_width=3, file=out)
assert (out.getvalue() == '[ ] 0/3, elapsed: 0s, ETA:\r[> ] 1/3, 1.0 task/s, elapsed: 1s, ETA: 2s\r[>> ] 2/3, 1.0 task/s, elapsed: 2s, ETA: 1s\r[>>>] 3/3, 1.0 task/s, elapsed: 3s... |
def kl_anealing(i, high=0.1, low=0.0):
hh = (1 - low)
ll = (1 - high)
x = (10 * (i - 0.5))
z = (1 / (1 + np.exp(x)))
y = (((hh - ll) * z) + ll)
return (1 - y) |
def get_data():
from bigdl.chronos.data import get_public_dataset
from sklearn.preprocessing import StandardScaler
(tsdata_train, tsdata_val, tsdata_test) = get_public_dataset(name='nyc_taxi')
stand = StandardScaler()
for tsdata in [tsdata_train, tsdata_val, tsdata_test]:
tsdata.impute().sca... |
def make_dataset(input_dir, split, net_name, target_dir=None):
plyfiles = []
if (net_name == 'GAN'):
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)... |
class NLayerDiscriminator(nn.Module):
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False, gpu_ids=[]):
super(NLayerDiscriminator, self).__init__()
self.gpu_ids = gpu_ids
kw = 4
padw = int(np.ceil(((kw - 1) / 2)))
sequence = [nn.Conv2... |
class QuantLinear(nn.Linear):
def __init__(self, in_features, out_features, bias=True, a_bits=8, w_bits=8, quant_inference=False, all_positive=False, per_channel=False, batch_init=20):
super(QuantLinear, self).__init__(in_features, out_features, bias)
self.quant_inference = quant_inference
s... |
def abundance_to_mass_fraction(all_elements, all_masses, all_abundances, abundances, symbols):
fractions = []
for (i, item) in enumerate(symbols):
fractions.append(abundances[i])
fractions[i] -= 12
fractions[i] = np.power(10, fractions[i])
fractions[i] *= all_masses[np.where((all... |
def deeplabv3_resnetd50b_voc(pretrained_backbone=False, num_classes=21, aux=True, **kwargs):
backbone = resnetd50b(pretrained=pretrained_backbone, ordinary_init=False, multi_output=True).features
del backbone[(- 1)]
return get_deeplabv3(backbone=backbone, num_classes=num_classes, aux=aux, model_name='deepla... |
def get_model(point_cloud, is_training, bn_decay=None, num_class=NUM_CLASSES):
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_points = {}
l0_xyz = point_cloud
l0_points = None
end_points['l0_xyz'] = l0_xyz
(l1_xyz, l1_points, l1_indices) = poin... |
def _get_cosine_schedule_with_warmup_lr_lambda(current_step: int, *, num_warmup_steps: int, num_training_steps: int, num_cycles: float, min_lr_ratio: float):
if (current_step < num_warmup_steps):
return (float(current_step) / float(max(1, num_warmup_steps)))
progress = (float((current_step - num_warmup_... |
_registry(operator_type='MatMulWithBiasTanh')
class MatMulWithBiasTanh(Operator):
def __init__(self):
super().__init__() |
def check_dataset(dataset):
dataloader = DataLoader(dataset)
for batch in dataloader:
if ('views' not in batch):
raise ValueError("The dataset must return a dictionary with a 'representations' key containing a list of tensors")
else:
break |
def check_one_contract_on_ether_lock(contract_bytecode, contract_address, debug=False, read_from_blockchain=False):
print('\x1b[94m[ ] Check if contract is GREEDY\x1b[0m\n')
print(('[ ] Contract address : %s' % contract_address))
print(('[ ] Contract bytecode : %s...' % contract_bytecode[:50]))
print... |
def pytest_configure(config):
config.addinivalue_line('markers', 'is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested')
config.addinivalue_line('markers', 'is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested')
config.addinivalue_line('markers',... |
class DPRQuestionEncoder(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def create_example_autopilot(image, path, ctrl_cmd):
feature = {'image': image_feature(image), 'path': bytes_feature(path), 'left': float_feature((float(ctrl_cmd[0]) / 255.0)), 'right': float_feature((float(ctrl_cmd[1]) / 255.0)), 'cmd': float_feature(float(ctrl_cmd[2]))}
return tf.train.Example(features=tf.tra... |
class Seq2SeqSequenceClassifierOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
past_key_values: Optional[List[torch.FloatTensor]] = None
decoder_hidden_states: Optional[Tuple[torch.FloatTensor]] = None
decoder_attentions: Optional[Tuple[torch.FloatTenso... |
class DummyActorPolicy():
def __init__(self, action=1.0):
self._action = action
def __call__(self, observation):
action = torch.Tensor([self._action])
return (_MockDistribution(action), {})
def action(self, unused_observation):
del unused_observation
action = torch.Te... |
def warning_suppress(func):
(func)
def wrapper(*args, **kwargs):
with warnings.catch_warnings():
warnings.simplefilter('ignore')
return func(*args, **kwargs)
return wrapper |
def tail2label(tails):
global tail2label_table
if (tail2label_table == None):
tail2label_table = json.load(open(config['path']['Tail2Emotion'], encoding='utf8'))
tail_labels = []
for tail in tails:
if (tail in tail2label_table.keys()):
tail_labels.append(tail2label_table[tail... |
class Decoder(nn.Module):
def __init__(self, rr, theta, T, gpu_id):
super(Decoder, self).__init__()
self.rr = rr
self.theta = theta
self.T = T
self.gid = gpu_id
def forward(self, x):
dic_de = creatRealDictionary(self.T, self.rr, self.theta, self.gid)
resul... |
def test_typechange(conf_dict):
cfg = conf_dict({'a': 'bar', 'b': 'foo', 'c': 1})
assert (cfg.typechanged == {'a': (int, type('bar')), 'b': (float, type('foo')), 'c': (bool, int)}) |
class Content_Density(object):
def __init__(self, sentence_objs):
self.sentence_objs = sentence_objs
def handle(self):
(tot_num_nouns, tot_num_verbs, tot_num_adjs, tot_num_advs) = (0, 0, 0, 0)
(tot_num_det, tot_num_prep, tot_num_pron, tot_num_cconj) = (0, 0, 0, 0)
for so in self.... |
class SuperResK1KX(PlainNetBasicBlockClass):
def __init__(self, in_channels=0, out_channels=0, kernel_size=3, stride=1, expansion=1.0, sublayers=1, no_create=False, block_name=None, **kwargs):
super(SuperResK1KX, self).__init__(**kwargs)
self.in_channels = in_channels
self.out_channels = out... |
def generate_combined_transform_function(transform_funcs, indices=[0]):
for index in indices:
print(transform_funcs[index])
def combined_transform_func(sample):
for index in indices:
sample = transform_funcs[index](sample)
return sample
return combined_transform_func |
def eval(path):
if args.reconst:
eval_file_name = '/eval.pkl'
elif args.voxels:
eval_file_name = '/eval_voxelization_{}.pkl'.format(args.res)
else:
eval_file_name = '/eval_pointcloud_{}.pkl'.format(args.points)
try:
if os.path.exists((path + eval_file_name)):
... |
class Flatten(KerasLayer):
def __init__(self, input_shape=None, **kwargs):
super(Flatten, self).__init__(None, (list(input_shape) if input_shape else None), **kwargs) |
class TestKerasInKerasOut(unittest.TestCase):
def setUpClass(self):
os.environ['ITEX_ONEDNN_GRAPH'] = '1'
def tearDownClass(self):
shutil.rmtree('baseline_model', ignore_errors=True)
shutil.rmtree('itex_qdq_keras_model', ignore_errors=True)
def test_keras_in_keras_out(self):
... |
def evaluate(args, task_dataloader_val, task_cfg, device, task_id, model, task_losses, log_f):
from vilbert.vilbert_mavex import VILBertForVLTasks
from vilbert.task_utils import LoadDatasets, LoadLosses, ForwardModelsTrain, ForwardModelsVal
model.eval()
returned_variables = ['batch_score', 'batch_score_... |
def main():
gui.Application.instance.initialize()
w = ExampleWindow()
gui.Application.instance.run() |
class ContextFilter():
def filter(self, record):
split_name = record.name.split('.', 1)
if ((split_name[0] == 'BASELINE') or (split_name[0] == 'MAIN')):
if (len(split_name) > 1):
record.name = split_name[1]
if (split_name[0] == 'TESTING'):
if (len(spli... |
def create_tri_parametric_color_ramp_node(node_tree: bpy.types.NodeTree) -> bpy.types.Node:
tri_color_ramp_node_group: bpy.types.NodeGroup
if ('Tri Parametric Color Ramp' in bpy.data.node_groups):
tri_color_ramp_node_group = bpy.data.node_groups['Tri Parametric Color Ramp']
else:
tri_color_r... |
def _visit_dict_config(cfg, func):
if isinstance(cfg, DictConfig):
func(cfg)
for v in cfg.values():
_visit_dict_config(v, func)
elif isinstance(cfg, ListConfig):
for v in cfg:
_visit_dict_config(v, func) |
def split_train_test(anno_list, train_ratio_hard=0.5, train_num=1500):
nf_data = []
google_data = []
openfood_data = []
for anno_ in anno_list:
file_name = anno_['file_name'].split('/')[(- 1)]
if (file_name[:2] == 'nf'):
nf_data.append(anno_)
elif (file_name[:3] == 'G... |
class Mask2FormerPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class KandinskyPipeline(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(cls, ... |
_cache()
def is_torch_tpu_available(check_device=True):
if (not _torch_available):
return False
if (importlib.util.find_spec('torch_xla') is not None):
if check_device:
try:
import torch_xla.core.xla_model as xm
_ = xm.xla_device()
retu... |
class InputInjection(nn.Module):
def __init__(self, num_downsampling):
super(InputInjection, self).__init__()
self.pool = nn.ModuleList()
for i in range(num_downsampling):
self.pool.append(nn.AvgPool2d(3, stride=2, padding=1))
def forward(self, x):
for pool in self.po... |
def hungarian_match(flat_preds, flat_targets, preds_k, targets_k) -> Tuple[(torch.Tensor, Dict[(int, int)])]:
assert (isinstance(flat_preds, torch.Tensor) and isinstance(flat_targets, torch.Tensor) and (flat_preds.is_cuda == flat_targets.is_cuda))
assert (flat_preds.shape == flat_targets.shape)
num_samples ... |
class JavaParser(Parser):
def __init__(self, *args, **kwargs):
super(JavaParser, self).__init__(*args, **kwargs)
def parse(self, code):
raise NotImplementedError('Not yet implemented') |
def set_seed(seed):
seed %=
global seed_
seed_ = seed
import random
random.seed(seed)
np.random.seed(seed)
import torch
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
print(colorize(f'using seed {seed}', 'green')) |
def test_digits_corr_naive_init():
model = SaturatedCoverageSelection(100, 'corr', optimizer='naive', initial_subset=digits_corr_ranking[:5])
model.fit(X_digits)
assert_array_equal(model.ranking[:(- 5)], digits_corr_ranking[5:])
assert_array_almost_equal(model.gains[:(- 5)], digits_corr_gains[5:], 4)
... |
class WeightPruningConfig():
def __init__(self, pruning_configs=[{}], target_sparsity=0.9, pruning_type='snip_momentum', pattern='4x1', op_names=[], excluded_op_names=[], start_step=0, end_step=0, pruning_scope='global', pruning_frequency=1, min_sparsity_ratio_per_op=0.0, max_sparsity_ratio_per_op=0.98, sparsity_de... |
class DepthEvaluator(Harness):
def _init_validation(self, opt):
self.fixed_depth_scaling = opt.depth_validation_fixed_scaling
self.ratio_on_validation = opt.depth_ratio_on_validation
self.val_num_log_images = opt.eval_num_images
def evaluate(self):
print('Evaluate depth predictio... |
def cast_ndarray_type(x):
if (x.dtype == np.int64):
return x.astype(np.int32)
elif (x.dtype == np.float64):
return x.astype(np.float32)
else:
return x |
def test_log_scalar_metric_with_implicit_step(ex):
messages = {}
def main_function(_run):
for i in range(10):
val = (i * i)
ex.log_scalar('training.loss', val)
messages['messages'] = ex.current_run._metrics.get_last_metrics()
ex.run()
assert (ex.current_run is not... |
def get_parser():
parser = argparse.ArgumentParser()
parser.add_argument('-c', help='Config file path.')
return parser |
def kl_divergence(mu, log_sigma, device='cpu'):
return torch.mean(((- 0.5) * torch.sum((((1.0 + log_sigma) - (mu ** 2)) - torch.exp(log_sigma)), dim=(- 1)))) |
class XconfigRes2Block(XconfigLayerBase):
def __init__(self, first_token, key_to_value, prev_names=None):
assert (first_token == 'res2-block')
XconfigLayerBase.__init__(self, first_token, key_to_value, prev_names)
def set_default_configs(self):
self.config = {'input': '[-1]', 'height': (... |
def vgg11_bn(pretrained=False, **kwargs):
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A'], batch_norm=True), **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['vgg11_bn']))
return model |
_module()
class HourglassNet(BaseModule):
def __init__(self, downsample_times: int=5, num_stacks: int=2, stage_channels: Sequence=(256, 256, 384, 384, 384, 512), stage_blocks: Sequence=(2, 2, 2, 2, 2, 4), feat_channel: int=256, norm_cfg: ConfigType=dict(type='BN', requires_grad=True), init_cfg: OptMultiConfig=None)... |
class custom_dataset(torch.nn.Module):
def __init__(self, path, dim, num_class, load_from_txt=True):
super(custom_dataset, self).__init__()
self.nodes = set()
self.load_from_txt = load_from_txt
self.num_nodes = 0
self.num_features = dim
self.num_classes = num_class
... |
def get_example_outputs(agent, EnvCls, env_kwargs, examples, subprocess=False, env=None):
if subprocess:
import torch
torch.set_num_threads(1)
if (env is None):
env = EnvCls(**env_kwargs)
if (not hasattr(env, 'spaces')):
env = MVPWrapper(env)
o = env.reset()
a... |
def register_video_dataset(name, dataset):
global __video_datasets
curr_datasets = list(__video_datasets.keys())
if (name in curr_datasets):
raise ValueError('The given name already exists, please choose another name excluding {}'.format(curr_datasets))
__video_datasets[name] = dataset |
class UserScatteredDataParallel(DictGatherDataParallel):
def scatter(self, inputs, kwargs, device_ids):
assert (len(inputs) == 1)
inputs = inputs[0]
inputs = _async_copy_stream(inputs, device_ids)
inputs = [[i] for i in inputs]
assert (len(kwargs) == 0)
kwargs = [{} f... |
def get_sample_bernoulli(p):
return (lambda lst: [elem for elem in lst if (random.random() < p)]) |
def insertUser(user):
user.hashed_password = pbkdf2_sha256.hash(user.password.encode('utf-8'))
user.registered = datetime.utcnow().strftime('%Y-%m-%d-%H-%M-%S')
conn = getDb()
with closing(conn.cursor()) as cur:
sql = 'INSERT INTO users(email, salted_hash, firstname, lastname,\n ... |
def encode_dense_query(queries: Dict[(Union[(str, int)], str)], model: Union[(BertDense, RobertaDense)], tokenizer, max_seq_length: int, eval_args: TrainingArguments):
logger.info('Encoding Queries...')
query_ids = sorted(list(queries.keys()))
queries_text = [queries[qid] for qid in query_ids]
query_dat... |
def prepare_data(args, train=True):
data_args = DFR_DATA_ARGS[args.dataset]
if (data_args.data_transform == 'None'):
transform_cls = (lambda *args, **kwargs: None)
else:
transform_cls = getattr(dfr_data, data_args.data_transform)
train_transform = transform_cls(train=True)
test_trans... |
def Basic_Fourier_model():
return {'model': 'LSTM', 'hidden_depth': 3, 'hidden_width': 20, 'recurrent_layers': 2, 'state_size': 32} |
class Generator(abc.ABC):
def __init__(self, num_jobs: int, num_machines: int, max_num_ops: int, max_op_duration: int):
self.num_jobs = num_jobs
self.num_machines = num_machines
self.max_num_ops = max_num_ops
self.max_op_duration = max_op_duration
def __call__(self, key: chex.PRN... |
class StartEndDataset(Dataset):
Q_FEAT_TYPES = ['pooler_output', 'last_hidden_state']
def __init__(self, dset_name, data_path, v_feat_dirs, q_feat_dir, q_feat_type='last_hidden_state', max_q_l=32, max_v_l=75, data_ratio=1.0, ctx_mode='video', normalize_v=True, normalize_t=True, load_labels=True, clip_len=2, max... |
def parse_set_parameter_strings(set_para_array):
set_list = []
for set_para in set_para_array:
set = (lambda : None)
setattr(set, 'filename', None)
setattr(set, 'probability', None)
parts = set_para.split(',')
if (len(parts) == 2):
set.probability = float(part... |
def _target_samples_dict(y, n_target_samples, sampling_type):
target_stats = dict(Counter(y))
set_diff_sampling_strategy_target = (set(n_target_samples.keys()) - set(target_stats.keys()))
if (len(set_diff_sampling_strategy_target) > 0):
raise ValueError(f'The {set_diff_sampling_strategy_target} targ... |
class _BaseQuantizationConfig():
def __init__(self, inputs=[], outputs=[], backend='default', domain='auto', model_name='', recipes={}, quant_format='default', device='cpu', calibration_sampling_size=[100], example_inputs=None, op_type_dict=None, op_name_dict=None, reduce_range=None, excluded_precisions=[], quant_l... |
def densenet169(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> DenseNet:
return DenseNet(torchvision.models.densenet169(pretrained, progress, **kwargs)) |
def _reload_meta_parameter(module, tensor_name, device, value=None, ckpt_name=None):
if ('.' in tensor_name):
splits = tensor_name.split('.')
for split in splits[:(- 1)]:
new_module = getattr(module, split)
if (new_module is None):
raise ValueError(f'{module} ... |
class DistMult(torch.nn.Module):
def __init__(self, d, d1, d2, **kwargs):
super(DistMult, self).__init__()
self.E = torch.nn.Embedding(len(d.entities), d1, padding_idx=0)
self.R = torch.nn.Embedding(len(d.relations), d2, padding_idx=0)
self.inp_drop = torch.nn.Dropout(kwargs['input_d... |
def resolve_backend_name(name, backends, deprecated, aliased):
available = [backend.name() for backend in backends]
resolved_name = deprecated.get(name, aliased.get(name, name))
if isinstance(resolved_name, list):
resolved_name = next((b for b in resolved_name if (b in available)), '')
if (resol... |
class RecurrentDecoder(Decoder):
def __init__(self, vocab_size, latent_dim, rnn_mode, num_layers, hidden_size, bidirectional=True, dropout=0.0, dropword=0.0, label_smoothing=0.0, _shared_weight=None):
super(RecurrentDecoder, self).__init__(vocab_size, latent_dim, label_smoothing=label_smoothing, _shared_wei... |
def _add_property_function(func_name):
def property_func(self, *args, **kwargs):
result = getattr(self._tensor, func_name)(*args, **kwargs)
return result
setattr(CUDALongTensor, func_name, property_func) |
class CNN(nn.Module):
def __init__(self, dim_out):
super(CNN, self).__init__()
self.dim_out = dim_out
self.features = nn.Sequential(nn.Conv2d(1, 8, kernel_size=3, stride=2), nn.ReLU(inplace=True), nn.MaxPool2d(kernel_size=3, stride=2), nn.Conv2d(8, dim_out, kernel_size=3, stride=2), nn.ReLU(... |
class Vocab(object):
def __init__(self, filename, min_occur_cnt, specials=None):
idx2token = ([PAD, UNK] + (specials if (specials is not None) else []))
self._priority = dict()
num_tot_tokens = 0
num_vocab_tokens = 0
for line in open(filename).readlines():
try:
... |
def conv1x1(in_planes, out_planes, stride=1):
return nl.SharableConv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) |
def F1_score(pred_prob, true_prob):
(TP, FP, FN, TN) = (0, 0, 0, 0)
for (i, label) in enumerate(true_prob):
if ((label == 0) and (pred_prob[i] <= 0.5)):
TP += 1
elif ((label == 0) and (pred_prob[i] > 0.5)):
FN += 1
elif ((label == 1) and (pred_prob[i] <= 0.5)):
... |
def seed_all(seed):
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
os.environ['PYTHONHASHSEED'] = str(seed) |
def meshgrid(*tensors: Union[(torch.Tensor, List[torch.Tensor])], indexing: Optional[str]=None) -> Tuple[(torch.Tensor, ...)]:
if is_torch_greater_or_equal_than_1_10:
return torch.meshgrid(*tensors, indexing=indexing)
else:
if (indexing != 'ij'):
raise ValueError('torch.meshgrid only... |
class Audio():
def __init__(self, hyper_params):
self.hyper_params = hyper_params
self.mel_basis_matrix = librosa.filters.mel(sr=hyper_params.sample_rate, n_fft=hyper_params.n_fft, n_mels=hyper_params.embedder_num_mels)
def get_mel_spec(self, wave):
spec = librosa.core.stft(y=wave, n_fft... |
def get_bio_expression(opinion):
try:
(text, idxs) = opinion['Polar_expression']
except TypeError:
return []
except ValueError:
return []
if (len(text) > 1):
updates = []
for (t, idx) in zip(text, idxs):
(bidx, eidx) = idx.split(':')
bidx =... |
def analyze_grid_data(acc_threshold=0.01):
fh = open('hyperparameter_grid_models_slackprop.csv', 'r')
grid_data = []
for line in fh:
parsed = line.split(',')
parsed[1] = float(parsed[1])
parsed[5] = float(parsed[5])
parsed[6] = float(parsed[6])
parsed[7] = float(parse... |
def main_lower(x_minus, x_plus, y_minus, y_plus, print_info=True):
(u0, v0, ka0, kb0) = find_initial_feasible_solution(x_minus, x_plus, y_minus, y_plus)
(x, y, ka, kb, a, b, c, v) = train_lower(u0, v0, ka0, kb0, x_minus, x_plus, y_minus, y_plus, lr_x=0.01, lr_k=0.01, max_iter=200, print_info=print_info)
inc... |
def define_model_inputs_outputs(num_classes, img_size):
inputs = tf.keras.layers.Input(shape=(img_size, img_size, 3))
x = tf.cast(inputs, tf.float32)
x = tf.keras.applications.resnet50.preprocess_input(x)
backbone = ResNet50(weights='imagenet')
backbone.trainable = False
x = backbone(x)
x = ... |
def dfs(current_id, node_dict, id_visited):
next_nodes = node_dict[current_id]['next_nodes']
if (len(next_nodes) == 0):
return
if (not id_visited[current_id]):
for next_node_id in next_nodes:
if (next_node_id != ''):
next_node = node_dict[next_node_id]
... |
def to_sparse(hg, weight_nodes='const', weight_edges='log'):
winfo = hg.compute_weights(weight_nodes=weight_nodes, weight_edges=weight_edges)
hyperedge_indices = []
hyperedges = []
for e in winfo['edge_list']:
hyperedge_indices.append(len(hyperedges))
hyperedges.extend(hg.edges[e])
h... |
def GetArgs():
parser = argparse.ArgumentParser(description='The purpose of this script is to use a ctm and a vocab fileto extract sub-utterances and a sub-segmentation. Extracted sub-utterancesare all the strings of consecutive in-vocab words from the ctmsurrounded by an out-of-vocab word at each end if present.',... |
_grad()
def rescore_with_n_best_list(lats: k2.Fsa, G: k2.Fsa, num_paths: int) -> k2.Fsa:
device = lats.device
assert (len(lats.shape) == 3)
assert hasattr(lats, 'aux_labels')
assert hasattr(lats, 'lm_scores')
assert (G.shape == (1, None, None))
assert (G.device == device)
assert (hasattr(G, ... |
class MappingRule(object):
def matches(self, key):
raise NotImplementedError()
def apply(self, key, value):
raise NotImplementedError() |
class LRPolicy():
def __init__(self, lr, n_epochs, lr_policy='multi_step'):
self.lr_policy = lr_policy
self.params_dict = {}
self.n_epochs = n_epochs
self.base_lr = lr
self.lr = lr
def set_params(self, params_dict=None):
if (self.lr_policy == 'multi_step'):
... |
class AutoModelForImageClassification(_BaseAutoModelClass):
_model_mapping = MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING |
def vgg11_bn(pretrained=False, dataset_history=[], dataset2num_classes={}, **kwargs):
if pretrained:
kwargs['init_weights'] = False
model = VGG(make_layers(cfg['A'], batch_norm=True), dataset_history, dataset2num_classes, **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(mode... |
class CosineDistance(Layer):
def __init__(self, bigdl_type='float'):
super(CosineDistance, self).__init__(None, bigdl_type) |
def get_time_str(trycnt=0):
return ('2023-06-01-12-00-' + str(trycnt).zfill(2))
return time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime()) |
(derivate=True, coderize=True)
_loss
def balanced_l1_loss(pred, target, beta=1.0, alpha=0.5, gamma=1.5, reduction='mean'):
assert (beta > 0)
if (target.numel() == 0):
return (pred.sum() * 0)
assert (pred.size() == target.size())
diff = torch.abs((pred - target))
b = ((np.e ** (gamma / alpha)... |
def train(args, train_loader, num_train, model, criterion, optimizer):
model.train()
start_time = time.time()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
num_back = 0
device = args.device
create_graph = (args.opt == 'adahessian')
if args.cuda:
torch.cu... |
class LinearSumTrainer(Trainer):
def __init__(self, params):
super(LinearSumTrainer, self).__init__(params)
self.x_v = tensor.matrix('vgg_features', dtype='float32')
self.x_t = tensor.matrix('features', dtype='float32')
self.y = tensor.matrix('genres', dtype='int32')
model = ... |
_task('multilingual_translation')
class MultilingualTranslationTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='DIR', help='path to data directory')
parser.add_argument('--lang-pairs', default=None, metavar='PAIRS', help='comma-separated list of language pairs (in ... |
def hash_file(file_name):
sha1 = hashlib.sha1()
with open(file_name, 'rb') as f:
while True:
data = f.read(BUF_SIZE)
if (not data):
break
sha1.update(data)
return sha1.hexdigest() |
class VGG(nn.Module):
def __init__(self, features, num_classes=1000):
super(VGG, self).__init__()
self.features = features
self.classifier = nn.Linear(512, num_classes)
self._initialize_weights()
def forward(self, x):
x = self.features(x)
features = x.view(x.size(... |
def ReadFileSL(tthread, batchInterval, NUM_ITEMS, deposit_ratio, key_skewness, overlap_ratio, abort_ratio, isCyclic, complexity):
(w, h) = (3, 5)
y = [[0 for x in range(w)] for y in range(h)]
y_sum = [0 for x in range(w)]
inputEvents = (tthread * batchInterval)
if (isCyclic == 'true'):
f = g... |
def dcnn_nodelta(bands=60, frames=31, n_classes=10, channels=1, fully_connected=5000, filters=80, activation='relu'):
from keras.models import Sequential, Model
from keras.layers import Dense, Dropout, Activation, Input, Concatenate
import keras.layers
input_shape = (bands, frames, channels)
def hea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.