code stringlengths 101 5.91M |
|---|
def velocity_after_collision(n: np.ndarray, velocity: np.ndarray, m: float, j: float) -> np.ndarray:
return (velocity + ((j * n) / m)) |
def paths_to_tensors(paths, max_path_length, baseline_predictions, discount):
baselines = []
returns = []
for (idx, path) in enumerate(paths):
path['baselines'] = baseline_predictions[idx]
baselines.append(path['baselines'])
path['returns'] = tensor_utils.discount_cumsum(path['reward... |
def benchmark_shortest_path_image(configuration_space, source):
def shortest_path_image():
graph = shortest_paths.GridGraph(configuration_space)
graph.shortest_path_image(source)
benchmark(shortest_path_image) |
def FindEndOfExpressionInLine(line, startpos, depth, startchar, endchar):
for i in xrange(startpos, len(line)):
if (line[i] == startchar):
depth += 1
elif (line[i] == endchar):
depth -= 1
if (depth == 0):
return ((i + 1), 0)
return ((- 1), dept... |
class FlaxBigBirdForMultipleChoice(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class AssignScoreWithK(Function):
def forward(ctx, scores, points, centers, knn_idx, aggregate):
agg = {'sum': 0, 'avg': 1, 'max': 2}
(B, N, M, O) = points.size()
K = scores.size(2)
output = torch.zeros([B, O, N], dtype=points.dtype, device=points.device)
output = output.cont... |
def list_non_bool_dtypes():
return [o3c.float32, o3c.float64, o3c.int8, o3c.int16, o3c.int32, o3c.int64, o3c.uint8, o3c.uint16, o3c.uint32, o3c.uint64] |
def get_hbond_donor_indice(m):
smarts = ['[!#6;!H0]']
indice = []
for s in smarts:
s = Chem.MolFromSmarts(s)
indice += [i[0] for i in m.GetSubstructMatches(s)]
indice = np.array(indice)
return indice |
class FeatureFusionModule(nn.Module):
def __init__(self, in_chan, out_chan, *args, **kwargs):
super(FeatureFusionModule, self).__init__()
self.convblk = ConvBNReLU(in_chan, out_chan, ks=1, stride=1, padding=0)
self.conv1 = nn.Conv2d(out_chan, (out_chan // 4), kernel_size=1, stride=1, padding... |
class MetaFeature(AbstractMetaFeature):
def __init__(self):
super(MetaFeature, self).__init__()
self.type_ = 'METAFEATURE' |
def makeplot_bar(experiments, planner, ttl):
if (plt_cfg['qt'] == 1):
N = len(experiments)
x = np.linspace(1, N, N, endpoint=True)
plt.figure(ttl)
plt.xlabel('Test run')
if ('dur' in ttl):
plt.ylabel('Execution Time in [s]')
else:
plt.ylabel('P... |
class AutoregressiveRationalQuadraticSplineBijection(RationalQuadraticSplineBijection):
def __init__(self, num_input_channels, num_hidden_layers, num_hidden_channels, num_bins, tail_bound, activation, dropout_probability):
super().__init__(num_input_channels=num_input_channels, flow=MaskedPiecewiseRationalQ... |
def rearrange_tf_to_pt(value, depthwise=False):
if (value.ndim == 4):
if depthwise:
return einops.rearrange(value, 'h w c_in c_out -> c_in c_out h w')
else:
return einops.rearrange(value, 'h w c_in c_out -> c_out c_in h w')
elif (value.ndim == 2):
return einops.re... |
class HPText():
dataset = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'datasets/data/LJSpeech-1.1')
(num_train, num_valid) = (13000, 13099)
punctuation = list('\'",.:?!')
graphemes = ((['<pad>', '<unk>'] + list('abcdefghijklmnopqrstuvwxyz ')) + punctuation)
use_phonemes = True |
def test_construct_arguments_without_duplicates_passes():
s = Signature(bariza)
s.construct_arguments([1, 2], {'c': 5}, {})
s = Signature(complex_function_name)
s.construct_arguments([1], {'b': 4}, {})
s = Signature(FunCTIonWithCAPItals)
s.construct_arguments([], {'a': 6, 'b': 6, 'c': 6}, {}) |
def all_metrics(preds, labels):
acc = simple_accuracy(preds, labels)
f1 = f1_score(y_true=labels, y_pred=preds)
pre = precision_score(y_true=labels, y_pred=preds)
rec = recall_score(y_true=labels, y_pred=preds)
return {'acc': acc, 'precision': pre, 'recall': rec, 'f1': f1} |
def apiurl(args: argparse.Namespace, subpath: str, query_args: typing.Dict=None) -> str:
if (query_args is None):
query_args = {}
if (args.api_key is not None):
query_args['api_key'] = args.api_key
if query_args:
return (((args.url + subpath) + '?') + '&'.join(('{x}={y}'.format(x=x, ... |
class DRN_A(nn.Module):
def __init__(self, block, layers, BatchNorm=None):
self.inplanes = 64
super(DRN_A, self).__init__()
self.out_dim = (512 * block.expansion)
self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = BatchNorm(64)
se... |
def convert(item):
(qid, example) = item
q = {'image_id': example['imageId'], 'question_id': qid, 'question': example['question']}
if ('answer' in example):
a = {'image_id': example['imageId'], 'question_id': qid, 'answers': [{'answer': example['answer']}]}
else:
a = None
return (q, ... |
class Xception_dilation(nn.Module):
def __init__(self, input_channel=None, num_classes=None):
super(Xception_dilation, self).__init__()
self.num_classes = num_classes
self.conv1 = nn.Conv2d(input_channel, 32, 3, 2, 0, bias=False)
self.bn1 = nn.BatchNorm2d(32)
self.relu1 = nn.... |
class Pinwheel(VAE):
def __init__(self, params):
assert (params.latent_dim == 2)
super(Pinwheel, self).__init__(NormalMixture, dist.Normal, dist.Normal, Enc(params.latent_dim, params.num_hidden_layers, params.hidden_dim), Dec(params.latent_dim, params.num_hidden_layers, params.hidden_dim), params)
... |
def np_F1(y_true, y_pred):
score = []
for (yy_true, yy_pred) in zip(y_true, y_pred):
this = f1_score((yy_true > 0.5).astype('int').ravel(), (yy_pred > 0.5).astype('int').ravel())
that = f1_score((yy_true > 0.5).astype('int').ravel(), ((1 - yy_pred) > 0.5).astype('int').ravel())
score.app... |
def indice_maxpool(features, indice_pairs, indice_pair_num, num_activate_out):
if (features.dtype == torch.float32):
return sparse_conv_ext.indice_maxpool_fp32(features, indice_pairs, indice_pair_num, num_activate_out)
elif (features.dtype == torch.half):
return sparse_conv_ext.indice_maxpool_ha... |
def int2bitstr(integer):
four_bytes = struct.pack('>I', integer)
return ''.join((f'{byte:08b}' for byte in four_bytes)) |
class MLPComponentTest(BaseRegressionComponentTest):
__test__ = True
res = dict()
res['default_boston'] = 0.
res['default_boston_places'] = 4
res['boston_n_calls'] = 8
res['boston_iterative_n_iter'] = 161
res['default_boston_iterative'] = res['default_boston']
res['default_boston_iterati... |
class DukeMTMC(Dataset):
url = '
md5 = '2f93496f9b516d1ee5ef51c1d5e7d601'
def __init__(self, root, split_id=0, num_val=100, download=True):
super(DukeMTMC, self).__init__(root, split_id=split_id)
if download:
self.download()
if (not self._check_integrity()):
r... |
def generate_cross_cols(self, df: pd.DataFrame, crossed_cols):
df_cc = df.copy()
crossed_colnames = []
for cols in crossed_cols:
for c in cols:
df_cc[c] = df_cc[c].astype('str')
colname = '_'.join(cols)
df_cc[colname] = df_cc[list(cols)].apply((lambda x: '-'.join(x)), axi... |
def model_opts(parser):
group = parser.add_argument_group('Model-Embeddings')
group.add_argument('-src_word_vec_size', type=int, default=500, help='Word embedding size for src.')
group.add_argument('-tgt_word_vec_size', type=int, default=500, help='Word embedding size for tgt.')
group.add_argument('-wor... |
def update_context(job_args: JobArgs):
for (node_type, node_args) in job_args.node_args.items():
if (node_type == NodeType.WORKER):
_dlrover_context.auto_worker_enabled = node_args.auto_scale
elif (node_type == NodeType.PS):
_dlrover_context.auto_ps_enabled = node_args.auto_s... |
class L2BallProj(L2Ball):
def __init__(self, X, epsilon, k):
DualObject.__init__(self)
self.epsilon = epsilon
n = X[0].numel()
self.nu_x = [X]
self.nu = [X.new(1, k, *X.size()[1:]).normal_()]
def apply(self, dual_layer):
self.nu_x.append(dual_layer(*self.nu_x))
... |
class SmoothQuantCalibrationLLM(SmoothQuantCalibration):
def __init__(self, model_path, dataloader, iterations, op_types, percentile, temp_path, weight_name_mapping):
self.func = None
self.graph_def = None
self.frozen_func = None
self._saved_model = None
self.model = model_pa... |
class ImageExtents():
def __init__(self, minX, minY, minZ, maxX, maxY, maxZ):
self.minX: float = minX
self.minY: float = minY
self.minZ: float = minZ
self.maxX: float = maxX
self.maxY: float = maxY
self.maxZ: float = maxZ
def get_c_image_extents(self):
c_i... |
def register_box(name: str, box_type: Type=None, force: bool=False) -> Union[(Type, Callable)]:
if (not isinstance(force, bool)):
raise TypeError(f'force must be a boolean, but got {type(force)}')
if (box_type is not None):
_register_box(name=name, box_type=box_type, force=force)
return ... |
def disc(samples1, samples2, kernel, is_parallel=True, *args, **kwargs):
d = 0
if (not is_parallel):
for s1 in samples1:
for s2 in samples2:
d += kernel(s1, s2, *args, **kwargs)
else:
with concurrent.futures.ThreadPoolExecutor() as executor:
for dist i... |
class _CLAM_Base(nn.Module):
sizes = {'small': [1024, 512, 256], 'big': [1024, 512, 384], 'multiscale': [2048, 512, 256]}
def __init__(self, size: Union[(str, List[int])]='small', dropout: bool=False, k_sample: int=8, n_classes: int=2, instance_loss_fn: Optional[Callable]=None, subtyping: bool=False, gate: bool... |
class _MSDataLoaderIter(_DataLoaderIter):
def __init__(self, loader):
self.dataset = loader.dataset
self.collate_fn = loader.collate_fn
self.batch_sampler = loader.batch_sampler
self.num_workers = loader.num_workers
self.pin_memory = (loader.pin_memory and torch.cuda.is_avail... |
def train(train_loader, model, criterion, optimizer, scheduler, epoch):
batch_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
model.train()
end = time.time()
for (i, (input, target)) in enumerate(train_loader):
output = model(input)
loss = criterion(output, ta... |
class RayScenario(Scenario, ABC):
def __init__(self, name: str, ray_cluster_cpus: Union[(int, float)], ray_cluster_gpus: Union[(int, float)], ray_object_store_memory_cap_gigabytes: Union[(int, float)], ray_should_log_result_filter: Callable[([ResultDict], bool)]):
super().__init__(name=name)
self.ra... |
class BasicBlock(nn.Module):
def __init__(self, in_chan, out_chan, stride=1):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(in_chan, out_chan, stride)
self.bn1 = BatchNorm2d(out_chan)
self.conv2 = conv3x3(out_chan, out_chan)
self.bn2 = BatchNorm2d(out_chan)
... |
(version='2.0')
def check_model(model):
has_integerop = False
has_qlinearop = False
for node in model.graph.node:
if node.op_type.endswith('Integer'):
has_integerop = True
elif node.op_type.startswith('QLinear'):
has_qlinearop = True
elif (node.op_type in ['QA... |
_operation
def real(a: torch.Tensor):
if is_real(a):
raise ValueError('Last dimension must have length 2.')
return a[(..., 0)] |
def find_missing(xs, ys, rs):
rotations = [0, 3.14, 1.57, (- 1.57), 0.78, (- 0.78), 2.35, (- 2.35)]
expectedPoints = []
missingPointsX = []
missingPointsY = []
for (xd, yd) in zip(*required_points()):
expectedPoints.append((xd, yd))
isMissing = [True for _ in rotations]
for (... |
def initialize_hyperparameters(PATHS: dict, load_target: str, config_name: str='default', n_envs: int=1):
if (load_target is None):
hyperparams = load_hyperparameters_json(PATHS=PATHS, from_scratch=True, config_name=config_name)
hyperparams['agent_name'] = PATHS['model'].split('/')[(- 1)]
else:
... |
_criterion('legacy_masked_lm_loss')
class LegacyMaskedLmLoss(FairseqCriterion):
def __init__(self, task, masked_lm_only, nsp_loss_weight):
super().__init__(task)
self.masked_lm_only = masked_lm_only
self.nsp_loss_weight = nsp_loss_weight
def add_args(parser):
parser.add_argument(... |
class DeviceType(object):
CPU = 'CPU'
GPU = 'GPU'
HEXAGON = 'HEXAGON'
HTA = 'HTA'
APU = 'APU'
HTP = 'HTP'
QUANTIZE = 'QUANTIZE' |
class DeResNetBlockGroupNorm(nn.Module):
def __init__(self, inplanes, planes, num_groups, stride=1, output_padding=0, activation='relu'):
super(DeResNetBlockGroupNorm, self).__init__()
assert (activation in ['relu', 'elu', 'leaky_relu'])
self.deconv1 = deconv3x3(inplanes, planes, stride, out... |
def distributed_init(cfg: FairseqConfig):
if isinstance(cfg, Namespace):
from fairseq.dataclass.utils import convert_namespace_to_omegaconf
cfg = convert_namespace_to_omegaconf(cfg)
if (not cfg.common.tpu):
if (torch.distributed.is_available() and torch.distributed.is_initialized()):
... |
def evaluate(gold, guess, ks, rank_keys):
pp = pprint.PrettyPrinter(indent=4)
gold_dataset = kilt_utils.load_data(gold)
guess_dataset = kilt_utils.load_data(guess)
(gold_dataset, guess_dataset) = eval_downstream.validate_input(gold_dataset, guess_dataset)
guess_dataset = filter_answers(guess_dataset... |
def compute(inp, outp, settings, force):
sr = settings['samplerate']
_lazy_y = None
def load():
nonlocal _lazy_y
if (_lazy_y is None):
(_lazy_y, _sr) = librosa.load(inp, sr=sr)
assert (_sr == sr), _sr
return _lazy_y
exists = os.path.exists(outp)
size =... |
class VegaHTML(object):
def __init__(self, renderer):
self.specification = dict(width=renderer.figwidth, height=renderer.figheight, data=renderer.data, scales=renderer.scales, axes=renderer.axes, marks=renderer.marks)
def html(self):
id = random.randint(0, (2 ** 16))
html = ('<div id="vi... |
def build_fake_yaml():
fake_yaml = '\n model:\n name: fake_yaml\n framework: tensorflow\n inputs: x\n outputs: op_to_store\n device: cpu\n quantization:\n calibration:\n sampling_size: 10\n evaluation:\n accuracy:\n ... |
def preprocess_iwslt17(root: str, src: str, tgt: str, bpe_size: Optional[int], need_chars: bool, bbpe_size: Optional[int], need_bytes: bool):
in_root = op.join(root, f'{src}-{tgt}')
for lang in [src, tgt]:
_convert_train(op.join(in_root, f'train.tags.{src}-{tgt}.{lang}'), op.join(root, f'train.{lang}'))... |
class AudioFinetuningConfig(AudioPretrainingConfig):
eval_wer: bool = field(default=False, metadata={'help': 'compute WER for Seq2Seq models'})
eval_wer_config: GenerationConfig = field(default_factory=(lambda : GenerationConfig()), metadata={'help': 'beam search config for evaluating wer during training'})
... |
def get_document_ids(source_docs, indexes):
indexes = sorted([(key, value[0], value[1]) for (key, value) in indexes.items()], key=(lambda x: x[0]))
doc_ids = []
for (i, partial_start, partial_end) in indexes:
try:
doc_ids.append((source_docs[i], partial_start, partial_end))
excep... |
def RI(sentence, alpha_ri, n_aug=9):
sentence = get_only_chars(sentence)
words = sentence.split(' ')
num_words = len(words)
augmented_sentences = []
n_ri = max(1, int((alpha_ri * num_words)))
for _ in range(n_aug):
a_words = random_addition(words, n_ri)
augmented_sentences.append... |
def ResNet18Compressed(channels):
return ResNetCompressed(BasicBlockCompressed, [2, 2, 2, 2], channels) |
_registry(operator_type='BinaryAdd')
class BinaryAdd(Operator):
def __init__(self):
super().__init__() |
def _to_py_obj(x):
if (x.lower() in ['true', 'yes', 'on']):
return True
if (x.lower() in ['false', 'no', 'off']):
return False
try:
obj = eval(x)
if (type(obj).__name__ in ['int', 'float', 'tuple', 'list', 'dict', 'NoneType']):
x = obj
except:
pass
... |
class Speedometer(object):
def __init__(self, batch_size, frequent=50, batches_per_epoch=None, epochs=None):
self.batch_size = batch_size
self.frequent = frequent
self.batches_per_epoch = batches_per_epoch
self.epochs = epochs
self.epoch = (- 1)
self.init = False
... |
def sample(nodeInfor, edgeInfor):
nodeId = [nodeInfor[i][0] for i in range(len(nodeInfor))]
longitude = [nodeInfor[i][1] for i in range(len(nodeInfor))]
latitude = [nodeInfor[i][2] for i in range(len(nodeInfor))]
n = len(nodeId)
A1 = np.array(([([0] * n)] * n))
Graph1 = nx.Graph(A1)
column =... |
def _relaunch():
log.warn('Relaunching...')
if (sys.argv[:3] == ['-c', 'install', '--single-version-externally-managed']):
sys.argv[0] = 'setup.py'
args = ([sys.executable] + sys.argv)
sys.exit(subprocess.call(args)) |
def find_program(basename):
names = [basename]
if (os.name == 'nt'):
extensions = ('.exe', '.bat', '.cmd', '.dll')
if (not basename.endswith(extensions)):
names = ([(basename + ext) for ext in extensions] + [basename])
for name in names:
path = is_program_installed(name)
... |
class Dataset(object):
def __init__(self):
self._instances = []
def add_instance(self, propertyDict):
self._instances.append(propertyDict)
def get_phraselist(self):
return [instance['phrase'] for instance in self._instances]
def get_imagelist(self):
return [instance['imag... |
def main(args):
from benchmark.models.musichubert_hf.extract_bert_features import main as extract_hubert_features_main
from benchmark.models.music2vec.extract_music2vec_features import main as extract_data2vec_features_main
from benchmark.models.data2vec.extract_data2vec_features import main as extract_data... |
class SegmentationModuleBase(nn.Module):
def __init__(self):
super(SegmentationModuleBase, self).__init__()
def pixel_acc(self, pred, label):
(_, preds) = torch.max(pred, dim=1)
valid = (label >= 0).long()
acc_sum = torch.sum((valid * (preds == label).long()))
pixel_sum =... |
class MultipleChoiceQuestion(NamedTuple):
stem: str
choices: List[Choice]
id_: str = None
answerKey: str = None
def from_jsonl(line: str) -> 'MultipleChoiceQuestion':
blob = json.loads(line)
question = blob['question']
return MultipleChoiceQuestion(id_=blob['id'], stem=questi... |
class FlaxRobertaModel(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax']) |
class MaskFromDensePoseSampler():
def __call__(self, instances: Instances) -> BitMasks:
return ToMaskConverter.convert(instances.pred_densepose, instances.pred_boxes, instances.image_size) |
def _calc_dynamic_intervals(start_interval, dynamic_interval_list):
assert mmcv.is_list_of(dynamic_interval_list, tuple)
dynamic_milestones = [0]
dynamic_milestones.extend([dynamic_interval[0] for dynamic_interval in dynamic_interval_list])
dynamic_intervals = [start_interval]
dynamic_intervals.exte... |
def read_txt_file(path):
with open(path, 'r') as f:
lists = f.read().splitlines()
lists = [s.strip().split(' ') for s in lists]
return lists |
def get_preprocessing(name, is_training=False):
preprocessing_fn_map = {'resnet_v1_152': resnet_preprocessing, 'mobilenet_v1': mobilenet_preprocessing}
if (name not in preprocessing_fn_map):
raise ValueError(('Preprocessing name [%s] was not recognized' % name))
def preprocessing_fn(image, output_he... |
def _data_augmentation(image, label, bbox, data_augmentation_args):
print('Use data_augmentation_args: ', data_augmentation_args)
if data_augmentation_args['crop_bbox']:
sample_distorted_bounding_box = tf.image.sample_distorted_bounding_box(tf.shape(image), bounding_boxes=bbox, min_object_covered=0.1, a... |
class LogScheduler(LRScheduler):
def __init__(self, optimizer, start_lr=0.03, end_lr=0.0005, epochs=50, last_epoch=(- 1), **kwargs):
self.start_lr = start_lr
self.end_lr = end_lr
self.epochs = epochs
self.lr_spaces = np.logspace(math.log10(start_lr), math.log10(end_lr), epochs)
... |
class SepConvOp(nn.Module):
def __init__(self, C_in, C_out, kernel_size, act_op, affine=True):
super(SepConvOp, self).__init__()
padding = PADDING_OPS[kernel_size]
kernel_size = KERNEL_SIZE_OPS[kernel_size]
activation = ACTIVATION_OPS[act_op]
if (not activation):
... |
class ArgMaxParameter(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _ARGMAXPARAMETER |
def discretized_mix_logistic_topk(means, logscales, logit_probs, range, bin_size, lower, upper, topk=1) -> Tuple[(torch.Tensor, torch.LongTensor)]:
eps = 1e-12
means = means.unsqueeze(1)
logscales = logscales.unsqueeze(1)
logit_probs = logit_probs.unsqueeze(1)
x = torch.arange((- range), (range + 1)... |
def controled_step(short_memory, long_memory, selected_instruction, current_paras, request: gr.Request):
if (current_paras == ''):
return ('', '', '', '', '', '')
global _CACHE
cookie = request.headers['cookie']
cookie = cookie.split('; _gat_gtag')[0]
cache = _CACHE[cookie]
if ('writer' ... |
class MishActivation(nn.Module):
def __init__(self):
super().__init__()
if (version.parse(version.parse(torch.__version__).base_version) < version.parse('1.9')):
self.act = self._mish_python
else:
self.act = nn.functional.mish
def _mish_python(self, input: Tensor)... |
def rmdir(path: str) -> None:
if path.startswith('s3'):
invalidOperationError(False, 'not implement')
elif path.startswith('hdfs://'):
cmd = 'hdfs dfs -rm -r {}'.format(path)
result = subprocess.getstatusoutput(cmd)
if (result[0] != 0):
invalidOperationError(False, re... |
class TFEsmModel(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def move(src_path: str, tgt_path, suffix: str, split_name: str, url):
os.mkdir(os.path.join(tgt_path, split_name))
os.mkdir(os.path.join(tgt_path, split_name, 'doc'))
os.mkdir(os.path.join(tgt_path, split_name, 'abs'))
with open(url, 'r', encoding='utf-8') as fd:
lines = fd.read().splitlines()
... |
class ResnetBlock(nn.Module):
def __init__(self, dim, dilation=1, use_spectral_norm=False):
super(ResnetBlock, self).__init__()
self.conv_block = nn.Sequential(nn.ReflectionPad2d(dilation), spectral_norm(nn.Conv2d(in_channels=dim, out_channels=dim, kernel_size=3, padding=0, dilation=dilation, bias=(... |
def exportfile(newAudio, time1, time2, filename, i):
newAudio2 = newAudio[time1:time2]
g = os.listdir()
if ((((filename[0:(- 4)] + '_') + str(i)) + '.wav') in g):
filename2 = ((str(uuid.uuid4()) + '_segment') + '.wav')
print(('making %s' % filename2))
newAudio2.export(filename2, form... |
def label_file_from_coordinates(nifti_image, coord_list):
imsh = list(np.array(nifti_image.dataobj).shape)
label_array = np.zeros(tuple(imsh))
for j in range(len(coord_list)):
label_array[(coord_list[j][0], coord_list[j][1], coord_list[j][2])] = 1
nib_pred = nib.Nifti1Image(dataobj=label_array, ... |
class BeitImageProcessor(BaseImageProcessor):
model_input_names = ['pixel_values']
def __init__(self, do_resize: bool=True, size: Dict[(str, int)]=None, resample: PILImageResampling=PILImageResampling.BICUBIC, do_center_crop: bool=True, crop_size: Dict[(str, int)]=None, rescale_factor: Union[(int, float)]=(1 / ... |
def test_sanitize_date_range_bad_start_dt() -> None:
with pytest.raises(ValueError) as ex_info:
sanitize_date_range('INVALID', '2020-06-06')
assert (str(ex_info.value) == 'Incorrect data format, should be YYYY-MM-DD') |
def extract_answers(solver, data_path):
answers = []
best_choices = []
num_corrects = 0
with open(data_path, 'r') as f:
for (idx, line) in enumerate(f):
question = MultipleChoiceQuestion.from_jsonl_ours(line, idx)
answer = solver.answer_question(question)
answ... |
def compare_files(gold_file, pred_file, up_ignore_layer=0):
(gold_entity, pred_entity, match_entity) = get_matched_ner_from_file(gold_file, pred_file, up_ignore_layer)
match_num = len(match_entity)
gold_num = len(gold_entity)
pred_num = len(pred_entity)
return get_final_score(gold_num, pred_num, mat... |
def count_model_param_flops(model=None, dataset=None, multiply_adds=True, full=False):
prods = {}
def save_hook(name):
def hook_per(self, input, output):
prods[name] = np.prod(input[0].shape)
return hook_per
list_1 = []
def simple_hook(self, input, output):
list_1.app... |
def classify(info, gold, test):
coord_tags = ['CC']
info['classified_type'] = ('UNSET ' + info['type'])
if value_present(info, ['type'], ['move']):
if ('start left siblings' in info):
if ((len(info['start left siblings']) > 0) and (info['start left siblings'][(- 1)] in coord_tags)):
... |
('l2_side')
class TFL2SideBoxRegularizer(TFBoxRegularizer):
def __init__(self, weight: float, log_scale: bool=False, reduction: str='sum') -> None:
super().__init__(weight, log_scale=log_scale, reduction=reduction)
def _forward(self, box_tensor: TFBoxTensor) -> tf.Tensor:
return tf_l2_side_regul... |
def get_optimizer(model):
parameters = _get_paramters(model)
opt_lower = cfg.SOLVER.OPTIMIZER.lower()
if (opt_lower == 'sgd'):
optimizer = optim.SGD(parameters, lr=cfg.SOLVER.LR, momentum=cfg.SOLVER.MOMENTUM, weight_decay=cfg.SOLVER.WEIGHT_DECAY)
elif (opt_lower == 'adam'):
optimizer = o... |
class ConvBlock(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=3, add_bias=True, scale_factor=1, filtering_kernel=(1, 3, 3, 1), use_wscale=True, wscale_gain=_WSCALE_GAIN, lr_mul=1.0, activation_type='lrelu', minibatch_std_group_size=0, minibatch_std_channels=1):
super().__init__()
... |
def test_simple_creation() -> None:
tensor = tf.constant(np.random.rand(3, 2, 3))
box_tensor = TFBoxTensor(tensor)
assert (tensor.numpy() == box_tensor.data.numpy()).all()
assert isinstance(box_tensor, TFBoxTensor)
tensor = tf.constant(np.random.rand(2, 10))
box_tensor = TFBoxTensor(tensor)
... |
def process_images(files):
for file in tqdm(files, mininterval=10):
if ('.jpg' in file):
continue
try:
im = Image.open(file)
process_one_img(file, im)
except:
print(file) |
class StackedConvLayers(nn.Module):
def __init__(self, input_feature_channels, output_feature_channels, num_convs, conv_op=nn.Conv2d, conv_kwargs=None, norm_op=nn.BatchNorm2d, norm_op_kwargs=None, dropout_op=nn.Dropout2d, dropout_op_kwargs=None, nonlin=nn.LeakyReLU, nonlin_kwargs=None, first_stride=None, basic_bloc... |
_module()
class LCLDataset(MInstrDataset):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, placeholders=(IMAGE_PLACEHOLDER, EXPR_PLACEHOLDER))
self.data = self._get_annos(self.filename)
self.cls_neg_label = None
self.cls_idx = None
self.cls_name = None
... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
(model_args, data_args, training_args) = parser.parse_args_into_dataclasses()
configure_logger(model_args, training_args)
datasets = load_dataset(data_args.dataset_name, data_args.dataset_config_name, cache... |
def eye_like(x: Tensor, /) -> Tensor:
ndim = x.ndim
if (ndim < 2):
raise ValueError(f'Input must have at least two dimensions! Got "{ndim}"')
(n, n2) = (x.shape[(- 2)], x.shape[(- 1)])
if (n != n2):
raise ValueError(f'Input last two dimensions must be square (*, n, n)! Got "{x.shape}"')
... |
class LibrispeechASR(datasets.GeneratorBasedBuilder):
DEFAULT_WRITER_BATCH_SIZE = 256
DEFAULT_CONFIG_NAME = 'all'
BUILDER_CONFIGS = [LibrispeechASRConfig(name='clean', description="'Clean' speech."), LibrispeechASRConfig(name='other', description="'Other', more challenging, speech."), LibrispeechASRConfig(n... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.