code stringlengths 101 5.91M |
|---|
def _create_linear_initializer(input_size, output_size, dtype=tf.float32):
return {'w': tf.orthogonal_initializer(), 'b': tf.zeros_initializer(dtype=dtype)} |
class Timm_Encoder_toy(nn.Module):
def __init__(self, obs_shape, feature_dim):
super().__init__()
self.num_step = int((obs_shape[0] / 3))
self.feature_dim = feature_dim
self.image_encode = vit_toy_patch6_84()
self.linear_map = nn.Linear(192, 50)
self.byol_project = nn... |
_model
def res2net101_26w_4s(pretrained=False, **kwargs):
model_args = dict(block=Bottle2neck, layers=[3, 4, 23, 3], base_width=26, block_args=dict(scale=4), **kwargs)
return _create_res2net('res2net101_26w_4s', pretrained, **model_args) |
class TestSameTransfoms(unittest.TestCase):
def setUpClass(cls):
if (platform.system().lower() == 'windows'):
cls.skipTest(cls, 'not support mxnet on windows yet')
cls.img = (np.random.random_sample([10, 10, 3]) * 255)
cls.tf_trans = TRANSFORMS('tensorflow', 'preprocess')
... |
class _SimpleSegmentationModel(nn.Module):
def __init__(self, backbone, classifier, im_num, ex_num):
super(_SimpleSegmentationModel, self).__init__()
self.backbone = backbone
self.classifier = classifier
self.bat_low = _bound_learner(hidden_features=128, im_num=im_num, ex_num=ex_num)... |
def tokenize_for_mer(text):
reg_range = "[\\u4e00-\\ufaff]|[0-9]+|[a-zA-Z]+\\'*[a-z]*"
matches = re.findall(reg_range, text, re.UNICODE)
p = inflect.engine()
res = []
for item in matches:
try:
temp = (p.number_to_words(item) if (item.isnumeric() and (len(regex.findall('\\p{Han}+'... |
def main():
parser = argparse.ArgumentParser(description='SSD evaluation')
parser.add_argument('--exp-name', type=str, default='temp_eval_ssd')
parser.add_argument('--training-mode', type=str, choices=('SimCLR', 'SupCon', 'SupCE'))
parser.add_argument('--results-dir', type=str, default='./eval_results')... |
def write_version_py(filename='cuhnsw/version.py'):
cnt = "\nshort_version = '%(version)s'\ngit_revision = '%(git_revision)s'\n"
git_revision = git_version()
with open(filename, 'w') as fout:
fout.write((cnt % {'version': VERSION, 'git_revision': git_revision})) |
_cache()
def create_local_process_group(num_workers_per_machine: int) -> None:
global _LOCAL_PROCESS_GROUP
assert (_LOCAL_PROCESS_GROUP is None)
assert ((get_world_size() % num_workers_per_machine) == 0)
num_machines = (get_world_size() // num_workers_per_machine)
machine_rank = (get_rank() // num_w... |
def _compile_to_stage_mod(model_pipe, pipe_group, num_stages, device, chunks, pipe_schedule='1F1B', example_inputs=None, checkpoint=True, data_ranks=None, traced_forward_keys=None, amp_config=None, args_chunk_spec=None, kwargs_chunk_spec=None, output_chunk_spec=None, compiler_configs=dict()):
(complete_args, comple... |
class AverageMeter(object):
def __init__(self):
self.book = dict()
def reset_all(self):
self.book.clear()
def reset(self, id):
item = self.book.get(id, None)
if (item is not None):
item[0] = 0
item[1] = 0
def update(self, id, val):
record =... |
def test_swin_block():
block = SwinBlock(embed_dims=32, num_heads=4, feedforward_channels=128)
assert (block.ffn.embed_dims == 32)
assert (block.attn.w_msa.num_heads == 4)
assert (block.ffn.feedforward_channels == 128)
x = torch.randn(1, (56 * 56), 32)
x_out = block(x, (56, 56))
assert (x_ou... |
class DistributionParams(Generic[T], nn.Module):
def __init__(self, batch_shape: Size=torch.Size()):
super().__init__()
self.batch_shape = torch.Size(batch_shape)
def get_distribution(self) -> T:
raise NotImplementedError
def from_distribution(dist: T) -> 'DistributionParams[T]':
... |
class ResNetV1(nn.Module):
def __init__(self, block, layers, num_classes=1000, deep_stem=False, zero_init_residual=False, norm_layer=nn.BatchNorm2d):
output_stride = cfg.MODEL.OUTPUT_STRIDE
scale = cfg.MODEL.BACKBONE_SCALE
if (output_stride == 32):
dilations = [1, 1]
... |
_register()
def Maxout(x, num_unit):
input_shape = x.get_shape().as_list()
ndim = len(input_shape)
assert ((ndim == 4) or (ndim == 2))
ch = input_shape[(- 1)]
assert ((ch is not None) and ((ch % num_unit) == 0))
if (ndim == 4):
x = tf.reshape(x, [(- 1), input_shape[1], input_shape[2], (c... |
def tuple_to_seq_BIOES(tuples, id_to_tag):
sentlen = (max([tuple[1] for tuple in tuples]) + 1)
seq = [None for _ in range(sentlen)]
for tuple in tuples:
if (id_to_tag[tuple[(- 1)]] == 'O'):
for i in range(tuple[0], (tuple[1] + 1)):
seq[i] = 'O'
elif ((tuple[1] - t... |
_cache()
def _get_cpu_extra_compile_args():
base_args = ['-fopenmp', '-ffast-math']
if (sys.platform == 'darwin'):
return (['-Xpreprocessor'] + base_args)
else:
return base_args |
def train(args, model, train_dataloader, test_dataloader, optimizer, epoch_idx=0.0):
loss_stack = []
iter_idx = (epoch_idx * len(train_dataloader))
iter_max = (args.epochs * len(train_dataloader))
with torch.no_grad():
model.eval()
print('update psd label bank!')
(glob_multi_feat... |
def test_imports():
run_cell('import numpy as np')
run_cell('arr = np.zeros((5,))')
run_cell('logging.info(arr * 3)')
deps = set(compute_unparsed_slice(3).keys())
assert (deps == {1, 2, 3}), ('got %s' % deps)
slice_size = num_stmts_in_slice(3)
assert (slice_size == 3), ('got %d' % slice_size... |
class MSRVTT_Caption_DataLoader(Dataset):
def __init__(self, csv_path, json_path, features_path, tokenizer, max_words=30, feature_framerate=1.0, max_frames=100, split_type=''):
self.csv = pd.read_csv(csv_path)
self.data = json.load(open(json_path, 'r'))
self.feature_dict = pickle.load(open(f... |
def max_prim(this, contrs, this_vals=False, contr_vals=False):
this_nlp = get_nlps(this, (lambda x: x), vals=this_vals)
contrs_nlp = [get_nlps(cs, (lambda x: x), vals=contr_vals) for cs in contrs]
contrs_nlp = [item for sublist in contrs_nlp for item in sublist]
this_nlp = filter_oov(this_nlp)
contr... |
def log_prior(z, prob_type='gaussian'):
if (prob_type == 'gaussian'):
return log_prior_gaussian(z)
if (prob_type == 'bernoulli'):
return log_prior_bernoulli(z)
if (prob_type == 'bernoulli_sym'):
return log_prior_bernoulli_sym(z)
if (prob_type == 'softmax'):
return log_pri... |
def deduplicate_filename(retrieve_filename, img_dir):
print('Starting deduplicate')
files = os.listdir(img_dir)
test_filename = retrieve_filename
(name, ext) = os.path.splitext(retrieve_filename)
i = 1
while (test_filename in files):
test_filename = (((name + '-') + str(i)) + ext)
... |
def resnet50_ibn_a(last_stride, pretrained=False, **kwargs):
model = ResNet_IBN(last_stride, Bottleneck_IBN, [3, 4, 6, 3], **kwargs)
if pretrained:
model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
return model |
class Config(object):
def __init__(self, task):
self.download_url = '
self.raw_data_dir = '../data/cornellmovie/raw_data'
self.task = task
self.task_data_dir = f'../data/cornellmovie/{task}'
self.dataset_path = f'{self.task_data_dir}/dataset.txt'
self.word_count_path ... |
def test_merge_intermediate_variable():
cfg_file = osp.join(data_path, 'config/i_child.py')
cfg = Config.fromfile(cfg_file)
assert (cfg.item1 == [1, 2])
assert (cfg.item2 == dict(a=0))
assert (cfg.item3 is True)
assert (cfg.item4 == 'test')
assert (cfg.item_cfg == dict(b=2))
assert (cfg.... |
class ResNet(nn.Module):
def __init__(self, block, layers, output_stride=16, zero_init_residual=True, groups=1, width_per_group=64, norm_layer=nn.BatchNorm2d, bn_mom=0.05, root_beta=True):
super(ResNet, self).__init__()
self._norm_layer = norm_layer
self.inplanes = (128 if root_beta else 64)... |
class ResNet(nn.Module):
def __init__(self, block, layers, num_classes=1000, zero_init_residual=False, groups=1, width_per_group=64, replace_stride_with_dilation=None, norm_layer=None, feature_size=64):
super(ResNet, self).__init__()
if (norm_layer is None):
norm_layer = nn.BatchNorm2d
... |
def _split_channels(num_chan, num_groups):
split = [(num_chan // num_groups) for _ in range(num_groups)]
split[0] += (num_chan - sum(split))
return split |
def dataset(tfrecords_path, read_buffer_size=None, map_parallel_calls=None):
raw_dataset = tf.data.TFRecordDataset(tfrecords_path, compression_type=COMPRESSION_TYPE, buffer_size=read_buffer_size)
return raw_dataset.map(_decode, num_parallel_calls=map_parallel_calls) |
def add_ray_init_args(parser):
def init_help_string(help_string):
return (help_string + ' Passed to `ray.init`.')
parser.add_argument('--cpus', type=int, default=None, help=init_help_string('Cpus to allocate to ray process.'))
parser.add_argument('--gpus', type=int, default=None, help=init_help_stri... |
def single_gpu_test(model, data_loader, show=False):
model.eval()
results = []
dataset = data_loader.dataset
prog_bar = mmcv.ProgressBar(len(dataset))
for (i, data) in enumerate(data_loader):
with torch.no_grad():
result = model(return_loss=False, rescale=(not show), **data)
... |
def _compute_aspect_ratios_custom_dataset(dataset, indices=None):
if (indices is None):
indices = range(len(dataset))
aspect_ratios = []
for i in indices:
(height, width) = dataset.get_height_and_width(i)
aspect_ratio = (float(width) / float(height))
aspect_ratios.append(aspe... |
def preprocess_function(examples):
args = ((examples[sentence1_key],) if (sentence2_key is None) else (examples[sentence1_key], examples[sentence2_key]))
result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True)
if ((label_to_id is not None) and ('label' in examples)):
r... |
class PushGinConfigOperator(bpy.types.Operator):
bl_idname = 'scene.zpy_push_gin_config'
bl_label = 'Push gin config to file.'
bl_description = 'Push gin config to file.'
bl_category = 'ZPY'
bl_options = {'REGISTER'}
def execute(self, context):
_text = bpy.data.texts[LoadGinConfigOperato... |
class VOC2012(Dataset):
def __init__(self, root, phase, transform=None):
self.root = os.path.abspath(root)
self.path_devkit = os.path.join(self.root, 'VOCdevkit')
self.path_images = os.path.join(self.root, 'VOCdevkit', 'VOC2012', 'JPEGImages')
self.phase = phase
self.transfor... |
def resnet44_cifar(**kwargs):
model = ResNet_Cifar(BasicBlock, [7, 7, 7], **kwargs)
return model |
def recall(predictions, gold):
if (len(gold) == 0):
return (1.0 if (len(predictions) == 0) else 0.0)
if (len(predictions) == 0):
return 0.0
predictions_set = set(predictions)
gold_set = set(gold)
nom = len(predictions_set.intersection(gold_set))
denom = len(gold_set)
return (... |
def intersection(a, b):
top = max(a[0], b[0])
left = max(a[1], b[1])
bottom = min(a[2], b[2])
right = min(a[3], b[3])
h = max((bottom - top), 0)
w = max((right - left), 0)
return (h * w) |
def main():
print('------')
args = parse_args()
script_path = Path(os.path.abspath(os.getcwd()))
project_path = script_path.parent.parent.parent.parent.absolute()
dump_log_path = '{}/{}'.format(script_path, args.output_file)
if os.path.exists(dump_log_path):
os.remove(dump_log_path)
... |
class BaseTextControl(wx.stc.StyledTextCtrl):
def __init__(self, parent):
super().__init__(parent)
self.SetEditable(False)
self.CmdKeyClear(89, wx.stc.STC_SCMOD_CTRL)
self.CmdKeyAssign(90, (wx.stc.STC_SCMOD_SHIFT | wx.stc.STC_SCMOD_CTRL), wx.stc.STC_CMD_REDO)
self.text_font =... |
class parameter(Structure):
_names = ['solver_type', 'eps', 'C', 'nr_weight', 'weight_label', 'weight', 'p', 'init_sol']
_types = [c_int, c_double, c_double, c_int, POINTER(c_int), POINTER(c_double), c_double, POINTER(c_double)]
_fields_ = genFields(_names, _types)
def __init__(self, options=None):
... |
class TFDataDataset(TFDataset):
def get_num_partitions(self):
return self.total_core_num
def _assert_not_batched(dataset):
from tensorflow.python.data.ops import dataset_ops
if isinstance(dataset, dataset_ops.DatasetV1Adapter):
TFDataDataset._assert_not_batched(dataset._datas... |
class S2Image():
def __init__(self, name, yyyymmdd, cloudy_pct, coverage, aws_path, local_path, data_collection):
self.name = name
self.yyyymmdd = yyyymmdd
self.cloudy_pct = cloudy_pct
self.coverage = coverage
self.aws_path = aws_path
self.local_path = local_path
... |
def _clean_sexp(sexp):
if isinstance(sexp, sexpdata.Symbol):
return sexp.value()
return tuple((_clean_sexp(s) for s in sexp)) |
def syuv_to_rgb(yuv):
yuv = torch.as_tensor(yuv)
kernel = torch.tensor([[1, 1, 1], [0, (- 0.), 2.], [1., (- 0.), 0]]).to(yuv)
rgb = torch.reshape(torch.matmul(torch.reshape(yuv, [(- 1), 3]), kernel), yuv.shape)
return (rgb / _VOLUME_PRESERVING_YUV_SCALE) |
def gather_tensor(tensor, args):
output_tensors = [tensor.clone() for _ in range(args.world_size)]
torch.distributed.all_gather(output_tensors, tensor)
concat = torch.cat(output_tensors, dim=0)
return concat |
class EvalCOCO(data.Dataset):
def __init__(self, root, split, mode, res=128, transform_list=[], label=True, stuff=True, thing=False):
self.root = root
self.split = split
self.mode = mode
self.res = res
self.imdb = self.load_imdb()
self.stuff = stuff
self.thing... |
class domainTextIterator():
def __init__(self, s_domain_data, t_domain_data, g_domain_data, dic, batch=1, maxlen=50, n_words_target=(- 1)):
self.s_domain_data = fopen(s_domain_data, 'r')
self.t_domain_data = fopen(t_domain_data, 'r')
self.g_domain_data = fopen(g_domain_data, 'r')
wit... |
def get_model(point_cloud, is_training, num_classes, bn_decay=None):
batch_size = point_cloud.get_shape()[0].value
num_point = point_cloud.get_shape()[1].value
end_points = {}
input_image = tf.expand_dims(point_cloud, (- 1))
net = tf_util.conv2d(input_image, 64, [1, 3], padding='VALID', stride=[1, 1... |
class SwishMe(nn.Module):
def __init__(self, inplace: bool=False):
super(SwishMe, self).__init__()
def forward(self, x):
return SwishJitAutoFn.apply(x) |
class VWEvent():
def __init__(self, kind=None, params=None, actions=None, grid=None, camera=None, position=None, step=None, turn=None):
self.kind = kind
self.params = params
if (actions is None):
actions = []
assert isinstance(actions, (list, tuple))
self.actions ... |
class Item():
def __init__(self, attribute, value):
self.attribute = (repr(attribute) if (type(attribute) != str) else attribute)
self.value = (repr(value) if (type(value) != str) else value)
def __get_tuple(self):
return (self.attribute, self.value)
def __getitem__(self, idx):
... |
def customized_export_ply(outfile_name, v, f=None, v_n=None, v_c=None, f_c=None, e=None):
v_n_flag = False
v_c_flag = False
f_c_flag = False
N_v = v.shape[0]
assert (v.shape[1] == 3)
if (not (type(v_n) == type(None))):
assert (v_n.shape[0] == N_v)
if (type(v_n) == 'torch.Tensor')... |
class _EmptyMapDataset(torch.utils.data.Dataset):
def __init__(self, dataset):
self.ds = dataset
def __len__(self):
return len(self.ds)
def __getitem__(self, idx):
_ = self.ds[idx]
return [0] |
('single_seq_model')
class SingleSeqModel(Model):
def from_params(cls, params):
params = deepcopy(params)
input_names = params['input_names']
target_names = params['target_names']
embedder_config = params['embedder']
encoder_config = params['encoder']
decoder_config =... |
def format_text(text, **format):
text = re.sub(' '', text, flags=re.MULTILINE)
if format['remove_mentions']:
text = re.sub('\\S+', '', text, flags=re.MULTILINE)
if format['unidecode']:
text = unidecode(text)
new_text = []
for word in re.split("[' ]", text):
if ((len(word) < 5... |
def pal2al(_annolist):
annotations = AnnotationLib.AnnoList()
for adesc in _annolist.attribute_desc:
annotations.attribute_desc[adesc.name] = adesc
print('attribute: ', adesc.name, adesc.id)
for valdesc in adesc.val_to_str:
annotations.add_attribute_val(adesc.name, valdesc.s,... |
def prc_auc(targets, preds):
(precision, recall, _) = precision_recall_curve(targets, preds)
return auc(recall, precision) |
class Token():
def __init__(self, tid: int, index: int, span_start: int, span_end: int, phrase: str):
self._tid = tid
self._index = index
self._span_start = span_start
self._span_end = span_end
self._phrase = phrase
def index(self):
return self._index
def span... |
class TestParser(QiskitTestCase):
def setUp(self):
self.qasm_file_path = self._get_resource_path('example.qasm', Path.QASMS)
self.qasm_file_path_fail = self._get_resource_path('example_fail.qasm', Path.QASMS)
self.qasm_file_path_if = self._get_resource_path('example_if.qasm', Path.QASMS)
... |
def _experiments_to_circuits(qobj):
if qobj.experiments:
circuits = []
for x in qobj.experiments:
quantum_registers = [QuantumRegister(i[1], name=i[0]) for i in x.header.qreg_sizes]
classical_registers = [ClassicalRegister(i[1], name=i[0]) for i in x.header.creg_sizes]
... |
def conv_relu(input, size, depth, in_depth=None):
sqared = math.sqrt((size * size))
weights = tf.get_variable('weights', (size, size, in_depth, depth), initializer=tf.contrib.layers.xavier_initializer())
bias = tf.get_variable('bias', [depth], initializer=tf.constant_initializer(value=0.0))
conv = tf.nn... |
def accuracy(output: torch.tensor, target: torch.tensor, topk=(1,)) -> List[torch.tensor]:
with torch.no_grad():
maxk = max(topk)
batch_size = target.size(0)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))
... |
def main():
parser = ArgumentParser(description='Train or evaluate NeurWP models for LAM')
parser.add_argument('--dataset', type=str, default='meps_example', help='Dataset, corresponding to name in data directory (default: meps_example)')
parser.add_argument('--model', type=str, default='graph_lam', help='M... |
def clear_vocabs():
global _COG_LIST
global _VOCABS
_COG_LIST = None
_VOCABS = dict() |
class InputDataFields(object):
image = 'image'
original_image = 'original_image'
key = 'key'
source_id = 'source_id'
filename = 'filename'
groundtruth_image_classes = 'groundtruth_image_classes'
groundtruth_boxes = 'groundtruth_boxes'
groundtruth_classes = 'groundtruth_classes'
groun... |
class LayerNorm(nn.Module):
def __init__(self, features, eps=1e-06):
super(LayerNorm, self).__init__()
self.a_2 = nn.Parameter(torch.ones(features))
self.b_2 = nn.Parameter(torch.zeros(features))
self.eps = eps
def forward(self, x):
mean = x.mean((- 1), keepdim=True)
... |
def print_filtered_stacktrace():
(exc_type, exc_value, exc_traceback) = sys.exc_info()
current_tb = exc_traceback
while (current_tb.tb_next is not None):
current_tb = current_tb.tb_next
if ('__sacred__' in current_tb.tb_frame.f_globals):
print('Exception originated from within Sacred.\nT... |
class StatusData(genpy.Message):
_md5sum = 'c70a4ecae176ad30f89553'
_type = 'quadrotor_msgs/StatusData'
_has_header = True
_full_text = "Header header\nuint16 loop_rate\nfloat64 voltage\nuint8 seq\n\n\nMSG: std_msgs/Header\n# Standard metadata for higher-level stamped data types.\n# This is generally us... |
def divide_cls(image_path_lst, train_set_cls, train_set_lst, valid_set_lst):
ratio = 0.8
image_path_size = len(image_path_lst)
train_set = image_path_lst[:int((ratio * image_path_size))]
valid_set = image_path_lst[int((ratio * image_path_size)):]
with open(train_set_cls, 'w') as f:
f.write('... |
.skipif((not torch.cuda.is_available()), reason='requires CUDA to run')
def test_flash_standard_shapes():
assert (standard_attn(X).shape == flash_attn(X).shape) |
class FlaxWav2Vec2ForCTC(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
def reorient_image(arr: np.ndarray, slice_axis: int, nib_ref: nib, nib_ref_canonical: nib) -> nd.ndarray:
arr_ras = orient_img_ras(arr, slice_axis)
ref_orientation = nib.orientations.io_orientation(nib_ref.affine)
ras_orientation = nib.orientations.io_orientation(nib_ref_canonical.affine)
trans_orient =... |
class HfArgumentParser(ArgumentParser):
dataclass_types: Iterable[DataClassType]
def __init__(self, dataclass_types: Union[(DataClassType, Iterable[DataClassType])], **kwargs):
if ('formatter_class' not in kwargs):
kwargs['formatter_class'] = ArgumentDefaultsHelpFormatter
super().__i... |
def recall(rank, ground_truth, N):
return (len((set(rank[:N]) & set(ground_truth))) / float(len(set(ground_truth)))) |
def resnext20_32x2d_cifar10(num_classes=10, **kwargs):
return get_resnext_cifar(num_classes=num_classes, blocks=20, cardinality=32, bottleneck_width=2, model_name='resnext20_32x2d_cifar10', **kwargs) |
def get_micro_f1(guess_entities, gold_entities, mode='strong'):
precision = get_micro_precision(guess_entities, gold_entities, mode)
recall = get_micro_recall(guess_entities, gold_entities, mode)
return (((2 * (precision * recall)) / (precision + recall)) if (precision + recall) else 0) |
def setup_logger(output=None):
if (output is None):
return
if (output.endswith('.txt') or output.endswith('.log')):
fpath = output
else:
fpath = osp.join(output, 'log.txt')
if osp.exists(fpath):
fpath += time.strftime('-%Y-%m-%d-%H-%M-%S')
sys.stdout = Logger(fpath) |
class Adam(torch.optim.Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False):
defaults = dict(lr=lr, betas=betas, eps=eps, weight_decay=weight_decay, amsgrad=amsgrad)
super(Adam, self).__init__(params, defaults)
def supports_memory_efficie... |
def main():
args = get_arguments()
try:
directories = validate_directories(args)
except ValueError as e:
print('Some arguments are wrong:')
print(str(e))
return
logdir = directories['logdir']
restore_from = directories['restore_from']
is_overwritten_training = (lo... |
_dataset_obj('mnist')
class MNIST(datasets.MNIST):
def __init__(self, root, train=True, transform=None, target_transform=None, download=False):
super(MNIST, self).__init__(root, train=train, transform=transform, target_transform=target_transform, download=download) |
def test_rank1_symmetric_convex_solver():
(XYXY_rank1, XYXY_missing_rank1) = create_rank1_data(symmetric=True)
solver = NuclearNormMinimization(require_symmetric_solution=True)
completed = solver.fit_transform(XYXY_missing_rank1)
assert (abs((completed[(1, 2)] - XYXY_rank1[(1, 2)])) < 0.01), ('Expected ... |
def get_latest_version(folder):
versions = [int(pathlib.PurePath(path).name.split('_')[(- 1)]) for path in glob(f'{folder}/version_*/')]
if (len(versions) == 0):
return None
versions.sort()
return versions[(- 1)] |
def prompt_to_chatml(prompt: str, start_token: str='<|im_start|>', end_token: str='<|im_end|>'):
prompt = prompt.strip()
assert prompt.startswith(start_token)
assert prompt.endswith(end_token)
message = []
for p in prompt.split('<|im_start|>')[1:]:
newline_splitted = p.split('\n', 1)
... |
class CascadingBanditEpsilonGreedy(Agent):
def __init__(self, num_items, num_positions, a0=1, b0=1, epsilon=0.0, optimism=1.0):
self.num_items = num_items
self.num_positions = num_positions
self.a0 = a0
self.b0 = b0
self.prior_success = np.array([a0 for item in range(num_item... |
def get_well_conditioned_gaussian_datasets(dim, std, oos_std):
train_dset = get_gaussian_dataset(role='train', size=50000, dim=dim, std=std)
valid_dset = get_gaussian_dataset(role='valid', size=5000, dim=dim, std=std)
test_dsets = [get_gaussian_dataset(role='test', size=10000, dim=dim, std=std), get_gaussia... |
class GRU(Model):
_compatible_windows = (window_module.Global, window_module.Sliding, window_module.Expanding, window_module.Dyadic)
def __init__(self, in_channels, hidden_channels, out_channels, num_layers, bias=True, dropout=0):
super(GRU, self).__init__()
self.in_channels = in_channels
... |
def toVerticalPotential(Pot, R, phi=None, t0=0.0):
Pot = flatten(Pot)
if _isDissipative(Pot):
raise NotImplementedError('Converting dissipative forces to 1D vertical potentials is currently not supported')
try:
conversion.get_physical(Pot)
except:
raise PotentialError("Input to '... |
def modify_densenets(model):
model.last_linear = model.classifier
del model.classifier
def logits(self, features):
x = F.relu(features, inplace=True)
x = F.avg_pool2d(x, kernel_size=7, stride=1)
x = x.view(x.size(0), (- 1))
x = self.last_linear(x)
return x
def for... |
class Metric(ABC):
def get_metric(self, backend: str='bigdl'):
if (backend == 'bigdl'):
metric_impl = self.get_bigdl_metric()
elif (backend == 'pytorch'):
metric_impl = self.get_pytorch_metric()
elif (backend == 'tf'):
metric_impl = self.get_tf_metric()
... |
class GraphVisualization():
def __init__(self, env):
self.connections = env.connections.T
self.G = nx.DiGraph()
self.G.add_edges_from(self.connections)
self.pos = nx.kamada_kawai_layout(self.G)
self.colors = [COLOR_DOWN, COLOR_RUNNING, COLOR_SELECTED_D, COLOR_SELECTED_R]
... |
class Blip2CaptionProcessor():
def __init__(self, prompt='', max_words=50):
self.prompt = prompt
self.max_words = max_words
def __call__(self, caption):
caption = (self.prompt + self.pre_caption(caption))
return caption
def pre_caption(self, caption):
caption = re.sub... |
('mmdet.datasets.CocoDataset.load_annotations', MagicMock())
('mmdet.datasets.CustomDataset.load_annotations', MagicMock())
('mmdet.datasets.XMLDataset.load_annotations', MagicMock())
('mmdet.datasets.CityscapesDataset.load_annotations', MagicMock())
('mmdet.datasets.CocoDataset._filter_imgs', MagicMock)
('mmdet.datase... |
def row_csv2dict(csv_file):
dict_club = {}
with open(csv_file) as f:
reader = csv.reader(f, delimiter=',')
for row in reader:
dict_club[(row[0], row[1])] = row[2]
return dict_club |
class SetDataset():
def __init__(self, batch_size, transform):
self.sub_meta = {}
self.cl_list = range(47)
for cl in self.cl_list:
self.sub_meta[cl] = []
d = ImageFolder(DTD_path)
for (i, (data, label)) in enumerate(d):
self.sub_meta[label].append(data... |
def test():
net = PNASNetB()
print(net)
x = Variable(torch.randn(1, 3, 32, 32))
y = net(x)
print(y) |
def generate_labels(img_id, detail, out_dir):
def _class_to_index(mask, _mapping, _key):
values = np.unique(mask)
for i in range(len(values)):
assert (values[i] in _mapping)
index = np.digitize(mask.ravel(), _mapping, right=True)
return _key[index].reshape(mask.shape)
... |
def load_args():
parser = argparse.ArgumentParser(description='Transformer baseline', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--seed', type=int, default=0, help='random seed')
parser.add_argument('--dataset', type=str, default='ZINC', help='name of dataset')
parser.a... |
class XceptionBlock(nn.Module):
def __init__(self, channel_list, stride=1, dilation=1, skip_connection_type='conv', relu_first=True, low_feat=False, norm_layer=nn.BatchNorm2d):
super().__init__()
assert (len(channel_list) == 4)
self.skip_connection_type = skip_connection_type
self.re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.