code stringlengths 101 5.91M |
|---|
class StableDiffusionControlNetPipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_... |
def test_actionset_from_uspto_line():
change_str = '11-14;11-13'
expected = {11, 13, 14}
actual = uspto_data.actionset_from_uspto_line(change_str)
assert (actual == expected) |
def create_mobilenetv2_ssd_lite_predictor(net, candidate_size=200, nms_method=None, sigma=0.5, device=torch.device('cpu')):
predictor = Predictor(net, config.image_size, config.image_mean, config.image_std, nms_method=nms_method, iou_threshold=config.iou_threshold, candidate_size=candidate_size, sigma=sigma, device... |
def convert_torchvision_ckpt_to_detectron2(ckpt_path) -> Dict[(str, Any)]:
assert os.path.exists(ckpt_path)
input_state_dict = torch.load(ckpt_path)
DETECTRON2_RENAME_MAPPING: Dict[(str, str)] = {'layer1': 'res2', 'layer2': 'res3', 'layer3': 'res4', 'layer4': 'res5', 'bn1': 'conv1.norm', 'bn2': 'conv2.norm'... |
def main():
args = get_args()
args.factor = (1.0 + (args.factor / 100.0))
if (not os.path.exists(args.dir)):
os.makedirs(args.dir)
utterances = read_kaldi_datadir(args.srcdir)
(start_dur, end_dur) = find_duration_range(utterances, args.coverage_factor)
logger.info('Durations in the range... |
def draw_worm(frame, skel, width):
body_color = np.linspace(WORM_BODY_COLOR_HEAD, WORM_BODY_COLOR_TAIL, (len(skel) - 1))
for (i, (pt1, pt2)) in enumerate(zip(skel[1:], skel[:(- 1)])):
cv2.line(frame, pt1=tuple(pt1.astype(int)), pt2=tuple(pt2.astype(int)), color=body_color[i], thickness=int(width)) |
class RejectionLogFromTable(RejectionLog):
def __init__(self, file):
super().__init__(file)
self.cols = None
self.names = None
self.comments = None
def initialize_rejection_log(self, forest):
self.cols = [[], []]
self.names = ['FOREST_SIZE', 'REJECTION_STATUS']
... |
def test_subscript_is_live():
(live, dead) = compute_live_dead_symbol_refs('foo[bar] = baz')
assert (live == {'foo', 'bar', 'baz'}) |
class ASPP_module(nn.Module):
def __init__(self, inplanes, planes, dilation):
super(ASPP_module, self).__init__()
if (dilation == 1):
kernel_size = 1
padding = 0
else:
kernel_size = 3
padding = dilation
self.atrous_convolution = nn.Conv... |
class VanMlpLayer(nn.Module):
def __init__(self, in_channels: int, hidden_size: int, out_channels: int, hidden_act: str='gelu', dropout_rate: float=0.5):
super().__init__()
self.in_dense = nn.Conv2d(in_channels, hidden_size, kernel_size=1)
self.depth_wise = nn.Conv2d(hidden_size, hidden_size... |
def load_units(in_file):
out = {}
with open(in_file) as f:
for line in f:
(sample_id, units) = line.strip().split('|', 1)
out[sample_id] = units.split()
return out |
class FileStorageObserverWithExUuid(FileStorageObserver):
UNUSED_VALUE = (- 1)
def started_event(self, ex_info, command, host_info, start_time, config, meta_info, _id):
_id = (config['uuid'] + '_metadata')
super().started_event(ex_info, command, host_info, start_time, config, meta_info, _id=_id)... |
def preprocess_info(path=DATA_PATH, file=DATA_FILE, buys_file=DATA_FILE_BUYS, path_proc=DATA_PATH_PROCESSED, min_item_support=MIN_ITEM_SUPPORT, min_session_length=MIN_SESSION_LENGTH):
(data, buys) = load_data(path, file, buys_file)
data = filter_data(data, min_item_support, min_session_length) |
def get_scheduler(optimizer, n_iter_per_epoch, args):
if ('cosine' in args.lr_scheduler):
scheduler = CosineAnnealingLR(optimizer=optimizer, eta_min=1e-06, T_max=((args.epochs - args.warmup_epoch) * n_iter_per_epoch))
elif ('step' in args.lr_scheduler):
scheduler = MultiStepLR(optimizer=optimize... |
def adaptive_catavgmax_pool2d(x, output_size=1):
x_avg = F.adaptive_avg_pool2d(x, output_size)
x_max = F.adaptive_max_pool2d(x, output_size)
return torch.cat((x_avg, x_max), 1) |
class SelectiveKernelAttn(nn.Module):
def __init__(self, channels, num_paths=2, attn_channels=32, act_layer=nn.ReLU, norm_layer=nn.BatchNorm2d):
super(SelectiveKernelAttn, self).__init__()
self.num_paths = num_paths
self.fc_reduce = nn.Conv2d(channels, attn_channels, kernel_size=1, bias=Fals... |
.parametrize('metric, expected_value', [('map', 0.), ('ndcg', 0.75), ('jaccard', 0.6)])
def test_metric_is_not_1_for_incorrect(metric, expected_value):
(ground_truth, retrieved) = return_ground_incorrect_retrievals()
metric_val = mean_metric(ground_truth, retrieved, metric=metric)
assert (metric_val == expe... |
def plot_hist(title, experiment, n_tasks, fig_name):
max_step = 3000000
index = {}
scores = load_scores(experiment)
x = list(sorted(scores.keys()))
y = [[0 for _x in range(len(x))] for _t in range(n_tasks)]
for (ix, _x) in enumerate(x):
for k in scores[_x]:
if (k not in index... |
class HeadSelectionTransformerEncoderLayer(TransformerEncoderLayer):
def __init__(self, args, layer_idx, attn_head_selector=None):
super().__init__(args)
self.layer_idx = layer_idx
self.self_attn = self.build_self_attention_selection(self.embed_dim, args, attn_head_selector)
def build_se... |
def imfrombytes(content, flag='color'):
img_np = np.frombuffer(content, np.uint8)
flag = (imread_flags[flag] if is_str(flag) else flag)
img = cv2.imdecode(img_np, flag)
return img |
def mdb():
torchutil.download.targz(' penn.DATA_DIR)
shutil.rmtree((penn.DATA_DIR / 'mdb'), ignore_errors=True)
shutil.move((penn.DATA_DIR / 'MDB-stem-synth'), (penn.DATA_DIR / 'mdb')) |
class EvaluationCallback(Callback):
def __init__(self, base_dir, vocab, topk=10, corpus_dir='', embedding_path='', metric='npmi', every=10):
super(EvaluationCallback, self).__init__()
self.base_dir = base_dir
self.vocab = vocab
self.topk = topk
self.corpus_dir = corpus_dir
... |
def tree_norm(a):
return float(jnp.sqrt(sum([jnp.sum((p_a ** 2)) for p_a in jax.tree_util.tree_leaves(a)]))) |
def _get_module_by_path(module, path):
path = path.split('.')
for name in path:
module = getattr(module, name)
return module |
class MoveCarry(NamedTuple):
row: chex.Array
reward: float
target_idx: int
origin_idx: int
def target(self) -> chex.Numeric:
return self.row[self.target_idx]
def origin(self) -> chex.Numeric:
return self.row[self.origin_idx]
def update(self, update: MoveUpdate) -> 'MoveCarry'... |
def remove_spectral_norm_conv(module, name='weight'):
for (k, hook) in module._forward_pre_hooks.items():
if (isinstance(hook, SpectralNormConv) and (hook.name == name)):
hook.remove(module)
del module._forward_pre_hooks[k]
return module
raise ValueError("spectral_nor... |
def get_preprocessing_params(encoder_name, pretrained='imagenet'):
settings = encoders[encoder_name]['pretrained_settings']
if (pretrained not in settings.keys()):
raise ValueError('Available pretrained options {}'.format(settings.keys()))
formatted_settings = {}
formatted_settings['input_space'... |
def text_encoder_mlp_modules(text_encoder):
mlp_modules = []
if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
for (i, layer) in enumerate(text_encoder.text_model.encoder.layers):
mlp_mod = layer.mlp
name = f'text_model.encoder.layers.{i}.mlp'
... |
.skipif((os.getenv('GITHUB_ACTIONS') == 'true'), reason='No way of testing this on Github actions.')
def test_conv1(cel):
example = [{'speaker': 'USER', 'utterance': "I think science fiction is an amazing genre for anything. Future science, technology, time travel, FTL travel, they're all such interesting concepts.... |
class actionAngleVertical(actionAngle):
def __init__(self, *args, **kwargs):
actionAngle.__init__(self, ro=kwargs.get('ro', None), vo=kwargs.get('vo', None))
if (not ('pot' in kwargs)):
raise OSError('Must specify pot= for actionAngleVertical')
if (not ('pot' in kwargs)):
... |
_HEADS_REGISTRY.register()
class AttributeRes5ROIHeads(AttributeROIHeads, Res5ROIHeads):
def __init__(self, cfg, input_shape):
super(Res5ROIHeads, self).__init__(cfg, input_shape)
assert (len(self.in_features) == 1)
pooler_resolution = cfg.MODEL.ROI_BOX_HEAD.POOLER_RESOLUTION
pooler_... |
def build_data_set(dataset_name, istrain, cust_trans=None):
(eargs_te, eargs_tr) = ({}, {})
if ('celeba' in dataset_name):
eargs_te['split'] = 'valid'
eargs_tr['split'] = 'train'
else:
eargs_te['train'] = False
eargs_tr['train'] = True
T = transforms.ToTensor()
if (cu... |
def vgg6(conv_layer, linear_layer, init_type, **kwargs):
n = [i for i in cfgs['6'] if isinstance(i, int)][(- 1)]
model = VGG(make_layers(cfgs['6'], conv_layer, batch_norm=False), n, linear_layer, **kwargs)
initialize_weights(model, init_type)
return model |
class convprojection(nn.Module):
def __init__(self, path=None, **kwargs):
super(convprojection, self).__init__()
self.convd32x = UpsampleConvLayer(512, 512, kernel_size=4, stride=2)
self.convd16x = UpsampleConvLayer(512, 320, kernel_size=4, stride=2)
self.dense_4 = nn.Sequential(Resi... |
_module()
class WandbLoggerHook(LoggerHook):
def __init__(self, init_kwargs=None, interval=10, ignore_last=True, reset_flag=False, commit=True, by_epoch=True, with_step=True, log_artifact=True, out_suffix=('.log.json', '.log', '.py')):
super(WandbLoggerHook, self).__init__(interval, ignore_last, reset_flag,... |
class IntegerSBXCrossover(Crossover[(IntegerSolution, IntegerSolution)]):
__EPS = 1e-14
def __init__(self, probability: float, distribution_index: float=20.0):
super(IntegerSBXCrossover, self).__init__(probability=probability)
self.distribution_index = distribution_index
def execute(self, pa... |
class Item():
seq: str
rgb_stem: str
depth_stem: str
def get_split_file(cls, mode: str) -> Path:
return ((PATHS['tum'] / 'splits') / f'{mode}_files.txt')
def load_split(cls, mode: str) -> ty.S['Item']:
file = cls.get_split_file(mode)
return [cls(*line) for line in io.readline... |
def get_rank():
if (not dist.is_available()):
return 0
if (not dist.is_initialized()):
return 0
return dist.get_rank() |
class NormalizeInitialization(Layer):
def __init__(self, epsilon=1e-05, **kwargs):
self.epsilon = epsilon
super(__class__, self).__init__(**kwargs)
def build(self, input_shape):
(input_shape, _) = input_shape
self.counter = self.add_weight(name='counter', shape=[1], initializer=Z... |
def get_python_modules(local_graph_dict, module):
for node_name in local_graph_dict:
node_info = local_graph_dict[node_name]
(node_class, node_op) = (node_info['node_class'], node_info['node_op'])
if (node_class == 'Module'):
if ((node_op == None) or (node_name == '%self.1')):
... |
class MLPZinc(nn.Module):
def __init__(self, g, in_dim, num_layers, num_hidden, num_atom_type, num_bond_type):
super(MLPZinc, self).__init__()
self.g = g
self.num_atom_type = num_atom_type
self.num_bond_type = num_bond_type
self.layers = nn.ModuleList()
self.BNs = nn.... |
class Glorot(Initializer):
def __init__(self, initializer, gain=1.0, c01b=False):
if (gain == 'relu'):
gain = np.sqrt(2)
self.initializer = initializer
self.gain = gain
self.c01b = c01b
def sample(self, shape):
if self.c01b:
if (len(shape) != 4):
... |
def get_model(name, **kwargs):
name = name.lower()
if (name not in _models):
raise ValueError('Unsupported model: {}'.format(name))
net = _models[name](**kwargs)
return net |
class ShuffleNetV2b(nn.Module):
def __init__(self, channels, init_block_channels, final_block_channels, use_se=False, use_residual=False, shuffle_group_first=True, in_channels=3, in_size=(224, 224), num_classes=1000):
super(ShuffleNetV2b, self).__init__()
self.in_size = in_size
self.num_clas... |
_model
def efficientnet_b1(pretrained=False, **kwargs):
model = _gen_efficientnet('efficientnet_b1', channel_multiplier=1.0, depth_multiplier=1.1, pretrained=pretrained, **kwargs)
return model |
def masked_mape_np(preds, labels, null_val=np.nan):
with np.errstate(divide='ignore', invalid='ignore'):
if np.isnan(null_val):
mask = (~ np.isnan(labels))
else:
mask = np.not_equal(labels, null_val)
mask = mask.astype('float32')
mask /= np.mean(mask)
... |
def word_swap(s):
for t in word_transforms[LANGUAGE]:
if (s in t):
return random.sample(t, 1)[0]
return s |
def create_buffers(flags, obs_shape, num_actions) -> Buffers:
T = flags.unroll_length
specs = dict(frame=dict(size=((T + 1), *obs_shape), dtype=torch.uint8), reward=dict(size=((T + 1),), dtype=torch.float32), done=dict(size=((T + 1),), dtype=torch.bool), episode_return=dict(size=((T + 1),), dtype=torch.float32)... |
class DataTrainingArguments():
dataset_name: Optional[str] = field(default=None, metadata={'help': 'The name of the dataset to use (via the datasets library).'})
dataset_config_name: Optional[str] = field(default=None, metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}... |
def warmup_linear(x, warmup=0.002):
if (x < warmup):
return (x / warmup)
return max(((x - 1.0) / (warmup - 1.0)), 0) |
def collate_results(results):
scenario_results = {}
for res in results:
name = res['Name']
if (name not in scenario_results):
scenario_results[name] = Result(name)
scenario_results[name].add(res['Steps'], res['Total reward'])
return scenario_results |
def format_text(text):
text = regex.sub('[\\p{Z}]', ' ', text)
text = re.sub('([ ]{2,})', ' ', text)
text = re.sub('([ \\t]+)?[\\r\\n]([ \\t]+)?', '\n', text)
text = re.sub('\\n+', ' ', text)
text = text.strip()
return text |
class ResNet(nn.Module):
__factory = {18: torchvision.models.resnet18, 34: torchvision.models.resnet34, 50: torchvision.models.resnet50, 101: torchvision.models.resnet101, 152: torchvision.models.resnet152}
def __init__(self, depth, pretrained=True, cut_at_pooling=False, num_features=0, norm=False, dropout=0.5,... |
class PPOTest(tf.test.TestCase):
def test_no_crash_cheetah(self):
nets = (networks.ForwardGaussianPolicy, networks.RecurrentGaussianPolicy)
for network in nets:
config = self._define_config()
with config.unlocked:
config.env = 'HalfCheetah-v1'
... |
def rotationMatrixToEulerAngles(R):
sy = math.sqrt(((R[(0, 0)] * R[(0, 0)]) + (R[(1, 0)] * R[(1, 0)])))
singular = (sy < 1e-06)
if (not singular):
x = math.atan2(R[(2, 1)], R[(2, 2)])
y = math.atan2((- R[(2, 0)]), sy)
z = math.atan2(R[(1, 0)], R[(0, 0)])
else:
x = math.at... |
class Prcc(BaseImageDataset):
dataset_dir = 'prcc/rgb'
def __init__(self, root='/home/jinx/data', verbose=True, **kwargs):
super(Prcc, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.train_dir = osp.join(self.dataset_dir, 'train')
self.validation_dir = o... |
def numeric_score_fov(pred, gt, mask):
FP = np.float(np.sum((((pred == 1) & (gt == 0)) & (mask == 1))))
FN = np.float(np.sum((((pred == 0) & (gt == 1)) & (mask == 1))))
TP = np.float(np.sum((((pred == 1) & (gt == 1)) & (mask == 1))))
TN = np.float(np.sum((((pred == 0) & (gt == 0)) & (mask == 1))))
r... |
class FakeProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(self._read_corpus(os.path.join(data_dir, 'train_tok.csv'), MR=False, clean=False), 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(self._read_corpus(os.path.join(d... |
def parse_dollar(line):
all_dollar = re.findall('\\$[0-9][0-9.,]*', line)
for dollar in all_dollar:
number_text = engine.number_to_words(dollar[1:].replace(',', ''))
number_text = number_text.replace('-', ' ')
dollar_text = (number_text + ' dollars')
line = line.replace(dollar, d... |
def main(opt):
train_files = {'src': opt.train_src, 'tgt': opt.train_tgt}
valid_files = {'src': opt.valid_src, 'tgt': opt.valid_tgt}
if opt.feature:
assert ((len(opt.train_feats) == len(opt.valid_feats)) and (len(opt.train_feats) > 0))
(train_files['feature'], valid_files['feature']) = (opt.... |
def add_model_args(parser):
group = parser.add_argument_group('Model configuration')
from fairseq.models import ARCH_MODEL_REGISTRY
group.add_argument('--arch', '-a', metavar='ARCH', choices=ARCH_MODEL_REGISTRY.keys(), help='model architecture')
return group |
class BaseImageProcessFunc():
def __call__(self, image: Image.Image, preprocessor: Dict[(str, Any)]) -> Dict[(str, Any)]:
raise NotImplementedError |
class NetworkBlock(nn.Module):
def __init__(self, nb_layers, in_planes, out_planes, block, stride, dropRate=0.0):
super().__init__()
self.layer = self._make_layer(block, in_planes, out_planes, nb_layers, stride, dropRate)
def _make_layer(self, block, in_planes, out_planes, nb_layers, stride, dro... |
class ConsoleHandler(MetricHandlerBase):
def __init__(self, *args, **kwargs):
super().__init__('data', *args, **kwargs)
self._was_initialized = False
def collect(self, collection, time, mode='train'):
for (tag, val) in collection:
if (mode != 'train'):
tag = (... |
def vis_h36m_compare(p3d_gt, p3d_pred, save_path):
num_frames_gt = len(p3d_gt)
num_frames_pred = len(p3d_pred)
metadata = dict(title='01', artist='Matplotlib', comment='motion')
writer = FFMpegWriter(fps=10, metadata=metadata)
fig = plt.figure()
ax = plt.gca(projection='3d')
ob = H36m3DPose(... |
def compute_and_add_linker_smiles(data, progress=False):
data_with_linkers = []
generator = (tqdm(data) if progress else data)
for m in generator:
pred_mol = Chem.MolFromSmiles(m['pred_mol_smi'], sanitize=True)
true_mol = Chem.MolFromSmiles(m['true_mol_smi'], sanitize=True)
frag = Ch... |
def eval_once(saver, summary_writer, summary_op, agelogits, agelabels, genderlogits, genderlabels, num_eval, saveresultdir, requested_step=None):
agetop1 = tf.nn.in_top_k(agelogits, agelabels, 1)
agetop2 = tf.nn.in_top_k(agelogits, agelabels, 2)
gendertop1 = tf.nn.in_top_k(genderlogits, genderlabels, 1)
... |
def test_pvtv2():
with pytest.raises(TypeError):
PyramidVisionTransformerV2(pretrained=123)
with pytest.raises(AssertionError):
PyramidVisionTransformerV2(pretrain_img_size=(224, 224, 224))
temp = torch.randn((1, 3, 32, 32))
model = PyramidVisionTransformerV2()
outs = model(temp)
... |
class UnetGenerator_IN(nn.Module):
def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.InstanceNorm2d, use_dropout=False, output_function=nn.Sigmoid):
super(UnetGenerator_IN, self).__init__()
unet_block = UnetSkipConnectionBlock_IN((ngf * 8), (ngf * 8), input_nc=None, submodule=... |
class TopKNeuronCoverage(MyNeuronCoverage):
def __init__(self, k=5):
super(TopKNeuronCoverage, self).__init__(threshold=k)
self._threshould = k
self._topk = k
assert isinstance(k, int)
(parallel=True)
def _calc_1(intermediate_layer_output, features_index, threshold):
... |
def run():
zpy.blender.set_seed()
saver = zpy.saver_image.ImageSaver(description='Suzannes from a camera view')
suzanne_seg_color = zpy.color.random_color(output_style='frgb')
saver.add_category(name='Suzanne', color=suzanne_seg_color)
zpy.objects.segment('Suzanne', color=suzanne_seg_color)
zpy.... |
def plot_local_contrib(row, model, X, g_pred=None, scale=False):
local_contrib_frame = pd.DataFrame(columns=['Name', 'Local Contribution', 'Sign'])
for (key, val) in sorted(row[X].types.items()):
contrib = 0
name = ''
if (val == 'enum'):
level = row[key][(0, 0)]
n... |
def add_training_args(parser):
group = parser.add_argument_group('train', 'training configurations')
group.add_argument('--batch-size', type=int, default=4, help='Data Loader batch size')
group.add_argument('--weight-decay', type=float, default=0.01, help='weight decay coefficient for L2 regularization')
... |
def register_model(model_name: str, classification_cls: Optional[Type[ModelLike]]=None, regression_cls: Optional[Type[ModelLike]]=None, overwrite: Optional[bool]=None):
problem_types = ['classification', 'regression']
for (cls, problem_type) in zip([classification_cls, regression_cls], problem_types):
i... |
class TestDimPlanner(unittest.TestCase):
(((not torch.cuda.is_available()) or (torch_version() < (2, 0, 0))), 'Test on GPU image')
def test_dim_planner(self):
run_dim_planner(2, 4, my_loss_func) |
class MORAN(nn.Module):
def __init__(self, nc, nclass, nh, targetH, targetW, BidirDecoder=False, inputDataType='torch.cuda.FloatTensor', maxBatch=256, CUDA=True):
super(MORAN, self).__init__()
self.MORN = MORN(nc, targetH, targetW, inputDataType, maxBatch, CUDA)
self.ASRN = ASRN(targetH, nc,... |
def count_trainable_parameters(model: Any) -> int:
return sum([x.numel() for x in model.parameters() if x.requires_grad]) |
def create_train_state(model: FlaxAutoModelForTokenClassification, learning_rate_fn: Callable[([int], float)], num_labels: int, training_args: TrainingArguments) -> train_state.TrainState:
class TrainState(train_state.TrainState):
logits_fn: Callable = struct.field(pytree_node=False)
loss_fn: Callab... |
class GRevNet(snt.AbstractModule):
def __init__(self, make_gnn_fn, num_timesteps, node_embedding_dim, use_batch_norm=False, weight_sharing=False, name='GRevNet'):
super(GRevNet, self).__init__(name=name)
self.num_timesteps = num_timesteps
self.weight_sharing = weight_sharing
if weigh... |
class MetaAlbumDataset(Dataset):
def __init__(self, datasets, data_dir, img_size=128):
if (len(datasets) == 1):
self.name = datasets[0]
else:
self.name = f"Multiple datasets: {','.join(datasets)}"
self.data_dir = data_dir
self.transform = transforms.Compose([t... |
def _run_allgather_reducescatter(rank, world_size, tmp_file):
if torch.cuda.is_available():
torch.cuda.set_device(rank)
device = torch.device(f'cuda:{rank}')
backend = 'nccl'
else:
device = torch.device('cpu')
backend = 'gloo'
dist.init_process_group(init_method=('fil... |
def _target_samples_int(y, n_target_samples, sampling_type):
target_stats = dict(Counter(y))
max_class_ = max(target_stats, key=target_stats.get)
min_class_ = min(target_stats, key=target_stats.get)
n_max_class_samples_ = target_stats[max_class_]
n_min_class_samples_ = target_stats[min_class_]
i... |
_task('sentence_prediction')
class SentencePredictionTask(LegacyFairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='FILE', help='file prefix for data')
parser.add_argument('--num-classes', type=int, default=(- 1), help='number of classes or regression targets')
parser.ad... |
def convert_sentence_to_json(sentence):
if ('_' in sentence):
(prefix, rest) = sentence.split('_', 1)
(query, rest) = rest.split('_', 1)
query_index = len(prefix.rstrip().split(' '))
else:
(query, query_index) = (None, None)
(prefix, rest) = sentence.split('[', 1)
(pronou... |
def ori_pro(s, name=''):
s = s.strip()
s = s.replace('<mask><s>', ' ')
s = ' '.join(s.strip().split())
return s |
class kiunet3d(nn.Module):
def __init__(self, c=4, n=1, channels=128, groups=16, norm='bn', num_classes=5):
super(kiunet3d, self).__init__()
self.encoder1 = nn.Conv3d(c, n, kernel_size=3, padding=1, stride=1, bias=False)
self.encoder2 = nn.Conv3d(n, (2 * n), kernel_size=3, padding=1, stride=... |
def check_path_exists(path):
if (not os.path.exists(path)):
raise FileNotFoundError(path)
return path |
def kMobileNet(input_shape=None, alpha=1.0, depth_multiplier=1, dropout=0.001, include_top=True, weights=None, input_tensor=None, pooling=None, classes=1000, conv1_activation=keras.activations.swish, d_separable_activation=keras.activations.swish, activation=keras.activations.swish, kType=0, l_ratio=0.0, ab_ratio=0.0, ... |
class BasicUpdateBlock(nn.Module):
def __init__(self):
super(BasicUpdateBlock, self).__init__()
self.encoder = BasicMotionEncoder()
self.flow_head = dispHead()
self.mask = nn.Sequential(nn.ReflectionPad2d(1), nn.Conv2d(192, 324, 3), nn.LeakyReLU(inplace=True), nn.Conv2d(324, (64 * 9)... |
def unpack(source_data, target_dir, start_idx):
for (idx, (image_data, label_idx)) in tqdm(enumerate(source_data), total=len(source_data)):
subdir = os.path.join(target_dir, str(label_idx))
name = '{}_{}.png'.format((start_idx + idx), str(label_idx))
os.makedirs(subdir, exist_ok=True)
... |
class PIDNet(nn.Module):
def __init__(self, m=2, n=3, num_classes=19, planes=64, ppm_planes=96, head_planes=128, augment=True):
super(PIDNet, self).__init__()
self.augment = augment
self.conv1 = nn.Sequential(nn.Conv2d(3, planes, kernel_size=3, stride=2, padding=1), nn.ReLU(inplace=True), nn... |
class TransfoXLConfig(PretrainedConfig):
pretrained_config_archive_map = TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP
model_type = 'transfo-xl'
def __init__(self, vocab_size=267735, cutoffs=[20000, 40000, 200000], d_model=1024, d_embed=1024, n_head=16, d_head=64, d_inner=4096, div_val=4, pre_lnorm=False, n_laye... |
def print_result(best_scores, best_hypos, output_file):
for (i, (s, h)) in enumerate(zip(best_scores, best_hypos)):
print(f'{i} {s} {h}', file=output_file) |
def run(dataset_dir):
if (not tf.gfile.Exists(dataset_dir)):
tf.gfile.MakeDirs(dataset_dir)
training_filename = _get_output_filename(dataset_dir, 'train')
testing_filename = _get_output_filename(dataset_dir, 'test')
if (tf.gfile.Exists(training_filename) and tf.gfile.Exists(testing_filename)):
... |
class PSM_Encoder_Instance(nn.Module):
def __init__(self, in_planes=3, batch_norm=True):
super(PSM_Encoder_Instance, self).__init__()
self.in_planes = in_planes
self.batch_norm = batch_norm
self.firstconv = nn.Sequential(conv_in_relu(batch_norm, self.in_planes, 32, 3, 2, 1, 1, bias=F... |
_module(force=True)
class DefaultFormatBundle(object):
def __call__(self, results):
if ('img' in results):
img = results['img']
if (len(img.shape) < 3):
img = np.expand_dims(img, (- 1))
img = np.ascontiguousarray(img.transpose(2, 0, 1))
results... |
def quality_check_timeseries_dataframe(df, dt_col, id_col=None, repair=True):
invalidInputError((dt_col in df.columns), f'dt_col {dt_col} can not be found in df.')
if (id_col is not None):
invalidInputError((id_col in df.columns), f'id_col {id_col} can not be found in df.')
invalidInputError((pd.isn... |
def _update_config(base_cfg, exp_cfg):
if (isinstance(base_cfg, dict) and isinstance(exp_cfg, edict)):
for (k, v) in exp_cfg.items():
if (k in base_cfg):
if (not isinstance(v, dict)):
base_cfg[k] = v
else:
_update_config(bas... |
def draw_grasp_prediction_matplotlib(axs, prediction, image, grasp_success, z, showTextBox, title=None):
(center, theta, y_current, x_current) = decode_prediction_for_matplotlib(prediction, image)
axs.imshow(image, alpha=1, zorder=z)
z = draw_grasp(axs=axs, grasp_success=grasp_success, center=center, theta=... |
def vgg_conv_layer(x, kernel_size, out_channels, stride, var_list, pad='SAME', name='conv'):
in_channels = x.get_shape().as_list()[(- 1)]
with tf.variable_scope(name):
n = (kernel_size * in_channels)
stdv = (1.0 / math.sqrt(n))
w = tf.get_variable('kernel_weights', [kernel_size, kernel_s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.