code stringlengths 101 5.91M |
|---|
_model
def efficientnet_b2a(pretrained=False, **kwargs):
return efficientnet_b2(pretrained=pretrained, **kwargs) |
class Embedding(nn.Module):
def __init__(self, feature_dim, embed_dim=256, type='ori'):
super(Embedding, self).__init__()
self.bn = nn.BatchNorm1d(embed_dim, affine=True)
self.relu = nn.ReLU(inplace=True)
self.dropout = nn.Dropout(p=0.5)
self.bottleneck = nn.Linear(feature_di... |
class BartTokenizerFast(PreTrainedTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
model_input_names = ['input_ids', 'attention_mask']
slow_tokenizer_class = BartTokenizer
... |
class GraphDerivations():
def __init__(self, graph, derivations):
p = Process.from_modgraph(graph)
self.graph = graphGMLString(graph.getGMLString(), str(p))
setImage(self.graph)
self.derivations = derivations |
def weight_variable_devonc(shape, stddev=0.1, name='weight_devonc'):
return tf.Variable(tf.truncated_normal(shape, stddev=stddev), name=name) |
def _setup_random_policy(cfg: DictConfig, env: Environment) -> RandomPolicy:
assert (cfg.agent == 'random')
if (cfg.env.name == 'bin_pack'):
assert isinstance(env.unwrapped, BinPack)
random_policy = networks.make_random_policy_bin_pack(bin_pack=env.unwrapped)
elif (cfg.env.name == 'snake'):
... |
class CanonicalHFIndex(HFIndexBase):
def __init__(self, vector_size: int, dataset_name: str='wiki_dpr', dataset_split: str='train', index_name: Optional[str]=None, index_path: Optional[str]=None, use_dummy_dataset=False):
if ((int((index_path is None)) + int((index_name is None))) != 1):
raise V... |
def build_arg_parser2():
usage_str = 'Smatch calculator -- arguments'
parser = optparse.OptionParser(usage=usage_str)
parser.add_option('-f', '--files', nargs=2, dest='f', type='string', help='Two files containing AMR pairs. AMRs in each file are separated by a single blank line. This option is required.')
... |
def raw_npy_reader(path):
with open(path, 'rb') as f:
bin_data = f.read()
try:
npy_data = np.load(six.BytesIO(bin_data))
except Exception as e:
print(path)
npy_data = None
print(e)
return (bin_data, npy_data) |
_model('s2t_transformer')
class S2TTransformerModel(FairseqEncoderDecoderModel):
def __init__(self, encoder, decoder):
super().__init__(encoder, decoder)
def add_args(parser):
parser.add_argument('--conv-kernel-sizes', type=str, metavar='N', help='kernel sizes of Conv1d subsampling layers')
... |
class BalancedPositiveNegativeSampler(object):
def __init__(self, batch_size_per_image, positive_fraction):
self.batch_size_per_image = batch_size_per_image
self.positive_fraction = positive_fraction
def __call__(self, matched_idxs):
pos_idx = []
neg_idx = []
for matched_... |
def parallel_apply(flows, inputs, kwargs_tup=None, devices=None, backward=False):
assert (len(flows) == len(inputs))
if (kwargs_tup is not None):
assert (len(flows) == len(kwargs_tup))
else:
kwargs_tup = (({},) * len(flows))
if (devices is not None):
assert (len(flows) == len(dev... |
class Bottleneck(nn.Module):
def __init__(self, in_chs, out_chs, stride=1, dilation=1, bottleneck_ratio=1, group_width=1, se_ratio=0.25, downsample=None, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d, aa_layer=None, drop_block=None, drop_path=None):
super(Bottleneck, self).__init__()
bottleneck_chs =... |
def get_data(files, opt):
rst = {'src': None, 'tgt': None, 'ans': None, 'feature': None, 'ans_feature': None}
for (k, v) in files.items():
if isinstance(v, list):
rst[k] = [load_file(f) for f in v]
else:
rst[k] = load_file(v)
return rst |
def get_dataset(opt: dict, data_dir, use_lcc: bool=False) -> InMemoryDataset:
ds = opt['dataset']
path = os.path.join(data_dir, ds)
if (ds in ['Cora', 'Citeseer', 'Pubmed']):
dataset = Planetoid(path, ds)
elif (ds in ['Computers', 'Photo']):
dataset = Amazon(path, ds)
elif (ds == 'Co... |
class BERT_CNN(nn.Module):
def __init__(self):
super(BERT_CNN, self).__init__()
self.bert = BertModel.from_pretrained('bert-base-uncased')
self.conv = nn.Conv2d(in_channels=13, out_channels=13, kernel_size=(3, 768), padding=True)
self.relu = nn.ReLU()
self.pool = nn.MaxPool2d... |
def apply_spectral_norm(m):
for layer in m.modules():
if isinstance(layer, nn.Conv2d):
spectral_norm(layer)
elif isinstance(layer, nn.Linear):
spectral_norm(layer)
elif isinstance(layer, nn.Embedding):
spectral_norm(layer) |
def ggml_compute_forward_mul_mat_q_fp32(src_0_ne, src_0_data, src_0_qtype, src_1_ne, src_1_data, result) -> None:
return _lib.ggml_compute_forward_mul_mat_q_fp32(src_0_ne, src_0_data, src_0_qtype, src_1_ne, src_1_data, result) |
def gdt(p1, p2, mask, cutoffs):
n = torch.sum(mask, dim=(- 1))
p1 = p1.float()
p2 = p2.float()
distances = torch.sqrt(torch.sum(((p1 - p2) ** 2), dim=(- 1)))
scores = []
for c in cutoffs:
score = (torch.sum(((distances <= c) * mask), dim=(- 1)) / n)
scores.append(score)
retur... |
class Net(nn.Module):
def __init__(self, alpha=1):
super(Net, self).__init__()
self.alpha = alpha
def forward(self, M, batch1, batch2):
return torch.baddbmm(M, batch1, batch2, alpha=self.alpha) |
def dfsCheck(dfsInput, gmlInput):
print('DFS:', dfsInput)
dfs = Rule.fromDFS(dfsInput)
gml = Rule.fromGMLString(('rule [ %s ]' % gmlInput))
if (dfs.isomorphism(gml) != 1):
print('DFS Input:', dfs)
print(('GML Input: rule [\n%s\n]' % gmlInput))
dfs.name = 'DFS'
gml.name = ... |
class SingleClassTpFpWithDifficultBoxesTest(tf.test.TestCase):
def setUp(self):
num_groundtruth_classes = 1
matching_iou_threshold = 0.5
nms_iou_threshold = 1.0
nms_max_output_boxes = 10000
self.eval = per_image_evaluation.PerImageEvaluation(num_groundtruth_classes, matching_... |
class ConvTranspose_synapse(SynapseModel):
def __init__(self, conn, **kwargs):
super(ConvTranspose_synapse, self).__init__(conn)
self._syn_operations.append([(conn.post_var_name + '[post]'), 'conv_trans2d', self.input_name, 'weight[link]', 'stride[link]', 'padding[link]', 'dilation[link]', 'groups[l... |
def train(net, optimizer, lr_scheduler, train_loader, train_sampler, metrics, begin_epoch, end_epoch, logger, rank=None, batch_end_callbacks=None, epoch_end_callbacks=None, writer=None, validation_monitor=None, fp16=False, clip_grad_norm=(- 1), gradient_accumulate_steps=1):
assert (isinstance(gradient_accumulate_st... |
class ExplainableBoostingRegressor(EBMModel, RegressorMixin, ExplainerMixin):
n_features_in_: int
term_names_: List[str]
bins_: List[Union[(List[Dict[(str, int)]], List[np.ndarray])]]
feature_names_in_: List[str]
feature_types_in_: List[str]
feature_bounds_: np.ndarray
term_features_: List[T... |
class E2E(E2ETransformer):
def add_arguments(parser):
E2ETransformer.add_arguments(parser)
E2E.add_conformer_arguments(parser)
return parser
def add_conformer_arguments(parser):
group = parser.add_argument_group('conformer model specific setting')
group = add_arguments_co... |
def _support_choice_with_dot_py(choice):
if choice.endswith('.py'):
return choice[:(- 3)]
return choice |
class ContinuousConv(tf.keras.layers.Layer):
def __init__(self, filters, kernel_size, activation=None, use_bias=True, kernel_initializer='uniform', bias_initializer='zeros', kernel_regularizer=None, bias_regularizer=None, align_corners=True, coordinate_mapping='ball_to_cube_radial', interpolation='linear', normaliz... |
class SummertimeScisummnet(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version('1.1.0')
BUILDER_CONFIGS = [datasets.BuilderConfig()]
def _info(self):
features = datasets.Features({'entry_number': datasets.Value('string'), 'document_xml': datasets.Value('string'), 'citing_sentences_annotated.... |
def test_parse_config_with_invalid_flag(mocker):
flag_values = flags.FlagValues()
mocker.patch('sys.argv', ['vmcnet', '--config.model.type=not_a_real_model'])
with pytest.raises(KeyError):
parse_flags(flag_values) |
def json_to_text(file_path, data):
if (not isinstance(file_path, Path)):
file_path = Path(file_path)
with open(str(file_path), 'w') as fw:
for line in data:
line = json.dumps(line, ensure_ascii=False)
fw.write((line + '\n')) |
def conv_dw(in_channels, out_channels, kernel_size=3, padding=1, stride=1, dilation=1):
return nn.Sequential(nn.Conv2d(in_channels, in_channels, kernel_size, stride, padding, dilation=dilation, groups=in_channels, bias=False), nn.BatchNorm2d(in_channels), nn.ReLU(inplace=True), nn.Conv2d(in_channels, out_channels, ... |
def get_parser(additional_commands=None):
commands = ['retrain', 'resume', 'eval', 'eval-init', 'slurm']
if additional_commands:
commands += additional_commands
parser = argparse.ArgumentParser()
parser.add_argument('--cmd', type=str, default='resume', choices=commands)
parser.add_argument('... |
def get_args_parser():
detection_parser = detection.get_args_parser()
parser = argparse.ArgumentParser('Get predictions for GQA and dump to file', parents=[detection_parser], add_help=False)
parser.add_argument('--split', type=str, default='testdev', choices=('testdev', 'test', 'challenge', 'submission'))
... |
class Polygon():
def __init__(self, vertices, width, height):
self.vertices = vertices
self.width = width
self.height = height
self.color = (generate_color(), generate_color(), generate_color())
self.alpha = generate_alpha()
self.coordinates = generate_polygon_coordin... |
def preresnet18_wd4(**kwargs):
return get_preresnet(blocks=18, width_scale=0.25, model_name='preresnet18_wd4', **kwargs) |
class Trainer(TrainerAbstract, TrainerLoss, TrainerIteration, TrainerDataset, TrainerModel):
def __init__(self, opt):
super(Trainer, self).__init__(opt)
self.dataset_train = None
self.opt.training_media_path = os.path.join(self.opt.dir_name, 'training_media')
if (not os.path.exists(s... |
class Meta(Component):
def __init__(self, source, pivots, dimension_names=None):
self.fields = locals()
del self.fields['self'] |
def main(args):
logging_dir = Path(args.output_dir, args.logging_dir)
accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, mixed_precision=args.mixed_precision, log_with=args.report_to, logging_dir=logging_dir)
if (args.train_text_encoder and (args.gradient_accumulation_st... |
class VarRNNBase(nn.Module):
def __init__(self, Cell, input_size, hidden_size, num_layers=1, bias=True, batch_first=False, dropout=(0, 0), bidirectional=False, **kwargs):
super(VarRNNBase, self).__init__()
self.Cell = Cell
self.input_size = input_size
self.hidden_size = hidden_size
... |
class SupCEResNet(nn.Module):
def __init__(self, name='resnet50', num_classes=10):
super(SupCEResNet, self).__init__()
(model_fun, dim_in) = model_dict[name]
self.encoder = model_fun()
self.fc = nn.Linear(dim_in, num_classes)
def forward(self, x):
return self.fc(self.enco... |
def make_hashable(x):
if isinstance(x, list):
return tuple(map(make_hashable, x))
if isinstance(x, dict):
return tuple(sorted(((k, make_hashable(v)) for (k, v) in x.items())))
return x |
def seasonality(time, period, amplitude=1, phase=0):
season_time = (((time + phase) % period) / period)
return (amplitude * seasonal_pattern(season_time)) |
def convert_bertabs_checkpoints(path_to_checkpoints, dump_path):
config = BertAbsConfig(temp_dir='.', finetune_bert=False, large=False, share_emb=True, use_bert_emb=False, encoder='bert', max_pos=512, enc_layers=6, enc_hidden_size=512, enc_heads=8, enc_ff_size=512, enc_dropout=0.2, dec_layers=6, dec_hidden_size=768... |
def compute_precision(guessed_sentences, correct_sentences):
assert (len(guessed_sentences) == len(correct_sentences))
correctCount = 0
count = 0
for sentenceIdx in range(len(guessed_sentences)):
guessed = guessed_sentences[sentenceIdx]
correct = correct_sentences[sentenceIdx]
as... |
class Node1(nn.Module):
def __init__(self, node1_cls):
super(Node1, self).__init__()
self.conv0 = nn.Sequential(nn.Conv2d(512, 512, kernel_size=3, padding=1, dilation=1, bias=False), BatchNorm2d(512), nn.ReLU(inplace=False))
self.conv1 = nn.Sequential(nn.Conv2d(512, 256, kernel_size=3, paddi... |
def get_fused_adam_class():
try:
global fused_adam_cuda
import importlib
fused_adam_cuda = importlib.import_module('fused_adam_cuda')
return FusedAdamV1
except ImportError:
try:
from apex.multi_tensor_apply import multi_tensor_applier
from apex.opt... |
class NSGAII(GeneticAlgorithm[(S, R)]):
def __init__(self, problem: Problem, population_size: int, offspring_population_size: int, mutation: Mutation, crossover: Crossover, selection: Selection=BinaryTournamentSelection(MultiComparator([FastNonDominatedRanking.get_comparator(), CrowdingDistance.get_comparator()])),... |
class DecoderBase(nn.Module):
def __init__(self, attentional=True):
super(DecoderBase, self).__init__()
self.attentional = attentional
def from_opt(cls, opt, embeddings):
raise NotImplementedError |
_module()
class ICNet(BaseModule):
def __init__(self, backbone_cfg, in_channels=3, layer_channels=(512, 2048), light_branch_middle_channels=32, psp_out_channels=512, out_channels=(64, 256, 256), pool_scales=(1, 2, 3, 6), conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), act_cfg=dict(type='ReLU'), align_c... |
def load_tinyimagenet_data(datadir):
xray_train_ds = ImageFolder_custom((datadir + '/train/'), transform=None)
xray_test_ds = ImageFolder_custom((datadir + '/val/'), transform=None)
(X_train, y_train) = (np.array([s[0] for s in xray_train_ds.samples]), np.array([int(s[1]) for s in xray_train_ds.samples]))
... |
def process_all_table_structure_annotations(input_annotation_list):
current_region_annotations = input_annotation_list
current_region_annotations = resolve_direct_nesting_of_rows_and_columns(current_region_annotations)
(_, _) = assign_numbers_to_rows_and_cols(current_region_annotations)
structured_annot... |
def get_backtrans_data_dict(pkl_path, train_path):
if (not pkl_path.exists()):
print(f'creating {pkl_path}')
(sentences, _) = common.get_sentences_and_labels_from_txt(train_path)
sentence_to_augmented_sentences = {}
for sentence in tqdm(sentences):
sentence_to_augmented_s... |
def sparse_mx_to_torch_sparse_tensor(sparse_mx):
sparse_mx = sparse_mx.tocoo()
indices = torch.from_numpy(np.vstack((sparse_mx.row, sparse_mx.col))).long()
values = torch.from_numpy(sparse_mx.data).float()
shape = torch.Size(sparse_mx.shape)
return torch.sparse.FloatTensor(indices, values, shape) |
class ObservationsDecoder(nn.Module):
def __init__(self, representation_size, out_size, width):
super().__init__()
self.layers = nn.Sequential(nn.Linear((representation_size * 2), width), nn.ELU(), nn.Linear(width, width), nn.ELU(), nn.Linear(width, out_size))
def forward(self, x, y):
in... |
class DebertaPreTrainedModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def stats(matrix):
mean = np.mean(matrix)
std = np.std(matrix)
maxv = np.amax(matrix)
minv = np.amin(matrix)
median = np.median(matrix)
output = np.array([mean, std, maxv, minv, median])
return output |
class SubnetResNet(nn.Module):
def __init__(self, block, num_blocks, taskcla, nf, sparsity):
super(SubnetResNet, self).__init__()
self.in_planes = nf
self.conv1 = subnet_conv3x3(3, (nf * 1), 1, sparsity=sparsity)
if True:
self.bn1 = nn.BatchNorm2d((nf * 1), track_running_... |
def render_header(image: np.ndarray, header: str, **kwargs):
requires_backends(render_header, 'vision')
image = to_pil_image(image)
header_image = render_text(header, **kwargs)
new_width = max(header_image.width, image.width)
new_height = int((image.height * (new_width / image.width)))
new_heade... |
class CorotatingRotationWrapperPotential(parentWrapperPotential):
def __init__(self, amp=1.0, pot=None, vpo=1.0, beta=0.0, to=0.0, pa=0.0, ro=None, vo=None):
vpo = conversion.parse_velocity(vpo, vo=self._vo)
to = conversion.parse_time(to, ro=self._ro, vo=self._vo)
pa = conversion.parse_angle... |
class MobileBertPreTrainedModel():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class HorovodWorker():
def ip_addr(self):
import ray
return ray._private.services.get_node_ip_address()
def set_gloo_iface(self):
ip_addr = self.ip_addr()
import psutil
import socket
iface_name = None
for (intf, intf_addresses) in psutil.net_if_addrs().ite... |
def test_class_member_mutation_does_not_affect_instance_members():
run_cell('\n class Foo:\n shared = 99\n def __init__(self):\n self.x = 42\n ')
run_cell('foo = Foo()')
run_cell('Foo.shared = 12')
run_cell('logging.info(foo.x)')
assert_not_detected... |
def get_batch(source, i, args, seq_len=None, evaluation=False):
seq_len = min((seq_len if seq_len else args.bptt), ((len(source) - 1) - i))
data = source[i:(i + seq_len)]
target = source[(i + 1):((i + 1) + seq_len)].view((- 1))
return (data, target) |
def get_score_from_pos(pos_score_dict, prefix_len, hypo_dict, bpe_symbol, hypo_frac, backwards):
score_dict = {}
num_bpe_tokens_dict = {}
assert ((prefix_len is None) or (hypo_frac is None))
for key in pos_score_dict:
score_dict[key] = []
num_bpe_tokens_dict[key] = []
for i in ra... |
def differentiable_round(z, training=True):
if training:
z_rounded = tf.round(z)
return roundNoGradient((z_rounded + ((z - z_rounded) ** 3)))
else:
return tf.round(z) |
def convert_pytorch(nlp: Pipeline, opset: int, output: Path, use_external_format: bool):
if (not is_torch_available()):
raise Exception('Cannot convert because PyTorch is not installed. Please install torch first.')
import torch
from torch.onnx import export
print(f'Using framework PyTorch: {tor... |
def process_all():
build_new_table(config['path']['ATOMIC_Chinese'])
head = pd.read_csv(config['path']['head_phrase'])
trg = set(head['head_translated'])
extract = Extract()
data = json.load(open(config['path']['Cconv_matched'], 'r', encoding='utf8'))
content = []
for dialog in data['data']:... |
_tokenizers
class PreTrainedTokenizationFastTest(TokenizerTesterMixin, unittest.TestCase):
rust_tokenizer_class = PreTrainedTokenizerFast
test_slow_tokenizer = False
test_rust_tokenizer = True
from_pretrained_vocab_key = 'tokenizer_file'
def setUp(self):
self.test_rust_tokenizer = False
... |
_module()
class CrossKDSingleStageDetector(SingleStageDetector):
def __init__(self, backbone: ConfigType, neck: ConfigType, bbox_head: ConfigType, teacher_config: Union[(ConfigType, str, Path)], teacher_ckpt: Optional[str]=None, kd_cfg: OptConfigType=None, train_cfg: OptConfigType=None, test_cfg: OptConfigType=None... |
def load_or_encode_corpus(model_args: ModelArguments, data_args: DataArguments, eval_args: EvalArguments):
out_index_path = os.path.join(data_args.out_corpus_dir, 'index')
out_corpus_ids_path = os.path.join(data_args.out_corpus_dir, 'corpus_ids.npy')
if (os.path.exists(out_index_path) and os.path.exists(out... |
def test_caller(path, step_ind, on_val):
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '0'
config = Config()
config.load(path)
import pdb
pdb.set_trace()
config.first_subsampling_dl = 0.05
config.dataset = 'ETH'
config.KP_extent = 2
print()
print('Dataset Preparation')
print('')
d... |
class FCBlockVGG(nn.Module):
def __init__(self, input_dim, hidden_dims, output_dim=10):
super(FCBlockVGG, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dims[0])
self.fc2 = nn.Linear(hidden_dims[0], hidden_dims[1])
self.fc3 = nn.Linear(hidden_dims[1], output_dim)
def for... |
def test_digits_greedi_ln_sparse():
model1 = FeatureBasedSelection(100, 'sqrt')
model2 = FeatureBasedSelection(100, 'log')
model = MixtureSelection(100, [model1, model2], [1.0, 0.3], optimizer='greedi', optimizer_kwds={'optimizer1': 'lazy', 'optimizer2': 'naive'}, random_state=0)
model.fit(X_digits_spar... |
def t5_tokenize(texts: List[str], name=DEFAULT_T5_NAME):
(t5, tokenizer) = get_model_and_tokenizer(name)
if torch.cuda.is_available():
t5 = t5.cuda()
device = next(t5.parameters()).device
encoded = tokenizer.batch_encode_plus(texts, return_tensors='pt', padding='longest', max_length=MAX_LENGTH, ... |
def assert_allclose(actual: Dict[(str, np.ndarray)], desired: Dict[(str, np.ndarray)], actual_name: str, oracle_name: str, equal_nan=False, rtol=0.01, atol=0.001):
akeys = set(actual.keys())
dkeys = set(desired.keys())
if (akeys != dkeys):
raise KeyError(f'{actual_name}: {akeys} != {oracle_name}: {d... |
class ShuffleNetV2(Backbone):
def __init__(self, stages_repeats, stages_out_channels, **kwargs):
super().__init__()
if (len(stages_repeats) != 3):
raise ValueError('expected stages_repeats as list of 3 positive ints')
if (len(stages_out_channels) != 5):
raise ValueErr... |
def _load_pretrain_emb(data_loader, en_batch_dev=None, en_batch_test=None):
if ((args.embedding_source == 'elmo_1') or (args.embedding_source == 'elmo_2') or (args.embedding_source == 'elmo_0')):
ext_dim = 1024
args.embedding_dim = ext_dim
args.hidden_dim = ((ext_dim + args.tag_dim) // 2)
... |
class ImageNet100(ImageFolder):
def __init__(self, root, train=True, transform=None, target_transform=None, download=False):
self.parent_dir = root
if download:
self.download()
if (not self._check_exists()):
raise FileNotFoundError('Dataset does not exist.')
d... |
class WarmupMultiStepSchedule(LambdaLR):
def __init__(self, optimizer, warmup_steps, decay_steps, decay_ratio=0.1, last_epoch=(- 1)):
self.warmup_steps = warmup_steps
self.decay_steps = decay_steps
self.decay_ratio = decay_ratio
super(WarmupMultiStepSchedule, self).__init__(optimizer... |
def test_digits_cosine_two_stage_object():
model = SumRedundancySelection(100, 'cosine', optimizer=TwoStageGreedy())
model.fit(X_digits)
assert_array_equal(model.ranking, digits_cosine_ranking)
assert_array_almost_equal(model.gains, digits_cosine_gains, 4)
assert_array_almost_equal(model.subset, X_d... |
_end_docstrings(PIPELINE_INIT_ARGS)
class AudioClassificationPipeline(Pipeline):
def __init__(self, *args, **kwargs):
kwargs['top_k'] = 5
super().__init__(*args, **kwargs)
if (self.framework != 'pt'):
raise ValueError(f'The {self.__class__} is only available in PyTorch.')
... |
def read_in_articles(article_ids=None):
anno_df = pd.read_csv(anno_csv_path)
unique_article_ids = anno_df[STUDY_ID_COL].unique()
articles = []
for article_id in unique_article_ids:
if ((article_ids is None) or (article_id in article_ids)):
articles.append(get_article(article_id))
... |
class SummarizationModule(BaseTransformer):
mode = 'summarization'
loss_names = ['loss']
metric_names = ROUGE_KEYS
default_val_metric = 'rouge2'
def __init__(self, hparams, **kwargs):
if (hparams.sortish_sampler and (hparams.gpus > 1)):
hparams.replace_sampler_ddp = False
... |
class ChainExample(torch.utils.data.Dataset):
def __init__(self, egs_file, output_file=None):
if (output_file and egs_file.startswith('scp:')):
raise ValueError('need egs_file to start to be of type scp when using output_file')
self.egs_file = egs_file
egs_list = [ln.strip().spli... |
def translate_opts(parser):
group = parser.add_argument_group('Model')
group.add('--model', '-model', dest='models', metavar='MODEL', nargs='+', type=str, default=[], required=True, help='Path to model .pt file(s). Multiple models can be specified, for ensemble decoding.')
group.add('--fp32', '-fp32', actio... |
class Explanation(S):
def _init_explanation(cls, instance, *args):
super(Explanation, instance).__init__()
instance.components = {}
instance._field_components_map = {}
for value in args:
if (value is not None):
instance.append(value)
def __init__(self,... |
class CNN(aicnn.CNN):
def __init__(model, input_shape, nb_classes, n_dense=128, p_dropout=0.5, BN_flag=False, PretrainedModel=VGG16):
model.in_shape = input_shape
model.n_dense = n_dense
model.p_dropout = p_dropout
model.PretrainedModel = PretrainedModel
model.BN_flag = BN_fl... |
class MLPMixer(nn.Module):
def __init__(self, num_classes: int, image_size: int=256, channels: int=3, patch_size: int=32, num_layers: int=8, hidden_dim: int=512, tokens_hidden_dim: int=256, channels_hidden_dim: int=2048):
super().__init__()
num_patches = ((image_size // patch_size) ** 2)
sel... |
def setup(app):
app.add_config_value('recommonmark_config', {'url_resolver': (lambda url: (github_doc_root + url)), 'auto_toc_tree_section': 'Contents'}, True)
app.add_transform(AutoStructify) |
class TestFeatureCommon(ZooTestCase):
def setup_method(self, method):
sparkConf = init_spark_conf().setMaster('local[4]').setAppName('test feature set')
self.sc = init_nncontext(sparkConf)
def test_BigDL_adapter(self):
new_preprocessing = BigDLAdapter(Resize(1, 1))
assert isinsta... |
def heuristic_target_entropy(action_space):
heuristic_target_entropy = (- np.prod(action_space.shape))
return heuristic_target_entropy |
def get_images(fire, size=[128, 128]):
transform = transforms.Compose([transforms.Resize((size[0], size[1]))])
normalize = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
img = Image.open(fire).convert('RGB')
img = transform(img)
img = normalize(im... |
_registry(calib_method='percentile')
class PercentileCalibrator(CalibratorBase):
def __init__(self, num_bins=2048, percentile=99.999):
super(PercentileCalibrator, self).__init__()
self.collector = None
self.num_bins = num_bins
self.percentile = percentile
def collect_calib_data(s... |
class Appr(object):
def __init__(self, model, args, lr_min=0.0001, lr_factor=3, lr_patience=5, clipgrad=1000, lamb=0.01):
self.model = model
self.model_old = None
self.fisher = None
self.nepochs = args.nepochs
self.sbatch = args.sbatch
self.lr = args.lr
self.l... |
def get_user_topics(user_id):
conn = getDb()
with closing(conn.cursor(dictionary=True)) as cur:
sql = 'SELECT tr.topic_id, t.topic\n FROM topic_recommendations tr INNER JOIN topics t\n ON t.topic_id = tr.topic_id \n LEFT JOIN user_topics ut \n ... |
def create_solver(outfname, net_name, max_iter=10000, lr=0.0001, weight_decay=0.0005, snapshot_dir='snapshots', optimizer='Adam', solver_mode='GPU'):
txt = open('templates/solver.txt', 'r').read()
txt = txt.replace('_NET_NAME_', net_name)
txt = txt.replace('_MAX_ITER_', str(max_iter))
txt = txt.replace(... |
class InducingImages(inducing_variables.InducingVariables):
def __init__(self, images: TensorData, name: Optional[str]=None):
super().__init__(name=name)
self._images = Parameter(images, dtype=default_float())
def __len__(self) -> int:
return self._images.shape[0]
def Z(self) -> tf.T... |
_model
def efficientnet_cc_b0_4e(pretrained=False, **kwargs):
model = _gen_efficientnet_condconv('efficientnet_cc_b0_4e', channel_multiplier=1.0, depth_multiplier=1.0, pretrained=pretrained, **kwargs)
return model |
class NRDataSHMArrayReader(object):
def __init__(self, shm_info: NRDataSHMInfo):
self.total_image_num = shm_info.total_image_num
self.num_image_per_split = shm_info.num_image_per_split
self.camera = shm_info.camera
(H, W) = (self.camera.H, self.camera.W)
self.imgs = SHMArray(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.