code stringlengths 101 5.91M |
|---|
def create_Y(instances=1000, categs=5, seed=0):
rs = np.random.RandomState(seed)
size = (instances, 1)
Y = rs.randint(0, categs, size=size)
return Y |
class SN(object):
def __init__(self, num_svs, num_itrs, num_outputs, transpose=False, eps=1e-12):
self.num_itrs = num_itrs
self.num_svs = num_svs
self.transpose = transpose
self.eps = eps
for i in range(self.num_svs):
self.register_buffer(('u%d' % i), torch.randn(... |
_end_docstrings(CUSTOM_DPR_READER_DOCSTRING)
class DPRReaderTokenizerFast(CustomDPRReaderTokenizerMixin, BertTokenizerFast):
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = READER_PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
pretrain... |
def test_kernel_expand():
k = fk.Carls_Mauna_kernel()
k_expanded = grammar.expand_kernels(1, [k])
assert (len(k_expanded) > 1) |
def any(t: TensorType, axis: Optional[AxisAxes]=None, keepdims: bool=False) -> TensorType:
return t.any(axis=axis, keepdims=keepdims) |
_module()
class BoxFormatProcess(BaseTargetProcessFunc):
def __call__(self, raw_conv: List[Dict[(str, Any)]], target: Dict[(str, Any)], preprocessor: Dict[(str, Any)], multimage_mode=False) -> Tuple[(List[Dict[(str, Any)]], Dict[(str, Any)])]:
box_formatter = preprocessor['target']['boxes']
if multi... |
def mm_covisible_tri(h_lrgp, tri_ids_tar, tri_ids_src):
batch_size = h_lrgp.batch_size
tri_ids_tar = tf.reshape(tri_ids_tar, [(- 1)])
ver_ids_tar = tf.gather(h_lrgp.h_fore.mesh_tri, tri_ids_tar)
ver_ids_tar = tf.reshape(ver_ids_tar, [batch_size, (- 1)])
tri_ids_src = tf.reshape(tri_ids_src, [batch_s... |
def validate_pytorch_loss(loss):
import types
if isinstance(loss, str):
if (loss in PYTORCH_LOSS_NAMES):
return getattr(torch.nn.modules, loss)()
invalidInputError(False, f'Must provide a valid torch loss name among {PYTORCH_LOSS_NAMES}')
if (isinstance(loss, torch.nn.modules.los... |
def run_command(command):
result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True, shell=True)
return result.stdout.strip() |
def imputation_performance(ori_x, imputed_x, m, metric_name):
assert (metric_name in ['mae', 'mse', 'rmse'])
(no, seq_len, dim) = ori_x.shape
ori_x = np.reshape(ori_x, [(no * seq_len), dim])
imputed_x = np.reshape(imputed_x, [(no * seq_len), dim])
m = np.reshape(m, [(no * seq_len), dim])
if (met... |
def total_yngve_depth(yngve_tree_root):
tot_score = 0
for leaf in yngve_tree_root.leaves:
tot_score += leaf.score
return tot_score |
def append_suffix(prefix, path):
splits = path.split('.')
if (len(splits) > 0):
file_name = ((prefix + '.') + splits[(- 1)])
else:
file_name = prefix
return file_name |
def pyramidnet164_a270_bn_svhn(num_classes=10, **kwargs):
return get_pyramidnet_cifar(num_classes=num_classes, blocks=164, alpha=270, bottleneck=True, model_name='pyramidnet164_a270_bn_svhn', **kwargs) |
def process_browsing_train(browsing_train_path):
print('Processing {}'.format(browsing_train_path))
df = read_from_parquet(browsing_train_path, limit=1000000)
df = df[['session_id_hash', 'event_type', 'product_action', 'server_timestamp_epoch_ms']]
df['product_action'].fillna(value='', inplace=True)
... |
def StandardIni(L=4, t=1, U=4, nelec=4, TwoSz=0, J=1, Model='"Fermion Hubbard"'):
Info = {}
Info['L'] = L
Info['model'] = Model
Info['method'] = '"Lanczos"'
Info['lattice'] = '"chain"'
if (Model == '"Fermion Hubbard"'):
Info['t'] = t
Info['U'] = U
Info['nelec'] = nelec
... |
def image_to_pixmap(image):
b = BytesIO()
utils.enlarge_image(Image.fromarray(image), scale_factor=2).save(b, format='PNG')
return QtGui.QPixmap.fromImage(QtGui.QImage.fromData(b.getvalue())) |
def test_lookup_symbol_simple():
run_cell('x = y = 42')
run_cell("assert lift(x).readable_name == 'x'")
run_cell("assert lift(y).readable_name == 'y'") |
def vectorize_force(f):
ndim = len(getfullargspec(f).args)
signature = ','.join((['()'] * ndim))
signature += '->(N)'
vec_f = np.vectorize(f, signature=signature)
def new_func(*args):
return np.rollaxis(vec_f(*args), axis=(- 1), start=0)
return new_func |
def count_convtranspose2d(m, x, y):
x = x[0]
cin = m.in_channels
cout = m.out_channels
(kh, kw) = m.kernel_size
out_h = y.size(2)
out_w = y.size(3)
kernel_ops = ((((multiply_adds * kh) * kw) * cin) // m.groups)
bias_ops = (1 if (m.bias is not None) else 0)
ops_per_element = (kernel_o... |
class EdgeBlock(nn.Module):
def __init__(self, in_chs, out_chs, kernel_size=3, stride=1, dilation=(1, 1), bottle_ratio=1.0, group_size=None, downsample='avg', linear_out=False, layers: LayerFn=None, drop_block=None, drop_path_rate=0.0):
super(EdgeBlock, self).__init__()
layers = (layers or LayerFn()... |
def validate(val_loader, model, criterion, args):
batch_time = AverageMeter('Time', ':6.3f')
losses = AverageMeter('Loss', ':.4e')
top1 = AverageMeter('', ':6.2f')
top5 = AverageMeter('', ':6.2f')
progress = ProgressMeter(len(val_loader), batch_time, losses, top1, top5, prefix='Test: ')
with tor... |
_start_docstrings('Roberta Model with a multiple choice classification head on top (a linear layer on top of\n the pooled output and a softmax) e.g. for RocStories/SWAG tasks. ', XLM_ROBERTA_START_DOCSTRING)
class TFXLMRobertaForMultipleChoice(TFRobertaForMultipleChoice):
config_class = XLMRobertaConfig |
def jsonify_lists(vals):
if (len(vals) != 0):
if isinstance(vals[0], float):
for (idx, val) in enumerate(vals):
if isnan(val):
vals[idx] = 'nan'
elif (val == np.inf):
vals[idx] = '+inf'
elif (val == (- np.inf... |
class TFGPT2ForSequenceClassification():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def CHECKDIM(tensor, dim, val):
if (type(tensor) == list):
for t in tensor:
CHECKDIM(t, dim, val)
else:
assert (len(tensor.shape) >= dim), 'expect {} to have {} dim shape {}'.format(tensor.shape, dim, val)
assert (tensor.shape[dim] == val), 'expect {} to have {} dim shape {}'... |
def _decode(buffer_, enc_byte):
size = sum((((256 ** ((enc_byte - i) - 1)) * buffer_[i].item()) for i in range(enc_byte)))
bytes_list = bytes(buffer_[enc_byte:(enc_byte + size)].tolist())
shift = (size + enc_byte)
return (bytes_list, shift) |
def main() -> None:
parser = argparse.ArgumentParser(prog=config.PACKAGE_NAME, description='Netloc investigation')
parser.add_argument('--config-path', required=True, help='Configuration file path, e.g. /some/dir/config.yaml')
instance_config_path = Path(parser.parse_args().config_path)
log.debug('Readi... |
def extract_poses(vid_file: Path, new_fps: int):
video = cv2.VideoCapture(vid_file.as_posix())
fps = int(video.get(cv2.CAP_PROP_FPS))
print(f'Video FPS: {fps}')
(success, image) = video.read()
frames = []
while success:
frames.append(image)
(success, image) = video.read()
pos... |
def gpt_palm_completion(messages, temperature, model):
backoff_time = 1
while True:
try:
return palm.chat(messages=messages, temperature=temperature, model=model)
except:
print(f' Sleeping {backoff_time} seconds...')
time.sleep(backoff_time)
backof... |
def beamsearch_hp(datapath, benchmark, backbone, thres, alpha, logpath, candidate_base, candidate_layers, beamsize, maxdepth):
device = torch.device(('cuda:0' if torch.cuda.is_available() else 'cpu'))
model = hpflow.HyperpixelFlow(backbone, '0', benchmark, device)
download.download_dataset(os.path.abspath(d... |
def main():
from .profile_func import profile_slimmable_models
print(f'profile model GFLOPs (forward complexity) and size (#param)')
model = SlimmableAlexNet(track_running_stats=False, bn_type='bn', share_affine=False)
model.eval()
print(f"model {model.__class__.__name__} on {('training' if model.tr... |
class CIDErEvalCap():
def __init__(self, gts, res, df):
print('tokenization...')
tokenizer = PTBTokenizer('gts')
_gts = tokenizer.tokenize(gts)
print('tokenized refs')
tokenizer = PTBTokenizer('res')
_res = tokenizer.tokenize(res)
print('tokenized cands')
... |
_model
def repvgg_b3g4(pretrained=False, **kwargs):
return _create_byobnet('repvgg_b3g4', pretrained=pretrained, **kwargs) |
def infinite_iter(iterable):
it = iter(iterable)
while True:
try:
ret = next(it)
(yield ret)
except StopIteration:
it = iter(iterable) |
class Glove(vcb.Vocab):
def __init__(self, fname):
super().__init__()
if (fname is not None):
self.read_vectors(fname)
else:
self.dim = 0
def read_vectors(self, fname):
glove = []
print('Loading glove vectors')
with open(fname) as f:
... |
class GaussianNoise(ZooKerasLayer):
def __init__(self, sigma, input_shape=None, **kwargs):
super(GaussianNoise, self).__init__(None, float(sigma), (list(input_shape) if input_shape else None), **kwargs) |
def simxQuery(clientID, signalName, signalValue, retSignalName, timeOutInMs):
retSignalLength = ct.c_int()
retSignalValue = ct.POINTER(ct.c_ubyte)()
sigV = signalValue
if (sys.version_info[0] == 3):
if (type(signalName) is str):
signalName = signalName.encode('utf-8')
if (typ... |
def sample(a=[], temperature=1.0):
b = np.copy(a)
try:
if (temperature == 1):
return np.argmax(np.random.multinomial(1, a, 1))
if (temperature is None):
return np.argmax(a)
else:
a = (np.log(a) / temperature)
a = (np.exp(a) / np.sum(np.exp(... |
class Predict(Subcommand):
def add_subparser(self, name: str, parser: argparse._SubParsersAction) -> argparse.ArgumentParser:
description = 'Run the specified model against a JSON-lines input file.'
subparser = parser.add_parser(name, description=description, help='Use a trained model to make predic... |
def vgg(cfg, batch_norm=False):
layers = []
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
elif (v == 'C'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2, ceil_mode=True)]
else:
conv2d = nn.Conv2d(i... |
def densenet169(pretrained=False, **kwargs):
model = DenseNet(num_init_features=64, growth_rate=32, block_config=(6, 12, 32, 32), **kwargs)
if pretrained:
pattern = re.compile('^(.*denselayer\\d+\\.(?:norm|relu|conv))\\.((?:[12])\\.(?:weight|bias|running_mean|running_var))$')
state_dict = model_... |
_module()
class HRNet(BaseModule):
blocks_dict = {'BASIC': BasicBlock, 'BOTTLENECK': Bottleneck}
def __init__(self, extra, in_channels=3, conv_cfg=None, norm_cfg=dict(type='BN', requires_grad=True), norm_eval=False, with_cp=False, frozen_stages=(- 1), zero_init_residual=False, multiscale_output=True, pretrained... |
def clean_how2sign_vocabulary(path_to_data_sentencelevel):
partition = ['train', 'val', 'test']
print(f'loading: {path_to_data_sentencelevel[partition[0]]}')
data = load_h2s(path_to_data_sentencelevel['train'])
corrected_sentences = []
mpn = MosesPunctNormalizer()
mt = MosesTokenizer(lang='en')
... |
def _all_broadcastable(*shapes):
for (i, shape1) in enumerate(shapes[:(- 1)]):
for shape2 in shapes[(i + 1):]:
if (not _broadcastable(shape1, shape2)):
return False
return True |
class LoggingCallback(pl.Callback):
def on_batch_end(self, trainer, pl_module):
lr_scheduler = trainer.lr_schedulers[0]['scheduler']
lrs = {f'lr_group_{i}': lr for (i, lr) in enumerate(lr_scheduler.get_lr())}
pl_module.logger.log_metrics(lrs)
def on_validation_end(self, trainer: pl.Train... |
def select(sequence, iobs):
for (label, iob) in zip(sequence, iobs):
if (iob in 'BI'):
(yield label) |
class RoFormerForTokenClassification(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def save_features(dataset: Dataset, saving_path: (str | Path), features: dict[(int, dict[(int, Tensor)])], filename: str, make_zip: bool) -> None:
saving_path = Path(saving_path)
for video_index in features:
video_path = (saving_path / str(dataset.get_video_metadata(video_index)['video_name']))
... |
def main(opt):
result_dir = os.path.dirname(opt['model.model_path'])
trace_file = os.path.join(result_dir, 'trace.txt')
trace_vals = load_trace(trace_file)
best_epoch = trace_vals['val']['loss'].argmin()
model_opt_file = os.path.join(os.path.dirname(opt['model.model_path']), 'opt.json')
with ope... |
def prune_outside_window(boxlist, window, scope=None):
with tf.name_scope(scope, 'PruneOutsideWindow'):
(y_min, x_min, y_max, x_max) = tf.split(value=boxlist.get(), num_or_size_splits=4, axis=1)
(win_y_min, win_x_min, win_y_max, win_x_max) = tf.unstack(window)
coordinate_violations = tf.conc... |
def flat_nested_json_dict(json_dict, sep='.') -> dict:
flatted = {}
for (k, v) in json_dict.items():
if isinstance(v, dict):
_flat_nested_json_dict(v, flatted, sep, str(k))
else:
flatted[str(k)] = v
return flatted |
class DroneClass(ABC):
def __init__(self, p: bullet_client.BulletClient, start_pos: np.ndarray, start_orn: np.ndarray, control_hz: int, physics_hz: int, drone_model: str, model_dir: (None | str)=None, np_random: (None | np.random.RandomState)=None):
if ((physics_hz % control_hz) != 0):
raise Val... |
_module()
class SmoothL1Loss(nn.Module):
def __init__(self, beta=1.0, reduction='mean', loss_weight=1.0):
super(SmoothL1Loss, self).__init__()
self.beta = beta
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target, weight=None, avg_factor=None, ... |
class Conversions():
def convert_directions_to_degree_lat_lon(data, latitude: Text, longitude: Text):
def decimal_degree_to_decimal(col):
if (col[latitude][(- 1):] == 'N'):
col[latitude] = float(col[latitude][:(- 1)])
else:
col[latitude] = (float(col[l... |
class MNIST_MLP(nn.Module):
def __init__(self, num_classes):
super(MNIST_MLP, self).__init__()
self.layers = nn.ModuleList()
self.layers.append(nn.Linear((28 * 28), 500))
self.layers.append(nn.Linear(500, 500))
self.layers.append(nn.Linear(500, num_classes))
def forward(s... |
def get_img_path(img_name, voc12_root):
if (not isinstance(img_name, str)):
img_name = decode_int_filename(img_name)
return os.path.join(voc12_root, IMG_FOLDER_NAME, (img_name + '.jpg')) |
def main(config):
random.seed(config.seed)
np.random.seed(config.seed)
torch.manual_seed(config.seed)
device = torch.device(config.device)
source_classes = label_utils.get_classes(cfg.source.split('/')[0], combine_spring_and_winter=cfg.combine_spring_and_winter)
source_data = PixelSetData(cfg.da... |
def parse_cl():
import argparse
parser = argparse.ArgumentParser(description='Converts a given gate-level verilog to a blif.')
parser.add_argument('-i', action='store', dest='src_v', required=True)
parser.add_argument('-o', action='store', dest='dest_blif', default='out.blif')
parser.add_argument('-... |
def test_example(capsys, example_test):
(ex, call, out) = example_test
ex.run_commandline(call)
(captured_out, captured_err) = capsys.readouterr()
print(captured_out)
print(captured_err)
captured_out = captured_out.split('\n')
captured_err = captured_err.split('\n')
for out_line in out:
... |
def sentence_noise(sentence, p_max=MAX_SENTENCE):
words = sentence.split(' ')
for p in random.sample(SENTENCE_NOISE_TYPES, SENTENCE_MIN_LEN):
repeat_num = p.repeat_num
while True:
if (repeat_num == 0):
break
if (len(words) >= SENTENCE_MIN_LEN):
... |
class AutoModelForObjectDetection(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class RL2Env(gym.Wrapper):
def __init__(self, env):
super().__init__(env)
action_space = akro.from_gym(self.env.action_space)
observation_space = self._create_rl2_obs_space()
self._spec = EnvSpec(action_space=action_space, observation_space=observation_space)
def _create_rl2_obs_... |
def main():
state = VehicleState()
state.x.x = 1
state.x.y = 2
state.e.psi = (np.pi / 4)
vehicle_body = VehicleBody()
(fig, ax) = plt.subplots(1)
rect = RectangleObstacle(xc=state.x.x, yc=state.x.y, w=vehicle_body.l, h=vehicle_body.w, psi=state.e.psi)
rect.plot_pyplot(ax)
circles = v... |
class GenerationConfig(FairseqDataclass):
beam: int = field(default=5, metadata={'help': 'beam size'})
nbest: int = field(default=1, metadata={'help': 'number of hypotheses to output'})
max_len_a: float = field(default=0, metadata={'help': 'generate sequences of maximum length ax + b, where x is the source ... |
def sleep_long(secs: (int | float)) -> None:
max_secs =
if (secs <= max_secs):
time.sleep(secs)
else:
while (secs > 0):
sleep_time = min(secs, max_secs)
time.sleep(sleep_time)
secs -= max_secs |
class SuperglueMultiRCProcessor(DataProcessor):
def __init__(self):
super().__init__()
self.labels = ['No', 'Yes']
def get_examples(self, data_dir, split):
if ((split == 'valid') or (split == 'dev')):
split = 'validation'
try:
dataset = load_dataset(path=H... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--model', required=True, help='sentencepiece model to use for decoding')
parser.add_argument('--input', required=True, help='input file to decode')
parser.add_argument('--input_format', choices=['piece', 'id'], default='piece')
args... |
def adjust_learning_rate(optimizer, epoch, args, learning_rate):
if (args.lradj == 'type1'):
lr_adjust = {epoch: (learning_rate * (0.5 ** ((epoch - 1) // 1)))}
elif (args.lradj == 'type2'):
lr_adjust = {2: 5e-05, 4: 1e-05, 6: 5e-06, 8: 1e-06, 10: 5e-07, 15: 1e-07, 20: 5e-08}
elif (args.lradj... |
def print_results(res):
for (k, l) in res.items():
for e in l:
print(k, ':', e[0], ' ', e[1]) |
class SampleGeneratorFaceXSeg(SampleGeneratorBase):
def __init__(self, paths, debug=False, batch_size=1, resolution=256, face_type=None, generators_count=4, data_format='NHWC', **kwargs):
super().__init__(debug, batch_size)
self.initialized = False
samples = sum([SampleLoader.load(SampleType... |
class BatchData(ProxyDataFlow):
def __init__(self, ds, batch_size, remainder=False):
super(BatchData, self).__init__(ds)
if (not remainder):
try:
s = ds.size()
assert (batch_size <= ds.size())
except NotImplementedError:
pass
... |
class VAE(nn.Module):
def __init__(self, prior_dist, likelihood_dist, post_dist, enc, dec, params):
super(VAE, self).__init__()
self.pz = prior_dist
self.px_z = likelihood_dist
self.qz_x = post_dist
self.enc = enc
self.dec = dec
self.modelName = None
s... |
class ExperimentPlanner3DFabiansResUNet_v21(ExperimentPlanner3D_v21):
def __init__(self, folder_with_cropped_data, preprocessed_output_folder):
super(ExperimentPlanner3DFabiansResUNet_v21, self).__init__(folder_with_cropped_data, preprocessed_output_folder)
self.data_identifier = 'nnUNetData_plans_v... |
class TestEditDistance(unittest.TestCase):
def test_editdistance(self):
import editdistance
self.assertEqual(2, editdistance.eval('abc', 'aec'))
self.assertEqual(np.asarray([[2, 3], [1, 2]], dtype='int64').tolist(), editdistance.eval_all(['ab', 'abc'], ['bc', 'bcd']).tolist())
def test_t... |
class RepoCreateCommand(BaseUserCommand):
def run(self):
print(ANSI.red('WARNING! Managing repositories through transformers-cli is deprecated. Please use `huggingface-cli` instead.'))
token = HfFolder.get_token()
if (token is None):
print('Not logged in')
exit(1)
... |
class DgSampledSequenceBuilder(Generic[X]):
timestamps: list[Timestamp] = field(default_factory=list)
values: list[X] = field(default_factory=list)
sampled_sequence_type: DgSampledSequenceType = DgSampledSequence
def add(self, t: Timestamp, v: X):
if self.timestamps:
if (t <= self.ti... |
class DeadlockChecker():
def __init__(self):
pass
def reset(self, env):
self._is_deadlocked = np.zeros(len(env.agents))
self._is_far_deadlocked = np.zeros(len(env.agents))
self._old_deadlock = np.zeros(len(env.agents))
self.env = env
self.agent_positions = default... |
class XLMRobertaOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task == 'multiple-choice'):
dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
dynamic_axis = {0: 'batch', 1: 'sequence'}
return OrderedDict([('input_i... |
def tile_worker(c: List[int], args: SimpleNamespace) -> Optional[Union[(str, Dict)]]:
if args.has_segmentation:
(c, tile_mask) = c
((x, y, grid_x), grid_y) = (c, 0)
else:
tile_mask = None
(x, y, grid_x, grid_y) = c
x_coord = int((x + (args.full_extract_px / 2)))
y_coord =... |
class CommonConfig(FairseqDataclass):
no_progress_bar: bool = field(default=False, metadata={'help': 'disable progress bar'})
log_interval: int = field(default=100, metadata={'help': 'log progress every N batches (when progress bar is disabled)'})
log_format: Optional[LOG_FORMAT_CHOICES] = field(default=Non... |
def boundaries_to_intervals(boundaries):
intervals = []
j_prev = 0
for j in np.where(boundaries)[0]:
intervals.append((j_prev, (j + 1)))
j_prev = (j + 1)
return intervals |
class DenseNet(nn.Module):
def __init__(self, block_config, num_classes=10, growth_rate=12, compression=1.0):
self.block_config = block_config
self.n_classes = num_classes
self.growth_rate = growth_rate
self.compression = compression
assert (0 < self.compression <= 1), '0 < c... |
class BaseRoIHead(nn.Module, metaclass=ABCMeta):
def __init__(self, bbox_roi_extractor=None, bbox_head=None, mask_roi_extractor=None, mask_head=None, shared_head=None, train_cfg=None, test_cfg=None):
super(BaseRoIHead, self).__init__()
self.train_cfg = train_cfg
self.test_cfg = test_cfg
... |
class Discriminator():
def __init__(self, patch_size, kernel_size=3):
self.patch_size = patch_size
self.kernel_size = kernel_size
self.block_param = {}
self.block_param['filters'] = (64, 128, 128, 256, 256, 512, 512)
self.block_param['strides'] = (2, 1, 2, 1, 1, 1, 1)
... |
def masked_mean(mask: torch.Tensor, value: torch.Tensor, dim: int, eps: float=0.0001) -> torch.Tensor:
mask = mask.expand(*value.shape)
return (torch.sum((mask * value), dim=dim) / (eps + torch.sum(mask, dim=dim))) |
def assert_proba_distribution(probabilities, tol=1e-05):
assert (((probabilities.sum() - 1.0).abs() < tol) and (probabilities >= 0).all()), 'tensor was expected to be a proability distribution (sum={}, negatives={})'.format(probabilities.sum(), (probabilities < 0).any()) |
(scope='module')
def all_explanations():
all_explainers = get_all_explainers()
data = synthetic_classification()
binary_model = RandomForestClassifier()
binary_model.fit(data['train']['X'], data['train']['y'])
regression_model = RandomForestRegressor()
regression_model.fit(data['train']['X'], da... |
def get_anchors_idx(mol):
anchors_idx = []
for atom in mol.GetAtoms():
if (atom.GetProp('_Anchor') == '1'):
anchors_idx.append(atom.GetIdx())
return anchors_idx |
class TestClass():
def __init__(self, int_arg, list_arg=None, dict_arg=None, extra_arg=None):
self.int_arg = int_arg
self.list_arg = list_arg
self.dict_arg = dict_arg
self.extra_arg = extra_arg
def __call__(self, call_arg):
return (call_arg + self.int_arg) |
def button(label, width=0, enabled=True):
with grayed_out((not enabled)):
clicked = imgui.button(label, width=width)
clicked = (clicked and enabled)
return clicked |
def config(dataset, use_baseline):
assert (not use_baseline), 'Cannot use baseline model for this config'
return {'pure_cond_affine': False, 'dequantize': False, 'batch_norm': False, 'act_norm': False, 'max_epochs': 2000, 'max_grad_norm': None, 'early_stopping': True, 'max_bad_valid_epochs': 50, 'train_batch_si... |
def test_inference_multi_modality_detector():
if (not torch.cuda.is_available()):
pytest.skip('test requires GPU and torch+cuda')
pcd = 'tests/data/sunrgbd/points/000001.bin'
img = 'tests/data/sunrgbd/sunrgbd_trainval/image/000001.jpg'
ann_file = 'tests/data/sunrgbd/sunrgbd_infos.pkl'
detect... |
def feature_loss(fmap_r, fmap_g):
loss = 0
for (dr, dg) in zip(fmap_r, fmap_g):
for (rl, gl) in zip(dr, dg):
loss += torch.mean(torch.abs((rl - gl)))
return (loss * 2) |
def eval_time_fct():
global poly_class_instances, input_list
for (instance, input) in zip(poly_class_instances, input_list):
instance.eval(input) |
def get_parent(node, all_parents=False):
if (node.inputs() is None):
return None
elif (len(list(node.inputs())) == 0):
return None
if (not all_parents):
return list(node.inputs())[0].node()
else:
return list(node.inputs()) |
class MaskBasedCorrectionReader(Reader):
def __init__(self, labels, test):
super().__init__(labels, test)
self.db = FEVERDocumentDatabase('resources/wikipedia/fever.db')
self.using_pipeline = False
self.using_gold = False
def generate_instances(self, instance):
if ((insta... |
class TestNetSpec(unittest.TestCase):
def load_net(self, net_proto):
f = tempfile.NamedTemporaryFile(mode='w+', delete=False)
f.write(str(net_proto))
f.close()
return caffe.Net(f.name, caffe.TEST)
def test_lenet(self):
net_proto = lenet(50)
self.assertEqual(net_pr... |
class GAPSF(object):
def __init__(self, args):
self.result_dir = args.result_dir
self.dataset = args.dataset
self.datasetpath = args.datasetpath
self.n_res = args.n_res
self.ch = args.ch
self.img_size = args.img_size
self.have_gt = args.have_gt
print('... |
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
return DenseConv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=dilation, groups=groups, use_bias=False, dilation=dilation) |
class T5Tokenizer(metaclass=DummyObject):
_backends = ['sentencepiece']
def __init__(self, *args, **kwargs):
requires_backends(self, ['sentencepiece']) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.