code stringlengths 101 5.91M |
|---|
def test_digits_greedi_ln():
model = MaxCoverageSelection(100, optimizer='greedi', optimizer_kwds={'optimizer1': 'lazy', 'optimizer2': 'naive'}, random_state=0)
model.fit(X_digits)
assert_array_equal(model.ranking[:2], digits_greedi_ranking[:2])
assert_array_almost_equal(model.gains[:2], digits_greedi_g... |
def test_digits_cosine_greedi_ln_object():
model = SaturatedCoverageSelection(100, 'cosine', optimizer=GreeDi(optimizer1='lazy', optimizer2='naive', random_state=0))
model.fit(X_digits)
assert_array_equal(model.ranking[:2], digits_cosine_greedi_ranking[:2])
assert_array_almost_equal(model.gains[:2], dig... |
class TFElectraForQuestionAnswering(metaclass=DummyObject):
_backends = ['tf']
def __init__(self, *args, **kwargs):
requires_backends(self, ['tf']) |
def diapreresnet1001_cifar10(num_classes=10, **kwargs):
return get_diapreresnet_cifar(num_classes=num_classes, blocks=1001, bottleneck=True, model_name='diapreresnet1001_cifar10', **kwargs) |
def generate_corpus_4_elmo_test():
print('')
dataset_dir = os.path.join('C:\\Data\\NLP-corpus\\PHEME-dataset', 'pheme_training')
print(os.path.exists(dataset_dir))
all_test_dataset_path = load_files_from_dataset_dir(dataset_dir)
all_events = {'charliehebdo', 'ebola-essien', 'ferguson', 'germanwings'... |
class Param():
def __init__(self):
self.parser = argparse.ArgumentParser(description='')
self.parser.add_argument('--iters', type=int, default=100000)
self.parser.add_argument('--name', type=str, default='default')
self.parser.add_argument('--train', type=str, default='speaker')
... |
class Nima():
def __init__(self, base_model_name, n_classes=10, learning_rate=0.001, dropout_rate=0, loss=earth_movers_distance, decay=0, weights='imagenet'):
self.n_classes = n_classes
self.base_model_name = base_model_name
self.learning_rate = learning_rate
self.dropout_rate = drop... |
def get_mv_mean_var(param_tuple):
data = {(('dataset', 'object'), ('views', 6), ('resolution', 128), ('trans', (- 1.4)), ('size', 1), ('normalize', False), ('norm_pc', True)): [(0., 0.0615424), (0., 0.), (0., 0.), (0.044222, 0.)], (('dataset', 'modelnet'), ('views', 6), ('resolution', 128), ('trans', (- 1.4)), ('si... |
_module
class TTAReformat(object):
def __init__(self, cfg, **kwargs):
self.tta_flag = cfg.get('tta_flag', False)
self.num_tta_tranforms = cfg.get('num_tta_tranforms', (- 1))
def __call__(self, res, info):
meta = res['metadata']
points = res['lidar']['points']
voxels = res... |
class JamesSteinEncoderTransformer(AutotabularPreprocessingAlgorithm):
def __init__(self, cols=None, random_state: Optional[np.random.RandomState]=None):
self.cols = cols
self.random_state = random_state
def fit(self, X: PIPELINE_DATA_DTYPE, y: Optional[PIPELINE_DATA_DTYPE]=None) -> 'JamesSteinE... |
class TarDataset(Dataset):
def __init__(self, archive, transform=to_tensor, extensions=('.png', '.jpg', '.jpeg'), is_valid_file=None):
if (not isinstance(archive, TarDataset)):
worker = get_worker_info()
worker = (worker.id if worker else None)
self.tar_obj = {worker: tar... |
def dsrla_mobilenetv2_k6_eca(eca=True):
print('Constructing dsrla_mobilenetv2_k6_eca......')
model = dsRLA_MobileNetV2(rla_channel=6, ECA=eca)
return model |
def test_loader_func(config, batch_size):
(_, test_loader, _) = load_dataset(config['data_dir'], batch_size)
return test_loader |
_model
def resnetv2_101x3_bitm_in21k(pretrained=False, **kwargs):
return _create_resnetv2('resnetv2_101x3_bitm_in21k', pretrained=pretrained, num_classes=kwargs.pop('num_classes', 21843), layers=[3, 4, 23, 3], width_factor=3, stem_type='fixed', **kwargs) |
class TestStat(BasePythonTest):
def test_return_value(self):
la_str = 'a b\n where\n a: scalar\n b: scalar'
func_info = self.gen_func_info(la_str)
self.assertEqual(func_info.numpy_func(3, 2).ret, 6)
if TEST_MATLAB:
mat_func = getattr(mat_engine, func_... |
class _MultiHeadAttention(nn.Module):
def __init__(self, d_k, d_v, d_model, n_heads, dropout):
super(_MultiHeadAttention, self).__init__()
self.d_k = d_k
self.d_v = d_v
self.d_model = d_model
self.n_heads = n_heads
self.w_q = Linear([d_model, (d_k * n_heads)])
... |
def main():
parser = argparse.ArgumentParser(description='PyTorch Object Detection Webcam Demo')
parser.add_argument('--config-file', default='../configs/caffe2/e2e_mask_rcnn_R_50_FPN_1x_caffe2.yaml', metavar='FILE', help='path to config file')
parser.add_argument('--confidence-threshold', type=float, defau... |
def train(train_loader, model, criterion, optimizer, epoch, use_cuda):
model.train()
torch.set_grad_enabled(True)
batch_time = AverageMeter()
data_time = AverageMeter()
losses = AverageMeter()
top1 = AverageMeter()
top5 = AverageMeter()
end = time.time()
bar = Bar('Processing', max=l... |
def Backbone_ResNeXt50_in3():
net = l_resnext50(pretrained=True)
div_2 = nn.Sequential(*list(net.children())[:3])
div_4 = nn.Sequential(*list(net.children())[3:5])
div_8 = net.layer2
div_16 = net.layer3
div_32 = net.layer4
return (div_2, div_4, div_8, div_16, div_32) |
class SVI_Base(nn.Module):
def __init__(self, weight_shape, bias_shape, variational_distribution, prior, use_bias):
super(SVI_Base, self).__init__()
self.data_type = torch.float32
self.weight_rhos = nn.Parameter(torch.empty(weight_shape, dtype=self.data_type))
self.weight_mus = nn.Pa... |
class MapImage(ImageAugmentor):
def __init__(self, func):
self.func = func
def _augment(self, img, _):
return self.func(img) |
class TestQuantization(unittest.TestCase):
def setUpClass(self):
self.constant_graph = build_fake_model()
self.test_graph = create_test_graph()
build_fake_yaml()
build_fake_yaml2()
def tearDownClass(self):
os.remove('fake_yaml.yaml')
os.remove('fake_yaml2.yaml')
... |
def load_embedding_npz(path):
data = np.load(path)
return ([w.decode('utf8') for w in data['words']], data['vals']) |
def find(x, parents):
while (parents[x] != x):
parent = parents[x]
parents[x] = parents[parent]
x = parent
return x |
class IntDescriptor(NumDescriptor):
def contains_value(self, val):
(low, high) = self.range
return (low <= val < high)
def sample(self):
(low, high) = self.range
return random.randint(low, (high - 1)) |
class ChannelGate(nn.Module):
def __init__(self, channels, reduction_ratio=16, num_layers=1):
super(ChannelGate, self).__init__()
mid_channels = (channels // reduction_ratio)
self.pool = nn.AdaptiveAvgPool2d(output_size=(1, 1))
self.init_fc = DenseBlock(in_features=channels, out_feat... |
def row_logloss(row, model):
y = np.array([row['A'], row['B'], row['N']]).reshape(1, (- 1))
pred = np.array([row[(model + '-A')], row[(model + '-B')], row[(model + '-N')]]).reshape(1, (- 1))
return log_loss(y, pred) |
def get_count_matrix(args, file_path):
global DOC2IDX
doc_ids = {}
doc_metas = {}
nan_cnt = 0
for filename in sorted(os.listdir(file_path)):
print(filename)
with open(os.path.join(file_path, filename), 'r') as f:
articles = json.load(f)['data']
for article in ... |
_function('flip')
class AutogradFlip(AutogradFunction):
def forward(ctx, input, dims):
ctx.save_for_backward(dims)
return input.flip(dims)
def backward(ctx, grad_output):
(dims,) = ctx.saved_tensors
return grad_output.flip(dims) |
def default_init_weights(module, scale=1):
for m in module.modules():
if isinstance(m, nn.Conv2d):
kaiming_init(m, a=0, mode='fan_in', bias=0)
m.weight.data *= scale
elif isinstance(m, nn.Linear):
kaiming_init(m, a=0, mode='fan_in', bias=0)
m.weight.da... |
def parse_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('--input_model', type=str, required=False, default='ssd-12.onnx')
parser.add_argument('--output_model', type=str, required=True)
return parser.parse_args() |
class GATZinc(nn.Module):
def __init__(self, g, num_layers, in_dim, num_hidden, heads, activation, feat_drop, attn_drop, negative_slope, residual, num_atom_type, num_bond_type):
super(GATZinc, self).__init__()
self.g = g
self.num_layers = num_layers
self.gat_layers = nn.ModuleList()
... |
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsample=None, previous_dilation=1):
super().__init__()
self.conv1 = nn.Conv2d(inplanes, planes, 1, bias=False)
self.bn1 = norm_layer(planes)
self.conv2 = nn.Conv2d(planes, pla... |
class TokenizerTesterMixin():
tokenizer_class = None
rust_tokenizer_class = None
test_rust_tokenizer = False
space_between_special_tokens = False
from_pretrained_kwargs = None
from_pretrained_filter = None
from_pretrained_vocab_key = 'vocab_file'
def setUp(self) -> None:
if self.... |
_registry(dataset_type='CIFAR10', framework='onnxrt_qlinearops, onnxrt_integerops', dataset_format='')
class CIFAR10(Dataset):
url = '
filename = 'cifar-10-python.tar.gz'
tgz_md5 = 'c58f30108f718f92721af3b95e74349a'
train_list = [['data_batch_1', 'c99cafc152244af753f735de768cd75f'], ... |
def get_SVs(net, prefix):
d = net.state_dict()
return {('%s_%s' % (prefix, key)).replace('.', '_'): float(d[key].item()) for key in d if ('sv' in key)} |
class MobileViTFeatureExtractor(MobileViTImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class MobileViTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use MobileViTImageProcessor instead.', FutureWarning)
super().__init__(*arg... |
class IndexInitializer(trackable_base.Trackable):
def __init__(self, filename, name=None):
self._name = name
self._filename_arg = filename
self._filename = self._track_trackable(trackable.TrackableAsset(filename), '_filename')
def _shared_name(self):
shared_name = ('index_%s' % s... |
def _count_class_sample(y):
(unique, counts) = np.unique(y, return_counts=True)
return dict(zip(unique, counts)) |
def var_binned(t, y, w, freq, nbins, linterp=True):
ypred = binned_pdm_model(t, y, w, freq, nbins, linterp=linterp)(((t * freq) % 1.0))
return np.dot(w, np.power((y - ypred), 2)) |
class TestBaseDataset(unittest.TestCase):
def test_init_processors(self):
path = os.path.join(os.path.abspath(__file__), '../../../pythia/common/defaults/configs/datasets/vqa/vqa2.yml')
configuration = Configuration(os.path.abspath(path))
self._fix_configuration(configuration)
config... |
def add_to_freeze_collection(vars):
if (not isinstance(vars, (list, tuple))):
vars = [vars]
for v in vars:
tf.add_to_collection('freeze', v) |
def train_legacy_masked_language_model(data_dir, arch, extra_args=()):
train_parser = options.get_training_parser()
train_args = options.parse_args_and_arch(train_parser, (['--task', 'cross_lingual_lm', data_dir, '--arch', arch, '--optimizer', 'adam', '--lr-scheduler', 'reduce_lr_on_plateau', '--lr-shrink', '0.... |
def load_partition_data_cifar100(data_dir, partition_method, partition_alpha, client_number, batch_size, logger):
(X_train, y_train, X_test, y_test, net_dataidx_map, traindata_cls_counts) = partition_data(data_dir, partition_method, client_number, partition_alpha, logger=logger)
data_local_num_dict = dict()
... |
class Runner(object):
def __init__(self, cfg, metric, local_rank, sample_only=False):
self.local_rank = local_rank
self.cfg = cfg
self.best_modelpath = None
(self.last_msg_train, self.last_msg_eval, self.n_xid_train) = ('', '', 0)
self.img_size = data_helper.get_imgsize(cfg.d... |
class OurMultiheadAttention(nn.Module):
def __init__(self, q_feat_dim, k_feat_dim, out_feat_dim, n_head, d_k=None, d_v=None):
super(OurMultiheadAttention, self).__init__()
if (d_k is None):
d_k = (out_feat_dim // n_head)
if (d_v is None):
d_v = (out_feat_dim // n_head... |
.parametrize(**make_parametrize_kwargs(itertools.chain(places365(), caltech101(), caltech256(), cifar10(), cifar100(), mnist(), fashion_mnist(), kmnist(), emnist(), qmnist(), omniglot(), phototour(), sbdataset(), sbu(), semeion(), stl10(), svhn(), usps(), celeba(), widerface())))
def test_url_is_accessible(url, md5):
... |
def get_double_polynomial(idx, vrblvl=0):
if (vrblvl > 0):
print('in get_double_polynomial idx :', idx)
phc = get_phcfun()
adx = pointer(c_int32(idx))
bsz = pointer(c_int32(0))
ccc = pointer(c_double(0.0))
vrb = c_int32(vrblvl)
if (vrblvl > 0):
print('-> get_double_polynomial... |
def nms_gpu(boxes, scores, thresh, pre_maxsize=None, post_max_size=None):
order = scores.sort(0, descending=True)[1]
if (pre_maxsize is not None):
order = order[:pre_maxsize]
boxes = boxes[order].contiguous()
keep = torch.zeros(boxes.size(0), dtype=torch.long)
num_out = iou3d_cuda.nms_gpu(bo... |
_MASK_PREDICTOR.register('MaskRCNNC4Predictor')
class MaskRCNNC4Predictor(nn.Module):
def __init__(self, cfg, in_channels):
super(MaskRCNNC4Predictor, self).__init__()
num_classes = cfg.MODEL.ROI_BOX_HEAD.NUM_CLASSES
dim_reduced = cfg.MODEL.ROI_MASK_HEAD.CONV_LAYERS[(- 1)]
num_inputs... |
def normed(x, axis=None, keepdims=False):
eps = np.finfo(x.dtype).eps
return (x / (norm(x, axis=axis, keepdims=True) + eps)) |
class ReOutput(ModelOutput):
loss: Optional[torch.FloatTensor] = None
logits: torch.FloatTensor = None
hidden_states: Optional[Tuple[torch.FloatTensor]] = None
attentions: Optional[Tuple[torch.FloatTensor]] = None
entities: Optional[Dict] = None
relations: Optional[Dict] = None
pred_relation... |
def array_list_from_slog(x: SLArrayList) -> ArrayList:
return [array_from_slog(slog) for slog in x] |
class PreActBottleneck(nn.Module):
expansion = 4
def __init__(self, in_planes, planes, stride=1):
super(PreActBottleneck, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=1, bias=False)
self.bn2 = nn.BatchNorm2d(planes)
... |
class Ordinal():
DIGIT_MAP = {'1': 'one', '3': 'three', '-2': 'second', '-4': 'four', '-6': 'six'}
ORDINAL_MAP = {'first': '1', 'firstly': '1', 'second': '2', 'secondly': '2', 'twice': '2', 'ii': '2', 'third': '3', 'fourth': '4', 'fifth': '5', 'sixth': '6', 'seventh': '7', 'eighth': '8', 'ninth': '9', 'tenth': ... |
class GCN(torch.nn.Module):
def __init__(self, in_channels, hidden_channels, out_channels, num_layers, dropout):
super(GCN, self).__init__()
self.convs = torch.nn.ModuleList()
self.convs.append(GCNConv(in_channels, hidden_channels, normalize=False))
for _ in range((num_layers - 2)):
... |
_immediately
def allrank(gpu_queue, doc_begin_index, doc_end_index, finish_queue):
import os
import torch
gpuid = gpu_queue.get()
os.environ['CUDA_VISIBLE_DEVICES'] = f'{gpuid}'
device = torch.device(('cuda' if torch.cuda.is_available() else 'cpu'))
assert (torch.cuda.device_count() == 1)
(q... |
class PerceiverFeatureExtractor(metaclass=DummyObject):
_backends = ['vision']
def __init__(self, *args, **kwargs):
requires_backends(self, ['vision']) |
def remove_output(*sources: str) -> Iterator[None]:
try:
(yield)
finally:
for src in sources:
shutil.rmtree(src) |
def accuracy(output, target, topk=(1,)):
maxk = max(topk)
labeled_minibatch_size = max(target.ne(NO_LABEL).sum(), 1e-08)
(_, pred) = output.topk(maxk, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))
res = []
for k in topk:
correct_k = correct[:... |
class SegmentationLosses(object):
def __init__(self, weight=None, size_average=True, batch_average=True, ignore_index=255, cuda=False):
self.ignore_index = ignore_index
self.weight = weight
self.size_average = size_average
self.batch_average = batch_average
self.cuda = cuda
... |
class ResNet_Strategy(nn.Module):
def __init__(self, block, num_blocks, args):
self.args = args
super(ResNet_Strategy, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self... |
def main(args):
ii2s = Embedding(args)
im_path1 = os.path.join(args.input_dir, args.im_path1)
im_path2 = os.path.join(args.input_dir, args.im_path2)
im_path3 = os.path.join(args.input_dir, args.im_path3)
im_set = {im_path1, im_path2, im_path3}
ii2s.invert_images_in_W([*im_set])
ii2s.invert_i... |
def evaluate(result_sha, root, part='all', mail=mailpy.Mail('')):
mail.msg('Processing Result for KITTI Tracking Benchmark')
classes = []
for c in ('car', 'pedestrian'):
e = trackingEvaluation(t_sha=result_sha, root=root, part=part, mail=mail, cls=c)
try:
if (not e.loadTracker())... |
class Layer(JavaValue, SharedStaticUtils):
def __init__(self, jvalue, bigdl_type, *args):
if jvalue:
invalidInputError((type(jvalue) == JavaObject), f"jvalue type ${type(jvalue)} doesn't match JavaObject ${JavaObject}")
self.value = jvalue
else:
self.value = callB... |
def shape_equal_cmp(*args):
for i in range((len(args) - 1)):
if (args[i].shape != args[(i + 1)].shape):
s = '\n'.join([str(x.shape) for x in args])
raise ValueError(('Expected equal shapes. Got:\n%s' % s))
return True |
class ACE2005Processor(QueryNERProcessor):
def get_labels(self):
return ['GPE', 'ORG', 'PER', 'FAC', 'VEH', 'LOC', 'WEA', 'O'] |
class InceptionV4(nn.Module):
def __init__(self, num_classes=1000, in_chans=3, output_stride=32, drop_rate=0.0, global_pool='avg'):
super(InceptionV4, self).__init__()
assert (output_stride == 32)
self.drop_rate = drop_rate
self.num_classes = num_classes
self.num_features = 1... |
class BestRun(NamedTuple):
run_id: str
objective: float
hyperparameters: Dict[(str, Any)] |
class FlaxCrossAttnDownBlock2D(nn.Module):
in_channels: int
out_channels: int
dropout: float = 0.0
num_layers: int = 1
num_attention_heads: int = 1
add_downsample: bool = True
use_linear_projection: bool = False
only_cross_attention: bool = False
use_memory_efficient_attention: bool ... |
def add_flops_counter_variable_or_reset(module):
if (isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.Linear)):
module.__flops__ = 0 |
class MyNanoChannelsLastCorrectness(TorchNano):
def train(self):
x = torch.Tensor([[[[1, 0]], [[1, 0]]], [[[1, 0]], [[2, 0]]], [[[0, 3]], [[1, 0]]], [[[1, 1]], [[2, 1]]]])
y = torch.Tensor([[0.0], [1.0], [0.0], [1.0]])
train_dataset = torch.utils.data.TensorDataset(x, y)
train_loader... |
def val_to_vec(size, val):
assert (0 <= val < size)
vec = [0 for _ in range(size)]
vec[int(val)] = 1
return vec |
def copy_noise_bn(noised_src_model, dst_model, diff_coef=0.0):
assert (diff_coef == 0), 'Not support non-zero diff_coef since no clean ref is available.'
found_bn = False
eps = 1e-10
for key in dst_model.state_dict():
if ('bn' in key):
found_bn = True
if (('running_mean' ... |
class PlaneActiveSchedulerND(_SubspacePointActiveSchedulerND):
name = 'Plane'
def __init__(self, N_STEPS, D, point, iaxes):
if (D.nd < 3):
raise Exception('ERROR: requires nd >=3')
if (len(point) != (D.nd - 2)):
raise Exception(('ERROR: point incorrect shape %s' % (point.... |
class DeepONet(NN):
def __init__(self, layer_sizes_branch, layer_sizes_trunk, activation, kernel_initializer, use_bias=True):
super().__init__()
self.layer_sizes_func = layer_sizes_branch
self.layer_sizes_loc = layer_sizes_trunk
if isinstance(activation, dict):
self.activ... |
def plot_prediction(model, row, window, exponentiate=False, predict_deaths=True):
if predict_deaths:
key = 'deaths'
else:
key = 'cases'
model_predictions = get_auto_reg_predictions(model, row, window, exponentiate, predict_deaths=predict_deaths)
model_predictions = [float(v) for v in mod... |
def load_traindata_path(dataset_dir, name):
train = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
validation = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
which_view = os.path.join(dataset_dir, name)
data_list = {}
data_list['train'] = []
data_list['val'] = []
for k in train:
subject_id = os.path.joi... |
class CorrelatedBBTS(Agent):
def __init__(self, n_stages, mu0, sigma0, sigma_tilde, n_sweeps=10):
assert ((n_stages % 2) == 0)
self.n_stages = n_stages
self.n_sweeps = n_sweeps
self.internal_env = CorrelatedBinomialBridge(n_stages, mu0, sigma0)
self.edge2index = defaultdict(d... |
def product_dict(**kwargs):
keys = kwargs.keys()
vals = kwargs.values()
for instance in itertools.product(*vals):
(yield dict(zip(keys, instance))) |
class FE(nn.Module):
def __init__(self, in_channels, mid_channels):
super().__init__()
self.fe = nn.Sequential(*[CB(in_channels), MCB(in_channels, mid_channels, offset_channels=32)])
def forward(self, x):
out = self.fe(x)
return out |
class XSegNet(object):
VERSION = 1
def __init__(self, name, resolution=256, load_weights=True, weights_file_root=None, training=False, place_model_on_cpu=False, run_on_cpu=False, optimizer=None, data_format='NHWC', raise_on_no_model_files=False):
self.resolution = resolution
self.weights_file_ro... |
class CIFAR10V2_auto(object):
def __init__(self, batch_size=128, class_balance=False, imb_factor=None):
mean = [0.4914, 0.4822, 0.4465]
std = [0.2023, 0.1994, 0.201]
normalize = transforms.Normalize(mean, std)
transform_train = transforms.Compose([transforms.RandomCrop(32, padding=4)... |
def test_iou_piecewise_sampler():
if (not torch.cuda.is_available()):
pytest.skip()
assigner = MaxIoUAssigner(pos_iou_thr=0.55, neg_iou_thr=0.55, min_pos_iou=0.55, ignore_iof_thr=(- 1), iou_calculator=dict(type='BboxOverlaps3D', coordinate='lidar'))
bboxes = torch.tensor([[32, 32, 16, 8, 38, 42, (- ... |
def _build_humanoid_walls_env():
walker = walkers.CMUHumanoidPositionControlled(name='walker', observable_options={'egocentric_camera': dict(enabled=True)})
wall_width = distributions.Uniform(low=1, high=7)
wall_height = distributions.Uniform(low=2.5, high=4.0)
swap_wall_side = distributions.Bernoulli(p... |
def ideal_binary_mask(args, mix, sources):
mix_stft = librosa.stft(mix, n_fft=args.nfft, hop_length=args.nhop)
(mix_mag, mix_phase) = librosa.magphase(mix_stft, power=1)
source_1_stft = librosa.stft(sources[0], n_fft=args.nfft, hop_length=args.nhop)
(source_1_mag, source_1_phase) = librosa.magphase(sour... |
def _bf16_wrapper_model(model, bf16_ops_list, prefix=''):
for (name, child) in model.named_children():
op_name = (((prefix + '.') + name) if (prefix != '') else name)
for bf16_op_name in bf16_ops_list:
if (op_name == bf16_op_name[0]):
child = BF16ModuleWrapper(child)
... |
def test_sigmar_wlog_constbeta():
from galpy.potential import LogarithmicHaloPotential
lp = LogarithmicHaloPotential(normalize=1.0, q=1.0)
rs = numpy.linspace(0.001, 5.0, 101)
assert numpy.all((numpy.fabs((numpy.array([jeans.sigmar(lp, r) for r in rs]) - (1.0 / numpy.sqrt(2.0)))) < 1e-10)), 'Radial sigm... |
def get_pretrained_model(destination):
url = ' arbitrary_style_transfer.tar.gz'
os.system('curl -o arbitrary_style_transfer.tar.gz {0}'.format(url))
with tarfile.open('arbitrary_style_transfer.tar.gz') as tar:
if (not os.path.exists(destination)):
os.makedirs(destination)
... |
(kernels.SharedIndependent, inducing_variables.SharedIndependentInducingVariables, TensorLike, TensorLike)
def _exact_shared(kern, Z, u, f, *, multioutput_axis=None, **kwargs):
return _exact_independent(kern, Z, u, f, multioutput_axis=multioutput_axis, **kwargs) |
def full_run(input_doc):
print('Started full run')
print(len(input_doc._.Features[0]))
input_doc = variance_threshold(input_doc, load=True)
print(len(input_doc._.Features[0]))
print('Variance Threshold Done')
scalers = ['QuantileGaussian']
jobs = []
for scaler in scalers:
print((... |
def reduction_b(net):
with tf.variable_scope('Branch_0'):
tower_conv = slim.conv2d(net, 256, 1, scope='Conv2d_0a_1x1')
tower_conv_1 = slim.conv2d(tower_conv, 384, 3, stride=2, padding='VALID', scope='Conv2d_1a_3x3')
with tf.variable_scope('Branch_1'):
tower_conv1 = slim.conv2d(net, 256, ... |
class SequentialRules():
def __init__(self, steps=10, weighting='div', pruning=20, last_n_days=None, idf_weight=False, session_key='SessionId', item_key='ItemId', time_key='Time'):
self.steps = steps
self.pruning = pruning
self.weighting = weighting
self.last_n_days = last_n_days
... |
def imagenet_resnet101_pretrained(output_dim):
return _replace_fc(torchvision.models.resnet101(pretrained=True), output_dim) |
class LogisticRegressionNetwork1(nn.Module):
def __init__(self, num_feature) -> None:
super().__init__()
self.dense = nn.Linear(num_feature, 1)
def forward(self, x):
x = self.dense(x)
return x |
def torch_abs(input, *, out=None):
if (out is not None):
raise ValueError("Don't support in-place abs for MetaTensor analysis")
return input |
class StandardNorm(nn.Module):
def __init__(self, mean, std):
super(StandardNorm, self).__init__()
self.mean = mean
self.std = std
def forward(self, x):
return ((x - self.mean) / self.std)
def inverse(self, x):
return ((x * self.std) + self.mean) |
class OpPattern(JsonSerializer):
def __init__(self, pattern_data: dict):
super().__init__()
self.sequence: List[str] = pattern_data.get('sequence', '').split(',')
self.precision: str = pattern_data.get('precision', None) |
class TestNode():
def __init__(self, nav, nn, actions):
self.tb3 = nav
self.desired_speed = 0.3
self.nn = nn
self.actions = actions
self.desired_position = PoseStamped()
self.desired_action = np.zeros((2,))
rospy.Timer(rospy.Duration(0.2), self.cbControl)
... |
class iVAE(nn.Module):
def __init__(self, latent_dim, data_dim, aux_dim, prior=None, decoder=None, encoder=None, n_layers=3, hidden_dim=50, activation='lrelu', slope=0.1, device='cpu', anneal=False):
super().__init__()
self.data_dim = data_dim
self.latent_dim = latent_dim
self.aux_di... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.