code stringlengths 101 5.91M |
|---|
def add_change_in_new_deaths(df, target_days):
deaths_cols = df.filter(regex='#Deaths_').columns
latest_date_str = deaths_cols[(- 1)].replace('#Deaths_', '')
latest_date = datetime.strptime(latest_date_str, '%m-%d-%Y').date()
time_deltas = [timedelta(days=int(day)) for day in target_days]
plot_dates... |
class CloseGripperOption(AbstractOption):
def __init__(self, position=None, **kwargs):
super(CloseGripperOption, self).__init__(name='close_gripper')
self.position = position
def makePolicy(self, world):
return (CloseGripperPolicy(pos=self.position), TimeCondition((world.time() + 0.8)))
... |
def get_metrics(p_seq1, p_seq2, o_seq1, o_seq2):
psim = pitch_similarity(p_seq1, p_seq2)
osim = onset_similarity(o_seq1, o_seq2)
pc = cross_correlation(p_seq1, p_seq2)
oc = cross_correlation(o_seq1, o_seq2)
return (psim, osim, pc, oc) |
class BaselineDataset(Dataset):
def __init__(self, dataset=None, baseline=None):
super(BaselineDataset, self).__init__()
self.dataset = dataset
self.baseline = baseline
assert (len(self.dataset) == len(self.baseline))
def __getitem__(self, item):
return {'data': self.data... |
def gumbel_softmax_sample(logits, tau=1, eps=1e-10, dim=(- 1)):
gumbel_noise = sample_gumbel(logits.size(), eps=eps)
if logits.is_cuda:
gumbel_noise = gumbel_noise.cuda()
y = (logits + Variable(gumbel_noise))
return F.softmax((y / tau), dim=dim) |
class DFA(nn.Module):
def __init__(self, features, M=2, r=1, L=32):
super(DFA, self).__init__()
self.M = M
self.features = features
d = max(int((self.features / r)), L)
self.fc = nn.Sequential(nn.Conv1d(self.features, d, kernel_size=1), nn.BatchNorm1d(d))
self.fc_out ... |
def tarfile_to_samples_nothrow(src, handler=wds.warn_and_continue):
streams = url_opener(src, handler=handler)
files = tar_file_expander(streams, handler=handler)
samples = group_by_keys_nothrow(files, handler=handler)
return samples |
class FALoss(torch.nn.Module):
def __init__(self, subscale=0.0625):
super(FALoss, self).__init__()
self.subscale = int((1 / subscale))
def forward(self, feature1, feature2):
feature1 = torch.nn.AvgPool2d(self.subscale)(feature1)
feature2 = torch.nn.AvgPool2d(self.subscale)(featur... |
def get_random_digit_image():
indx = randint(0, (len(images) - 1))
img = images[indx][0]
return img |
def main(opt=None, inputs=None, isEvaluate=False):
if (not opt):
parser = argparse.ArgumentParser()
parser.add_argument('--bert_model', default=None, type=str, required=True, help='Bert pre-trained model selected in the list: bert-base-uncased, bert-large-uncased, bert-base-cased, bert-base-multilin... |
def dict_gather(comm, d, op='mean', assert_all_have_data=True):
if (comm is None):
return d
alldicts = comm.allgather(d)
size = comm.size
k2li = defaultdict(list)
for d in alldicts:
for (k, v) in d.items():
k2li[k].append(v)
result = {}
for (k, li) in k2li.items()... |
class FrameLevel(nn.Module):
def __init__(self, input_dim, output_dim, hiddens=None, activation='ReLU', **kwargs):
super().__init__()
latest_dim = input_dim
self.hiddens = []
if (hiddens is not None):
for dim in hiddens:
self.hiddens += [nn.Linear(latest_d... |
class CachedAttribute(object):
def __init__(self, method, name=None):
self.method = method
self.name = (name or method.__name__)
def __get__(self, obj, objtype):
if (obj is None):
return self
elif (self.name in obj.__dict__):
return obj.__dict__[self.name]... |
class Statistics(object):
def __init__(self, loss=0, n_words=0, n_correct=0):
self.loss = loss
self.n_words = n_words
self.n_correct = n_correct
self.n_src_words = 0
self.start_time = time.time()
def all_gather_stats(stat, max_size=4096):
stats = Statistics.all_ga... |
def test_add_batch_all_new(data):
add_info = data.archive.add(solution=([[1, 2, 3]] * 4), objective=[0, 0, 0, 1], measures=[[0, 0], [0.25, 0.25], [0.5, 0.5], [0.5, 0.5]])
assert (add_info['status'] == 2).all()
assert np.isclose(add_info['value'], [0, 0, 0, 1]).all()
assert_archive_elites(archive=data.ar... |
class BoundTransform(Transformation):
def __init__(self, x_bound, y_bound):
super().__init__(BoundedScaler(x_bound), BoundedScaler(y_bound)) |
def get_labels(path):
with open(path, 'r') as f:
labels = f.read().splitlines()
if ('O' not in labels):
labels = (['O'] + labels)
return labels |
class DenseNet(nn.Module):
def __init__(self, growth_rate=8, block_config=(6, 12, 24, 16), num_init_features=16, bn_size=4, drop_rate=0, pretrained=False):
super(DenseNet, self).__init__()
self.start_features = nn.Sequential(OrderedDict([('conv0', nn.Conv2d(3, num_init_features, kernel_size=7, strid... |
def vis(model, loader, save_dir, rank=None, world_size=1):
attention_dir = os.path.join(save_dir, 'attention_probs')
hidden_dir = os.path.join(save_dir, 'hidden_states')
cos_dir = os.path.join(save_dir, 'cos_similarity')
if (not os.path.exists(attention_dir)):
makedirsExist(attention_dir)
mo... |
class Storage(_IOMixin, metaclass=ABCMeta):
def __init__(self) -> None:
super().__init__()
self._storage = defaultdict(HistoricalContainer)
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def put(self, name: str, value: Dict[(str, floa... |
class dAUTOMAP(nn.Module):
def __init__(self, input_shape, output_shape, tfx_params, tfx_params2=None):
super(dAUTOMAP, self).__init__()
self.input_shape = input_shape
self.output_shape = output_shape
if (tfx_params2 is None):
tfx_params2 = tfx_params
self.domain_... |
def run_retraining(args: Any, test_only: bool=False, distributed: bool=False, batch_size: int=32, lr: float=0.01, train_epochs: int=20) -> tuple[(Any, int, int, int)]:
(model_name, model, state_dict, data_loader_train, data_loader_val, args_checkpoint, halut_modules, checkpoint) = load_model(args.checkpoint, distri... |
def _xgboost_min_child_weight(name):
return scope.int(hp.loguniform(name, np.log(1), np.log(100))) |
class TemperatureLogitsWarper():
def __init__(self, *args, **kwargs):
requires_pytorch(self) |
class GridAnchorGeneratorTest(tf.test.TestCase):
def test_construct_single_anchor(self):
scales = [0.5, 1.0, 2.0]
aspect_ratios = [0.25, 1.0, 4.0]
anchor_offset = [7, (- 3)]
exp_anchor_corners = [[(- 121), (- 35), 135, 29], [(- 249), (- 67), 263, 61], [(- 505), (- 131), 519, 125], [(... |
def main():
result_file = os.path.join(settings.RESULT, 'result.csv')
if (not os.path.exists(result_file)):
raise ValueError(f"Need a result file for analysis, couldn't find {result_file}")
result = pd.read_csv(result_file)
result.sort_values('neuron', inplace=True)
(model, dataset) = data.s... |
class OpenOutputDirOperator(Operator):
bl_idname = 'scene.zpy_open_output_dir'
bl_label = 'Open Output Dir'
bl_description = 'Open file browser at output dir.'
bl_category = 'ZPY'
bl_options = {'REGISTER'}
def execute(self, context):
zpy.files.open_folder_in_explorer(context.scene.zpy_ou... |
def make_rl_data_module(tokenizer: transformers.PreTrainedTokenizer, data_args, training_args):
prompt_dict = utils.jload(data_args.prompt_dict_path)
alpaca_instructions = datasets.load_dataset(data_args.dataset_path, data_args.dataset_name)
train_df = pd.concat([pd.DataFrame(alpaca_instructions[split]) for... |
def convbnrelu_bloc(input_dim, output_dim):
return nn.Sequential(nn.Conv2d(in_channels=input_dim, out_channels=output_dim, kernel_size=3, stride=1, padding=0, bias=False), nn.BatchNorm2d(output_dim), nn.ReLU(inplace=True)) |
class CacheNow(Cache):
def fetch_func(self):
def _to_json_doc(data, current_case_count_risklayer):
log.info('%s: serialize data to JSON', self)
t_consulted_ger_tz_iso8601 = datetime.fromtimestamp(int(data['t_obtained_from_source']), tz=pytz.timezone('Europe/Amsterdam')).isoformat()
... |
def nnp_freq(importtext):
text = word_tokenize(importtext)
tokens = nltk.pos_tag(text)
c = Counter((token for (word, token) in tokens))
return (c['NNP'] / len(text)) |
def make_bert_ner_model_fn(optimizer):
import tensorflow as tf
from bigdl.orca.tfpark import ZooOptimizer
def _bert_ner_model_fn(features, labels, mode, params):
output_layer = bert_model(features, labels, mode, params).get_sequence_output()
if (mode == tf.estimator.ModeKeys.TRAIN):
... |
def fetch_test_set(test_set_url):
import wget
fname = wget.download(test_set_url, 'opus_test.txt')
lns = Path(fname).open().readlines()
src = lmap(str.strip, lns[::4])
gold = lmap(str.strip, lns[1::4])
mar_model = lmap(str.strip, lns[2::4])
if (not (len(gold) == len(mar_model) == len(src))):... |
class AdjustLayer(nn.Module):
def __init__(self, in_channels, out_channels):
super(AdjustLayer, self).__init__()
self.downsample = nn.Sequential(nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels))
def forward(self, x):
x = self.downsample(x)
... |
def ignore_background_loss(y_true, y_pred):
dont_cares = K.minimum(1.0, y_true)
return (K.sum((K.abs((y_pred - y_true)) * dont_cares)) / K.sum(dont_cares)) |
def main(args):
if (args.seed is None):
colossalai.launch_from_torch(config={})
else:
colossalai.launch_from_torch(config={}, seed=args.seed)
local_rank = gpc.get_local_rank(ParallelMode.DATA)
world_size = gpc.get_world_size(ParallelMode.DATA)
if args.with_prior_preservation:
... |
class PSPnet(nn.Module):
def __init__(self, out_channels=256):
super(PSPnet, self).__init__()
self.layer6_0 = nn.Sequential(nn.Conv2d(out_channels, out_channels, kernel_size=1, stride=1, padding=0, bias=True), nn.ReLU(), nn.Dropout2d(p=0.5))
self.layer6_1 = nn.Sequential(nn.Conv2d(out_channe... |
def plot_causal_matrix_in_training(time_coef, name, log, log_step, threshold=0.5, plot_each_time=False):
if (time_coef is None):
return
if ((np.max(time_coef) - np.min(time_coef)) > 0.01):
time_coef = ((time_coef - np.min(time_coef)) / (np.max(time_coef) - np.min(time_coef)))
(n, m, t) = tim... |
class Vgg19(torch.nn.Module):
def __init__(self, model_path: str=None, requires_grad: bool=False):
super(Vgg19, self).__init__()
if (model_path is None):
vgg_pretrained_features = models.vgg19(pretrained=True).features
else:
model = vgg19(pretrained=False)
... |
class JobLauncher(object):
JOB_CONFIG = {'local': LocalJob}
def __init__(self, yaml_file):
self.yaml_file = yaml_file
job_key = 'local'
if yaml_file.endswith('.yaml'):
config = recursive_config(yaml_file)
if (config.task_type is not None):
job_key ... |
def JSD(P, Q):
_P = (P / np.linalg.norm(P, ord=1))
_Q = (Q / np.linalg.norm(Q, ord=1))
_M = (0.5 * (_P + _Q))
return (0.5 * (entropy(_P, _M) + entropy(_Q, _M))) |
class TestSetAllParamValues():
def test_set_all_param_values(self):
from lasagne.layers import InputLayer, DenseLayer, set_all_param_values
from lasagne.utils import floatX
l1 = InputLayer((10, 20))
l2 = DenseLayer(l1, 30)
l3 = DenseLayer(l2, 40)
a2 = floatX(numpy.ran... |
def test_openimages_dataset():
tmp_dir = tempfile.TemporaryDirectory()
label_file = osp.join(tmp_dir.name, 'label_file.csv')
ann_file = osp.join(tmp_dir.name, 'ann_file.csv')
label_level_file = osp.join(tmp_dir.name, 'label_level_file.csv')
_create_oid_style_ann(label_file, ann_file, label_level_fil... |
class MyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.integer):
return int(obj)
elif isinstance(obj, np.uint8):
return int(obj)
elif isinstance(obj, np.floating):
return float(obj)
elif isinstance(obj, np.ndarray):
... |
def get_callbacks(args):
monitor_mode = ('min' if ('loss' in args.logger.monitor) else 'max')
checkpoint_naming = '{epoch}-{step}-{valid_loss:.4f}'
if (args.logger.monitor != 'valid_loss'):
checkpoint_naming += (('-{' + args.logger.monitor) + ':.4f}')
checkpoint_callback = ModelCheckpoint(filena... |
class GAT(nn.Module):
def __init__(self, num_layers, in_dim, num_hidden, num_classes, heads, activation, feat_drop=0, attn_drop=0, negative_slope=0.2, residual=False):
super(GAT, self).__init__()
self.num_layers = num_layers
self.gat_layers = nn.ModuleList()
self.activation = activat... |
def tst_keras():
from tensorflow import __version__
from tensorflow.compat.v1 import reset_default_graph
from classification_models_3D.tfkeras import Classifiers
print('Tensorflow version: {}'.format(__version__))
if 1:
type = 'densenet121'
print('Go for {}'.format(type))
(mo... |
def log_board_file(fpath, args, metrics: dict):
rt_list = []
if args.dbg:
return
time = datetime.datetime.now()
rt_list.append('Time: {}'.format(time))
rt_list.append('Data Name')
rt_list.append(args.data_name)
rt_list.append('Compression')
rt_list.append(args.compression)
rt... |
def gen_required_sigs(project_name: str, class_name: str, methods_list: list):
full_text = ''
class_row = db.select(table_name='class', conditions={'project_name': project_name, 'class_name': class_name}, result_cols=['signature', 'fields', 'has_constructor'])
if (not class_row):
raise RuntimeError(... |
_config(framework_name=FRAMEWORK_NAME, algo_name=STATIC_QUANT)
class StaticQuantConfig(BaseConfig):
supported_configs: List[OperatorConfig] = []
params_list = ['weight_dtype', 'weight_sym', 'weight_granularity', 'act_dtype', 'act_sym', 'act_granularity']
name = STATIC_QUANT
def __init__(self, weight_dty... |
def make_res_layer(block, inplanes, planes, blocks, stride=1, dilation=1, style='pytorch', with_cp=False, conv_cfg=None, norm_cfg=dict(type='BN'), dcn=None, gcb=None, sac=None, rfp=None, gen_attention=None, gen_attention_blocks=[]):
downsample = None
if ((stride != 1) or (inplanes != (planes * block.expansion))... |
def main():
args = parse_args()
send_example_telemetry('run_swag_no_trainer', args)
accelerator_log_kwargs = {}
if args.with_tracking:
accelerator_log_kwargs['log_with'] = args.report_to
accelerator_log_kwargs['logging_dir'] = args.output_dir
accelerator = Accelerator(gradient_accumu... |
def load_parameters():
FIXED_PARAMETERS = {'model_type': args.model_type, 'model_name': args.model_name, 'training_mnli': '{}/multinli_0.9/multinli_0.9_train.jsonl'.format(args.datapath), 'dev_matched': '{}/multinli_0.9/multinli_0.9_dev_matched.jsonl'.format(args.datapath), 'dev_mismatched': '{}/multinli_0.9/multin... |
def test_same_as_metrics_mse_implementation():
actual = (np.random.random(size=(5, 5, 8)) * 255)
assert (np.min(actual) >= 0)
assert (np.max(actual) <= 255)
expected = (np.random.random(size=(5, 5, 8)) * 255)
assert (np.min(expected) >= 0)
assert (np.max(expected) <= 255)
mask = np.random.ra... |
class RoIAwarePool3d(nn.Module):
def __init__(self, out_size, max_pts_each_voxel=128):
super().__init__()
self.out_size = out_size
self.max_pts_each_voxel = max_pts_each_voxel
def forward(self, rois, pts, pts_feature, pool_method='max'):
assert (pool_method in ['max', 'avg'])
... |
class RandomHorizontallyFlip(object):
def __call__(self, img, mask):
if (random.random() < 0.5):
return (img.transpose(Image.FLIP_LEFT_RIGHT), mask.transpose(Image.FLIP_LEFT_RIGHT))
return (img, mask) |
class W2lDecoder(object):
def __init__(self, args, tgt_dict):
self.tgt_dict = tgt_dict
self.vocab_size = len(tgt_dict)
self.nbest = args.nbest
self.criterion_type = CriterionType.CTC
self.blank = (tgt_dict.index('<ctc_blank>') if ('<ctc_blank>' in tgt_dict.indices) else tgt_d... |
def prepare_corpus_vocabs(args):
(language, data_set, data_type) = args
print(f'Building vocabulary for {language} {data_type}')
if utils.check_vocab(language, data_type):
return
docs = utils.load_doc(language, data_set)
tokens = utils.flatten((doc[data_type] for doc in docs))
tokens = u... |
def compute_pixel_coverage(instance_seg, object_id):
cand_mask = (instance_seg == object_id)
score = (cand_mask.sum().astype(np.float64) / cand_mask.size)
return score |
def demo_to_midi(data, names, bpm=90.0, shift_second=None, shift_beat=None):
alpha = bpm_to_alpha(bpm)
if (shift_second is None):
shift_second = (alpha * shift_beat)
midi = pretty_midi.PrettyMIDI(initial_tempo=bpm)
for (track, name) in zip(data, names):
ins = pretty_midi.Instrument(0, na... |
def logging_csv(file, header):
i = 1
fname = file
while os.path.isfile(fname):
fname = (file + str(i))
i += 1
with open(fname, 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(header)
def write_csv(s):
with open(fname, 'a', newline='') as f:
... |
def convert_PubLayNet_blob_to_target_blob(PubLayNet_blob, lookup_table):
PubLayNet_shape = PubLayNet_blob.shape
leading_factor = int((PubLayNet_shape[0] / NUM_PUBLAYNET_CLS))
tail_shape = list(PubLayNet_shape[1:])
assert ((leading_factor == 1) or (leading_factor == 4))
PubLayNet_blob = PubLayNet_blo... |
def image_transform(image_size: Union[(int, List[int])], augmentation: dict, mean: List[float]=[0.485, 0.456, 0.406], std: List[float]=[0.229, 0.224, 0.225]) -> Callable:
if isinstance(image_size, int):
image_size = (image_size, image_size)
else:
image_size = tuple(image_size)
horizontal_fli... |
def get_spatial_graph(num_node, self_link, inward, outward):
I = edge2mat(self_link, num_node)
In = normalize_digraph(edge2mat(inward, num_node))
Out = normalize_digraph(edge2mat(outward, num_node))
A = np.stack((I, In, Out))
return A |
def get_vgg2l_odim(idim, in_channel=3, out_channel=128):
idim = (idim / in_channel)
idim = np.ceil((np.array(idim, dtype=np.float32) / 2))
idim = np.ceil((np.array(idim, dtype=np.float32) / 2))
return (int(idim) * out_channel) |
def get_default_cfg():
_C = CN()
_C.VERSION = 2
_C.DATA_DIR = './data/waymo/processed/validation/'
_C.DATASET = 'waymo'
_C.OUTPUT_DIR = './output/debug'
_C.OBJECT_LIST_PATH = './data/waymo/splits/easy_list.json'
_C.CKPT_PATH = '/root/code/shape-reconstruction/experiments/point_sdf/partial_po... |
class TestLanguageModeling(unittest.TestCase):
def setUp(self):
logging.disable(logging.CRITICAL)
def tearDown(self):
logging.disable(logging.NOTSET)
def test_fconv_lm(self):
with contextlib.redirect_stdout(StringIO()):
with tempfile.TemporaryDirectory('test_fconv_lm') as... |
class AutoEncoder(nn.Module):
def __init__(self, d, encoded_size):
super(AutoEncoder, self).__init__()
self.encoded_size = encoded_size
self.data_size = len(d.encoded_feature_names)
self.encoded_categorical_feature_indexes = d.get_data_params()[2]
self.encoded_continuous_feat... |
def get_detector(name, **kwargs):
if ('convs' == name):
return Conv3x3ReLUBNs(kwargs['in_channels'], kwargs['inner_channels'], kwargs['out_channels'], kwargs['scale'], kwargs['num_convs'], kwargs.get('drop_rate', 0.0))
raise ValueError(f'{name} is not supported.') |
def init_logger(log_folder, file_name='output.log'):
if os.path.exists(log_folder):
print(('WARNING: The results directory (%s) already exists. Delete previous results directory [y/N]? ' % log_folder), end='')
var = input()
if ((var is 'y') or (var is 'Y')):
print('removing direc... |
class BaseImageDataset(BaseDataset):
def print_dataset_statistics(self, train, query, gallery):
(num_train_pids, num_train_imgs, num_train_cams, num_train_views) = self.get_imagedata_info(train)
(num_query_pids, num_query_imgs, num_query_cams, num_train_views) = self.get_imagedata_info(query)
... |
_config
def model_resnet_cifar():
cfg = {'learner': {'model': 'ResnetiCifar44'}, 'training': {'resume_from_checkpoint_path': '/mnt/models/resnet44-nolinear-cifar.pth', 'resume_training': True}} |
class FCBlock(nn.Module):
def __init__(self, input_dim, hidden_dims, output_dim=10):
super(FCBlock, 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 forward(s... |
def build_backbone(args):
position_embedding = build_position_encoding(args)
train_backbone = (args.lr_backbone > 0)
return_interm_layers = (args.num_feature_levels > 1)
backbone = Backbone(args.backbone, train_backbone, return_interm_layers, args)
model = Joiner(backbone, position_embedding)
re... |
def gen_filename(filename, dataset='esc50'):
if (dataset == 'fma'):
dataset = 'fma_mp3'
ext = filename.split('.')[(- 1)]
filename = (((('/data/sls/scratch/yuangong/audiollm/src/data/prep_data_ltue/whisper_feat/' + str(dataset)) + '/whisper_large-v1/') + filename.split('/')[(- 1)][:((- len(ext)) - 1)... |
class Binarizer():
def binarize(filename, dict, consumer, tokenize=tokenize_line, append_eos=True, reverse_order=False, offset=0, end=(- 1), already_numberized=False):
(nseq, ntok) = (0, 0)
replaced = Counter()
def replaced_consumer(word, idx):
if ((idx == dict.unk_index) and (wo... |
class ImageDecoder(nn.Module):
def __init__(self, input_size, n_channels, ngf, n_layers, activation='tanh'):
super(ImageDecoder, self).__init__()
ngf = (ngf * (2 ** (n_layers - 2)))
layers = [nn.ConvTranspose2d(input_size, ngf, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True)]
... |
_torch
_torchaudio
_sentencepiece
class Speech2TextProcessorTest(unittest.TestCase):
def setUp(self):
self.tmpdirname = tempfile.mkdtemp()
vocab = ['<s>', '<pad>', '</s>', '<unk>', 'This', 'is', 'a', 't', 'est']
vocab_tokens = dict(zip(vocab, range(len(vocab))))
save_dir = Path(self.... |
def _validate_accelerator(accel_obj):
if (not (((a1 is not None) and isinstance(accel_obj, a1)) or ((a2 is not None) and isinstance(accel_obj, a2)))):
raise AssertionError(f'{accel_obj.__class__.__name__} accelerator is not subclass of BaseAccelerator') |
class GroupCenterCrop(object):
def __init__(self, size):
self.worker = torchvision.transforms.CenterCrop(size)
def __call__(self, img_group):
return [self.worker(img) for img in img_group] |
def get_dataloader(split, config, return_dict=False):
dataset = AudioCaptionDataset(config.dataset, split, 'captioning', return_dict)
if (split == 'train'):
shuffle = True
drop_last = True
else:
shuffle = False
drop_last = False
return DataLoader(dataset=dataset, batch_si... |
def test_seg_evaluate():
if (not torch.cuda.is_available()):
pytest.skip()
root_path = './tests/data/s3dis'
ann_file = './tests/data/s3dis/s3dis_infos.pkl'
s3dis_dataset = S3DISSegDataset(data_root=root_path, ann_files=ann_file, test_mode=True)
results = []
pred_sem_mask = dict(semantic_... |
def mobilenetv3_large_100(pretrained=False, **kwargs):
model = _gen_mobilenet_v3('mobilenetv3_large_100', 1.0, pretrained=pretrained, **kwargs)
return model |
class Kernel(Module):
def __init__(self, scale=1.0, p=2.0, basis='Epanechnikov', fix_params=True):
super().__init__()
self.init_params(scale, fix_params)
self.pairwise_distance = partial(torch.cdist, p=p)
self.basis_func = torch.jit.script(getattr(diffsnn.nonparametric.basis, basis)(... |
def make_student(run_seed: int, config) -> BaseStudent:
trajs_path = config['TRAIN_TRAJ_PATH']
model_path = get_model_path(config['ENV'], ('student_' + config['ALG']), run_seed=run_seed)
state_dim = config['STATE_DIM']
action_dim = config['ACTION_DIM']
num_training_envs = config['NUM_TRAINING_ENVS']... |
def pad_seq(seq, max_length, PAD_token=0):
seq += [PAD_token for i in range((max_length - len(seq)))]
return seq |
class TFXLMRobertaModel():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def initalizeEnvironment(environment, logger):
if (environment != ''):
db = Database(DB_NAME, DB_HOST, DB_PORT)
' Can be SimpleFog, BitbrainFog, AzureFog // Datacenter '
if (environment != ''):
datacenter = Datacenter(HOSTS_IP, environment, 'Virtual')
else:
datacenter = AzureFog(... |
class Probe(nn.Module):
def __init__(self, dim, n_probes):
super(Probe, self).__init__()
self.self_attn = nn.Linear(dim, n_probes, bias=False)
nn.init.xavier_uniform_(self.self_attn.weight)
def forward(self, birnn_outputs, masks):
attn = self.self_attn(birnn_outputs).transpose(1,... |
def gen_filename(filename):
ext = filename.split('.')[(- 1)]
filename = filename.split('/')[(- 1)][:((- len(ext)) - 1)]
return filename |
def TrainPrepare():
if 1:
WB97XDAtom = {}
WB97XDAtom[1] = (- 0.)
WB97XDAtom[6] = (- 37.)
WB97XDAtom[7] = (- 54.)
WB97XDAtom[8] = (- 75.)
a = MSet('nicotine_aimd_rand')
a.Load()
b = MSet('nicotine_aimd_rand_train')
for (mol_index, mol) in enumer... |
class Model(nn.Module):
def __init__(self):
super().__init__()
self.param = nn.Parameter(torch.tensor([1.0]))
def forward(self, x, **kwargs):
return (self.param * x)
def train_step(self, data_batch, optimizer, **kwargs):
return {'loss': torch.sum(self(data_batch['x']))}
d... |
class NystromformerForSequenceClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
.parametrize('loader_parameters', [{'path_data': [str(Path(__data_testing_dir__, 'microscopy_png'))], 'target_suffix': ['_seg-myelin-manual', '_seg-axon-manual'], 'extensions': ['.png'], 'roi_params': {'suffix': None, 'slice_filter_roi': None}, 'contrast_params': {'contrast_lst': [], 'balance': {}}, 'slice_axis': 'axia... |
def draw_success_precision(success_ret, name, videos, attr, precision_ret=None, norm_precision_ret=None, bold_name=None, axis=[0, 1]):
(fig, ax) = plt.subplots()
ax.grid(b=True)
ax.set_aspect(1)
plt.xlabel('Overlap threshold')
plt.ylabel('Success rate')
if (attr == 'ALL'):
plt.title(('\\... |
def framework_operator_impl(framework_realizable_ops: List[Type[AbsOpBase]], all_framework_ops: List[Type[AbsOpBase]], op_type: AbsOpBase, *args, **kwargs):
SanityCheck.true(issubclass(op_type, AbsOpBase), f'Decorator operator_impl takes AbsOpBase subclass, but got {op_type}')
if (op_type is not Constant):
... |
def _check_h3d_bbox_head(bbox_cfg, bbox_head):
assert (bbox_cfg['type'] == bbox_head.__class__.__name__)
assert ((bbox_cfg.num_proposal * 6) == bbox_head.surface_center_matcher.num_point[0])
assert ((bbox_cfg.num_proposal * 12) == bbox_head.line_center_matcher.num_point[0])
assert ((bbox_cfg.suface_matc... |
class Cursor(Structure):
_fields_ = [('_kind_id', c_int), ('xdata', c_int), ('data', (c_void_p * 3))]
def from_location(tu, location):
cursor = conf.lib.clang_getCursor(tu, location)
cursor._tu = tu
return cursor
def __eq__(self, other):
return conf.lib.clang_equalCursors(sel... |
class Alphabet(object):
def __init__(self, name, defualt_value=False, keep_growing=True, singleton=False):
self.__name = name
self.instance2index = {}
self.instances = []
self.default_value = defualt_value
self.offset = (1 if self.default_value else 0)
self.keep_growi... |
def annotation_to_instances(ann: Annotation, docs: Dict[(str, List[List[int]])], class_interner: Dict[(str, int)]):
evidences = defaultdict(set)
for ev in ann.all_evidences():
evidences[ev.docid].add(ev)
output_documents = dict()
evidence_spans = dict()
for (d, evs) in evidences.items():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.