code stringlengths 101 5.91M |
|---|
def readIntsFile(filename):
with open(filename) as f:
array = []
for line in f:
if (line.startswith('%') or line.startswith('#')):
continue
if (len(line.split()) == 0):
continue
array.append([int(x) for x in line.split()])
r... |
class TFT5PreTrainedModel():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def multi_run_histories_summary(run_histories, save_filename=None, metrics='val_binary_accuracy', description_prefix='k_fold_average_', results_prefix='k_fold_results', multi_history_metrics='mean', verbose=1):
if isinstance(metrics, str):
metrics = [metrics]
if isinstance(multi_history_metrics, str):
... |
class TestLDHead(TestCase):
def test_ld_head_loss(self):
s = 256
img_metas = [{'img_shape': (s, s, 3), 'pad_shape': (s, s, 3), 'scale_factor': 1}]
train_cfg = Config(dict(assigner=dict(type='ATSSAssigner', topk=9, ignore_iof_thr=0.1), allowed_border=(- 1), pos_weight=(- 1), debug=False))
... |
class ModelCheckpoint(callbacks.ModelCheckpoint):
def __init__(self, filepath, monitor='val_loss', verbose=0, save_best_only=True, mode='auto', save_freq='epoch', **kwargs):
super(ModelCheckpoint, self).__init__(filepath=filepath, monitor=monitor, verbose=verbose, save_best_only=save_best_only, mode=mode, s... |
def unconvert_from_RGB_255(colors):
un_rgb_color = ((colors[0] / 255.0), (colors[1] / 255.0), (colors[2] / 255.0))
return un_rgb_color |
class Graph(JsonSerializer):
def __init__(self) -> None:
super().__init__()
self._nodes: Dict[(str, Node)] = {}
self._edges: List[Edge] = []
def add_node(self, node: Node) -> None:
self._nodes[node.id] = node
def nodes(self) -> List[Node]:
return list(self._nodes.valu... |
def calculate_activation_statistics_from_files(files, sess, batch_size=50, verbose=False):
act = get_activations_from_files(files, sess, batch_size, verbose)
mu = np.mean(act, axis=0)
sigma = np.cov(act, rowvar=False)
return (mu, sigma) |
class Fuse_fea(nn.Module):
def __init__(self):
super(Fuse_fea, self).__init__()
self.convt1 = nn.Conv3d(in_channels=96, out_channels=48, kernel_size=(3, 5, 5), stride=(1, 1, 1), padding=(1, 2, 2))
self.convt2 = nn.Conv3d(in_channels=48, out_channels=n_class, kernel_size=(3, 5, 5), stride=(1,... |
class SimpleCrossAttnUpBlock2DTests(UNetBlockTesterMixin, unittest.TestCase):
block_class = SimpleCrossAttnUpBlock2D
block_type = 'up'
def dummy_input(self):
return super().get_dummy_input(include_res_hidden_states_tuple=True, include_encoder_hidden_states=True)
def prepare_init_args_and_inputs_... |
def image_loader(path):
if isinstance(path, Path):
path = str(path.resolve())
return default_loader(path) |
class TestTwoStagePanopticSegmentor(unittest.TestCase):
def setUp(self):
register_all_modules()
def _create_model_cfg(self):
cfg_file = 'panoptic_fpn/panoptic-fpn_r50_fpn_1x_coco.py'
model_cfg = get_detector_cfg(cfg_file)
model_cfg.backbone.depth = 18
model_cfg.neck.in_ch... |
class SimpleEngine(Engine):
def __init__(self, run_function: Callable):
super().__init__(process_function=(lambda x, y: None))
self._allowed_events = [Events.STARTED, Events.COMPLETED]
self._run_function = run_function
def run(self, *args, **kwargs):
self._fire_event(Events.START... |
def split_dataset(fname, ind_arg):
with open(fname, 'r') as read_obj:
header = np.array(['ID', 'Pregnancies', 'Glucose', 'BloodPressure', 'SkinThickness', 'Insulin', 'BMI', 'DiabetesPedigreeFunction', 'Age', 'Outcome'])
ind_1 = ([0] + [(ind + 1) for ind in ind_arg])
ind_2 = ind_2 = ([0] + [i... |
def get_mask(mask_root, mask_paths, ignore_path, f_resize_length: Optional[int]=None):
rsize = (RESIZE_LENGTH if (f_resize_length is None) else f_resize_length)
mask_all_instances = []
for mask_path in mask_paths:
mask_file = os.path.join(mask_root, mask_path)
if os.path.isfile(mask_file):
... |
class TFTrainingArguments(TrainingArguments):
framework = 'tf'
tpu_name: Optional[str] = field(default=None, metadata={'help': 'Name of TPU'})
tpu_zone: Optional[str] = field(default=None, metadata={'help': 'Zone of TPU'})
gcp_project: Optional[str] = field(default=None, metadata={'help': 'Name of Cloud... |
.parametrize(['item', 'location', 'expected_space'], [(Item(2, 3, 4), Location(1, 4, 5), Space(x1=1, x2=3, y1=4, y2=7, z1=5, z2=9)), (Item(4, 1, 6), Location(10, 5, 3), Space(x1=10, x2=14, y1=5, y2=6, z1=3, z2=9))])
def test__space_from_item_and_location(item: Item, location: Location, expected_space: Space) -> None:
... |
def F_measure(preds, labels, openset=False, theta=None):
if openset:
true_pos = 0.0
false_pos = 0.0
false_neg = 0.0
for i in range(len(labels)):
true_pos += (1 if ((preds[i] == labels[i]) and (labels[i] != (- 1))) else 0)
false_pos += (1 if ((preds[i] != label... |
def convert_from_interleaved(args):
nargs = len(args)
arrays = []
inputs = []
for i in range(0, (nargs // 2)):
arrays.append(args[(2 * i)])
inputs.append(args[((2 * i) + 1)])
symbol_map = get_symbol_map(inputs)
eq = ','.join((''.join((symbol_map[ix] for ix in term)) for term in i... |
class PythonFormatter():
standard_header = '# \n# - Open3D: www.open3d.org -\n# \n# Copyright (c) 2018-2023 www.open3d.org\n# SPDX-License-Identifier: MIT\n# \n'
def __init__(self, file_paths, style_config):
self.file_paths = file_paths
self.styl... |
class Reshape(nn.Module):
def __init__(self, size):
super().__init__()
self.size = size
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.view(self.size) |
def greedy_search(gold, test, classify):
cur = (test.clone(), {'type': 'init'}, 0)
iters = 0
path = []
while True:
path.append(cur)
if (iters > 100):
return ((0, iters), None)
ctree = cur[0]
cerrors = parse_errors.ParseErrorSet(gold, ctree)
if (len(cer... |
def fast_walsh_hadamard_torched(x, axis=0, normalize=False):
orig_shape = x.size()
assert ((axis >= 0) and (axis < len(orig_shape))), ('For a vector of shape %s, axis must be in [0, %d] but it is %d' % (orig_shape, (len(orig_shape) - 1), axis))
h_dim = orig_shape[axis]
h_dim_exp = int(round((np.log(h_di... |
def analyze_ops(graph, print_info=False):
if print_info:
print('')
print('Operations: name -> (type shapes) [size]')
print('')
total_size = 0
for op in graph.get_operations():
op_size = 0
shapes = []
for output in op.outputs:
output_size = (output.... |
class MultiScaleInternal(Flow):
def __init__(self, flow_step, num_steps, in_channels, hidden_channels, h_channels, factor=2, transform='affine', prior_transform='affine', alpha=1.0, inverse=False, kernel_size=(2, 3), coupling_type='conv', h_type=None, activation='relu', normalize=None, num_groups=None):
sup... |
class ResNet(nn.Module):
def __init__(self, last_stride, block, layers, num_classes=1000):
scale = 64
self.inplanes = scale
super(ResNet, self).__init__()
self.conv1 = nn.Conv2d(3, scale, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = nn.InstanceNorm2d(scale, affi... |
_registry(pattern_type='TorchInnerProductInsertBias')
class TorchInnerProductInsertBias(Pattern):
def __call__(self, model):
if ((model.framework_modeling_config['framework'] != 'torch') or (not util.get_quant_info())):
return model
for node in model.nodes:
if (node.op_type =... |
def preprocessor(l):
pdb_fn = '_'.join(l.split('/')[(- 1)].split('.')[0].split('_')[:(- 2)])
key = pdb_fn.split('_')[0]
data_dir = './'
if os.path.exists(f'{data_dir}/{key}'):
return
ligand_pdb_fn = l
pdb_dir = '../../refined_set'
bs_pdb_fn = f'{pdb_dir}/{key}/{key}_protein.pdb'
... |
class BasicResidualBlock(nn.Module):
def __init__(self, in_planes, out_planes, kernel_size, props, stride=None):
super().__init__()
self.kernel_size = kernel_size
props['conv_op_kwargs']['stride'] = 1
self.stride = stride
self.props = props
self.out_planes = out_plane... |
class ProofStepClassificationDatasetCreator(DatasetCreator):
def __init__(self, fp):
super().__init__(fp)
self.seen = set()
def process_dp(self, dp):
(ts, positive_hyps) = get_proof_step_classification_datapoint(dp)
positive_hyps = tuple(map(to_type_annotation, positive_hyps))
... |
def make_seed():
d = 10000
t = time.time()
sub1 = (int((t * d)) % d)
sub2 = (int((t * (d ** 2))) % d)
s = 0.001
s_inv = (1.0 / s)
time.sleep(((s * sub2) / d))
t2 = time.time()
t2 = (t2 - int(t2))
t2 = (int(((t2 * d) * s_inv)) % d)
time.sleep(((s * sub1) / d))
t3 = time.ti... |
class DataReaderBase(object):
def from_opt(cls, opt):
return cls()
def _read_file(cls, path):
with open(path, 'rb') as f:
for line in f:
(yield line)
def _raise_missing_dep(*missing_deps):
raise MissingDependencyException(('Could not create reader. Be sure... |
def contrastive_loss(y_c: torch.Tensor, pred_dists: torch.Tensor, margin: int=1) -> torch.Tensor:
N = pred_dists.shape[0]
pull_losses = (y_c * torch.pow(pred_dists, 2))
zero = torch.zeros(N)
device = y_c.device
zero = zero.to(device)
clamped_dists = torch.max((margin - pred_dists), zero)
pus... |
class GroupsSimpleStationary(GroupsStationary):
monsters = Groups.monsters[:3]
modifiers = Groups.modifiers[:4] |
class DataTrainingArguments():
source_lang: str = field(default=None, metadata={'help': 'Source language id for translation.'})
target_lang: str = field(default=None, metadata={'help': 'Target language id for translation.'})
dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of th... |
def replace_attr(obj, name: str, value):
torch_attr = getattr(obj, name)
setattr(obj, name, value)
attrs.append((obj, name, torch_attr)) |
class GymEnvironment(BaseEnvironment):
def __init__(self, name: str, **kwargs):
import gym
self.name = name
self.environmet = gym.make(name)
self.action_space = self.environmet.action_space
self.action_num = self.action_space.n
self.shape = kwargs.get('shape', None)
... |
class FeedWrapper(object):
def __init__(self, feed, **kwargs):
assert isinstance(feed, torch.utils.data.DataLoader)
(self.feed, self.kwargs) = (feed, kwargs)
def __len__(self):
return len(self.feed)
def __iter__(self):
if (not self.kwargs):
(yield from iter(self.f... |
class LogConfusionMatrix(Callback):
def __init__(self):
self.preds = []
self.targets = []
self.ready = True
def on_sanity_check_start(self, trainer, pl_module) -> None:
self.ready = False
def on_sanity_check_end(self, trainer, pl_module):
self.ready = True
def on_... |
class TFXLNetForMultipleChoice():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
def apply_spectral_norm(m):
from torch.nn.utils import spectral_norm
for layer in m.modules():
if isinstance(layer, nn.Conv2d):
spectral_norm(layer)
elif isinstance(layer, nn.Linear):
spectral_norm(layer)
elif isinstance(layer, nn.Embedding):
spectral_... |
def loadMappableLayers(path):
path = os.path.join(path, 'compiled_partitions')
if (not os.path.exists(path)):
raise FileNotFoundError
filenames = [f for f in os.listdir(path) if (os.path.splitext(f)[1] == '.pickle')]
layers = {}
layerNames = []
with ThreadPoolExecutor() as executor:
... |
class EuclideanDistance(Distance):
def get_distance(self, list1: [], list2: []):
return distance.euclidean(list1, list2) |
class WorldRegistry():
_world_classes = {}
def get(cls, world_type: str) -> World:
try:
return cls._world_classes[world_type]
except KeyError:
raise ValueError(f'unknown world type for: {world_type}')
def register(cls, world_type: str):
def inner_wrapper(wrapp... |
def parse_messages(messages, functions):
if all(((m.role != 'user') for m in messages)):
raise HTTPException(status_code=400, detail=f'Invalid request: Expecting at least one user message.')
messages = copy.deepcopy(messages)
default_system = 'You are a helpful assistant.'
system = ''
if (me... |
class ClsAccuracy(EvalMetric):
def __init__(self, allreduce=False, num_replicas=1):
super(ClsAccuracy, self).__init__('ClsAcc', allreduce, num_replicas)
def update(self, outputs):
with torch.no_grad():
cls_logits = outputs['label_logits']
cls_pred = (cls_logits > 0).long(... |
def InverseBoxCoxL(num_blocks, **kwargs):
(set_res, addf0, init_random, constraint) = common_config(kwargs)
block_array = []
for nb in range(num_blocks):
if init_random:
(a_aff, b_aff) = numpy.random.randn(2)
init_lam = (numpy.random.randn(1) + 1.0)
else:
... |
def train_epoch(model, loader, criterion, optimizer, lr_scheduler, epoch, use_cuda=False):
model.train()
running_loss = 0.0
tic = timer()
for (i, (data, mask, pe, lap_pe, degree, labels)) in enumerate(loader):
if (args.warmup is not None):
iteration = ((epoch * len(loader)) + i)
... |
def is_mag(arg1: str) -> bool:
arg1_split = arg1.lower().split('x')
if ((len(arg1_split) != 2) or (arg1_split[1] != '')):
return False
try:
mag = float(arg1_split[0])
except ValueError:
return False
return True |
def get_onnx_model_list():
config_mapping = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING
model_names = config_mapping = transformers_module.models.auto.configuration_auto.MODEL_NAMES_MAPPING
onnx_model_types = [model_type for model_type in config_mapping.keys() if has_onnx(model_type)]
... |
class TestLayer(ZooTestCase):
def test_embedding(self):
input_data = np.random.randint(1000, size=(32, 10))
zlayer = ZLayer.Embedding(1000, 64, input_shape=(10,))
klayer = KLayer.Embedding(1000, 64, input_length=10)
self.compare_layer(klayer, zlayer, input_data, WeightsConverter.conv... |
def plmodel(**kwvars):
def registered_class(Cls):
objCls = obj(**kwvars)(Cls)
class PLAutoMdl(Cls):
def __init__(self, **kwargs):
self.kwargs = kwargs
self._lazyobj = objCls(**kwargs)
default_config = self._lazyobj.cs.get_default_configurat... |
class ATONet(nn.Module):
def __init__(self, opt):
super(ATONet, self).__init__()
fn = opt.feature_num
self.an = opt.angular_num
self.an2 = (self.an * self.an)
self.scale = opt.scale
self.fea_conv0 = nn.Conv2d(1, fn, 3, 1, 1, bias=True)
self.fea_resblock = make... |
class MyNano(TorchNano):
def train(self):
seed_everything(42)
model = MyPytorchModule()
optimizer = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9, weight_decay=0.0005)
loss_fuc = torch.nn.CrossEntropyLoss()
(train_loader, val_loader) = create_dataloaders()
... |
def is_torch_compile_available():
if (not is_torch_available()):
return False
import torch
return hasattr(torch, 'compile') |
def get_pyg_dataset(dataset=[], id_tag='jid', target='', neighbor_strategy='', atom_features='', use_canonize='', name='', line_graph='', cutoff=8.0, max_neighbors=12, classification=False, output_dir='.', tmp_name='dataset', use_lattice=False, use_angle=False, data_from='Jarvis', use_save=False, mean_train=None, std_t... |
class CubicQuad():
mul = 8
def __call__(t: Tensor) -> Tensor:
y_sup = (0.5 * (t ** 2))
y_inf = (((1 / 6) * ((t + 0.5).clamp(min=0) ** 3)) - (1 / 24))
return torch.where((t >= 0.5), y_sup, y_inf)
def tilde(: Tensor) -> Tensor:
y_sup =
y_inf = (torch.sqrt((2 * )) - 0.5... |
def pretty_print(res):
import numpy as np
pres = dict()
for (k, v) in res.items():
if tf.is_tensor(v):
pres[k] = f'{v.shape}, {v.dtype}, {np.average(v.numpy())}'
else:
pres[k] = v
print(pres)
return pres |
def get_entity_spans_finalize(input_sentences, output_sentences, redirections=None):
return_outputs = []
for (input_, output_) in zip(input_sentences, output_sentences):
input_ = (input_.replace('\xa0', ' ') + ' -')
output_ = (output_.replace('\xa0', ' ') + ' -')
entities = []
... |
def get_vgg(cut_idx=(- 1), vgg_type='pytorch'):
f = get_vanilla_vgg_features(cut_idx, vgg_type)
keys = [x for x in cnn._modules.keys()]
max_idx = max((keys.index(x) for x in opt_content['layers'].split(',')))
for k in keys[(max_idx + 1):]:
cnn._modules.pop(k)
return f |
class LinearMapper(object):
def __init__(self, in_bounds, out_bounds):
(self.in_min, in_max) = in_bounds
(self.out_min, out_max) = out_bounds
self.in_range = (in_max - self.in_min)
self.out_range = (out_max - self.out_min)
def convert(self, value):
return ((((value - self... |
class Timer(object):
def __init__(self):
self.total_time = 0.0
self.calls = 0
self.start_time = 0.0
self.diff = 0.0
self.average_time = 0.0
def tic(self):
self.start_time = time.time()
def toc(self, average=True):
self.diff = (time.time() - self.start_... |
class resnet_base(nn.Module):
def __init__(self):
super(resnet_base, self).__init__()
self.base = models.resnet101(pretrained=True)
def forward(self, x):
for (name, module) in self.base._modules.items():
if (name == 'avgpool'):
break
x = module(x)
... |
class ProcessPool(object):
def __init__(self, num_processes: int=None, interval_sec: int=0):
self.num_processes = (num_processes if (num_processes is not None) else os.cpu_count())
self.interval_sec = interval_sec
def map(self, *args, **kwargs):
return self.run(*args, **kwargs)
def r... |
def aspect_ratio_abs(im, aspect_ratio):
(im_h, im_w) = im.shape[:2]
im_area = (im_h * im_w)
im_ar_w = np.sqrt((im_area * aspect_ratio))
im_ar_h = np.sqrt((im_area / aspect_ratio))
assert np.isclose((im_ar_w / im_ar_h), aspect_ratio)
im_ar = cv2.resize(im, dsize=(int(im_ar_w), int(im_ar_h)))
... |
('cnn_lnlstm')
def cnn_lnlstm(nlstm=128, **conv_kwargs):
return cnn_lstm(nlstm, layer_norm=True, **conv_kwargs) |
.register('R-50-LPF')
def build_resnet_50_antialiased_backbone(cfg):
filter_size = 3
model = resnet_lpf.resnet50(cfg, filter_size=filter_size)
model.out_channels = cfg.MODEL.RESNETS.BACKBONE_OUT_CHANNELS
return model |
class BrainDataset(data.Dataset):
def __init__(self, df, transform=None):
self.df = df
self.transform = transform
def __len__(self):
return len(self.df)
def __getitem__(self, idx):
image = cv2.imread(self.df.iloc[(idx, 0)])
image = (np.array(image) / 255.0)
ma... |
def iters_schedule_grid_search(model, config, n_iter=6, betas_range=(1e-06, 0.01), test_batch_size=2, step=1, path_to_store_schedule=None, save_stats_for_grid=True, verbose=True, n_jobs=1):
device = next(model.parameters()).device
if ('cpu' in str(device)):
show_message('WARNING: running grid search on ... |
def parse_args():
import argparse
parser = argparse.ArgumentParser(description='PyTorch Embedding Learning')
parser.add_argument('--dataset-dir', default='/tmp/fmnist/', help='FashionMNIST dataset directory path')
parser.add_argument('-p', '--labels-per-batch', default=8, type=int, help='Number of uniqu... |
def sepreresnet56_cifar100(num_classes=100, **kwargs):
return get_sepreresnet_cifar(num_classes=num_classes, blocks=56, bottleneck=False, model_name='sepreresnet56_cifar100', **kwargs) |
class AbsCriterion(Criterion):
def __init__(self, size_average=True, bigdl_type='float'):
super(AbsCriterion, self).__init__(None, bigdl_type, size_average) |
class TrackEpochCallback(LearnerCallback):
_order = (- 20)
def __init__(self, learn: Learner, name: str='epoch', epoch_offset: int=None):
super().__init__(learn)
learn._test_writeable_path()
self.path = ((learn.path / learn.model_dir) / name)
if (epoch_offset is None):
... |
class autoencoder_vgg5(nn.Module):
def __init__(self):
super(autoencoder_vgg5, self).__init__()
self.encoder = models.vgg19(pretrained=True).features
self.decoder = nn.Sequential(nn.Conv2d(512, 512, 3, stride=1, padding=1), nn.ReLU(True), nn.Conv2d(512, 512, 3, stride=1, padding=1), nn.ReLU(... |
def main(_):
seed = 8964
tf.set_random_seed(seed)
np.random.seed(seed)
random.seed(seed)
print(' Arguments ')
for key in FLAGS.__flags.keys():
print('{}: {}'.format(key, getattr(FLAGS, key)))
print(' Arguments ')
if (not os.path.exists(FLAGS.checkpoint_dir)):
os.makedirs(... |
def count_parameters(model):
table = PrettyTable(['Modules', 'Parameters'])
total_params = 0
for (name, parameter) in model.named_parameters():
if (not parameter.requires_grad):
continue
param = parameter.numel()
table.add_row([name, param])
total_params += param
... |
def save_config(config, logdir=None):
if logdir:
with config.unlocked:
config.logdir = logdir
message = 'Start a new run and write summaries and checkpoints to {}.'
tf.logging.info(message.format(config.logdir))
tf.gfile.MakeDirs(config.logdir)
config_path = os.pa... |
def add_vae_arguments(parser):
for f in dataclasses.fields(Hyperparams):
kwargs = (dict(action='store_true') if ((f.type is bool) and (not f.default)) else dict(default=f.default, type=f.type))
parser.add_argument(f'--{f.name}', **kwargs, **f.metadata)
return parser |
def validate(args, model, criterion, device, val_dataloader, writer, epoch):
torch.set_grad_enabled(False)
model.eval()
total_loss = 0.0
correct = 0
for (i, data) in enumerate(val_dataloader):
(clips, idxs) = data
inputs = clips.to(device)
targets = idxs.to(device)
ou... |
def read_csv(path):
with open(path) as f1:
data = f1.readlines()[1:]
data = [line.split(', ') for line in data]
return data |
def IPOT_distance_torch_batch_uniform_T(C, bs, n, m, iteration=50):
C = C.float().cuda()
T = IPOT_torch_batch_uniform(C, bs, n, m, iteration=iteration)
return T |
.dataclass
class FlaxCausalLMOutputWithCrossAttentions(ModelOutput):
logits: jnp.ndarray = None
past_key_values: Optional[Tuple[Tuple[jnp.ndarray]]] = None
hidden_states: Optional[Tuple[jnp.ndarray]] = None
attentions: Optional[Tuple[jnp.ndarray]] = None
cross_attentions: Optional[Tuple[jnp.ndarray]... |
def double_newton_at_series(pols, lser, idx=1, maxdeg=4, nbr=4, checkin=True, vrblvl=0):
nbsym = number_of_symbols(pols)
if (vrblvl > 0):
print('the polynomials :')
for pol in pols:
print(pol)
print('Number of variables :', nbsym)
if checkin:
if (not checkin_newto... |
class Hamburger(nn.Module):
def __init__(self, ham_channels=512, ham_kwargs=dict(), norm_cfg=None):
super().__init__()
self.ham_in = ConvModule(ham_channels, ham_channels, 1, norm_cfg=None, act_cfg=None)
self.ham = NMF2D(ham_kwargs)
self.ham_out = ConvModule(ham_channels, ham_channel... |
def extract(fpath, dest_folder):
if fpath.endswith('.tar.gz'):
mode = 'r:gz'
elif fpath.endswith('.tar'):
mode = 'r:'
else:
raise IOError(('fpath has unknown extension: %s' % fpath))
with tarfile.open(fpath, mode) as tar:
members = tar.getmembers()
for member in t... |
def try_once(func):
def func_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
logging.info('ignore error \n{}'.format(str(e)))
print_trace()
return func_wrapper |
class ImageFolder(data.Dataset):
def __init__(self, imgDir, dataTransform, imgSize, isTrain):
self.imgDir = imgDir
sample3 = os.path.join(self.imgDir, '1_3.jpg')
self.cycle = (3 if os.path.exists(sample3) else 2)
self.nbImg = (len(os.listdir(self.imgDir)) // self.cycle)
self.... |
class RMBitbrain(RM):
def __init__(self, size_list, read_list, write_list):
super().__init__()
self.size_list = size_list
self.read_list = read_list
self.write_list = write_list
def ram(self):
size_list_count = ((self.container.env.interval - self.container.startAt) % len... |
def count_accuracy(B_bin_true, B_bin_est, check_input=False):
if check_input:
if (B_bin_est == (- 1)).any():
if (not (((B_bin_est == 0) | (B_bin_est == 1)) | (B_bin_est == (- 1))).all()):
raise ValueError('B_bin_est should take value in {0, 1, -1}.')
if ((B_bin_est ==... |
def _get_weight_shape(w):
with misc.suppress_tracer_warnings():
shape = [int(sz) for sz in w.shape]
misc.assert_shape(w, shape)
return shape |
def get_segment_waveform(path_or_fp, offset, n_frames, normalization=True):
if isinstance(path_or_fp, str):
ext = os.path.splitext(os.path.basename(path_or_fp))[1]
if (ext not in {'.flac', '.wav'}):
raise ValueError(f'Unsupported audio format: {ext}')
(waveform, sample_rate) = torcha... |
def expect_token(expected_item, seen_item, what_parsing):
if (seen_item != expected_item):
raise RuntimeError("parsing {0}, expected '{1}' but got '{2}'".format(what_parsing, expected_item, seen_item)) |
def plot_7_day_prediction_errors(metric, all_errors, all_dates):
plt.figure(figsize=(4, 3), dpi=200)
ax = plt.subplot(111)
for method in ['linear', 'advanced_shared_model', 'ensemble']:
if (method != 'ensemble'):
ax.plot(all_errors[method][7][::(- 1)], label=label_name[method], color=col... |
class FSMTForConditionalGeneration():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
def vgg(x, is_training, config, num_filters=32):
print(('Input: ' + str(x.get_shape)))
input_layer = tf.expand_dims(x, 3)
bn_input = tf.compat.v1.layers.batch_normalization(input_layer, training=is_training)
conv1 = tf.compat.v1.layers.conv2d(inputs=bn_input, filters=num_filters, kernel_size=[3, 3], pad... |
def test_classifier(P, model, loader, criterion, steps, logger=None):
metric_logger = MetricLogger(delimiter=' ')
if (logger is None):
log_ = print
else:
log_ = logger.log
mode = model.training
model.eval()
acc = 0.0
for (n, batch) in enumerate(loader):
if ((n * P.te... |
class Actor(nn.Module):
def __init__(self, in_dim, out_dim, hidden_size, layers, activation=nn.ReLU):
super().__init__()
self.feedforward_model = build_model(in_dim, out_dim, layers, hidden_size, activation)
def forward(self, state_features):
x = self.feedforward_model(state_features)
... |
def num_lines(filename):
try:
p = subprocess.check_output(['wc', '-l', filename])
return int(p.decode().strip().split()[0])
except subprocess.CalledProcessError as cpe:
quit(cpe.returncode) |
def test_link_func_mlogit():
predictions = np.array([[0.25, 0.625, 0.125], [0.5, 0.25, 1.25], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [1.0, np.nan, 0.0]])
expected = np.array([[(- 0.9162907), 0.0, (- 1.6094379)], [(- 0.9162907), (- 1.6094379), 0.0], [(- np.inf), (- np.inf), 0], [0, (- np.inf), (- np.inf)], [np.nan, n... |
def pitching_stats_bref(season: Optional[int]=None) -> pd.DataFrame:
if (season is None):
season = most_recent_season()
str_season = str(season)
start_dt = (str_season + '-03-01')
end_dt = (str_season + '-11-30')
return pitching_stats_range(start_dt, end_dt) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.