code stringlengths 101 5.91M |
|---|
class META(nn.Module):
def __init__(self, ebd, args):
super(META, self).__init__()
self.args = args
self.ebd = ebd
self.aux = get_embedding(args)
self.ebd_dim = self.ebd.embedding_dim
input_dim = (((int(args.meta_idf) + self.aux.embedding_dim) + int(args.meta_w_target... |
_task('commonsense_qa')
class CommonsenseQATask(FairseqTask):
def add_args(parser):
parser.add_argument('data', metavar='DIR', help='path to data directory; we load <split>.jsonl')
parser.add_argument('--init-token', type=int, default=None, help='add token at the beginning of each batch item')
... |
class Progress():
def __init__(self, n_iter, pmax, batchSizeList):
assert ((n_iter > 0) and isinstance(n_iter, int)), 'n_iter must be int >= 1'
assert ((pmax >= 0) and isinstance(pmax, int)), 'pmax must be int >= 0'
assert (isinstance(batchSizeList, list) and all((isinstance(x, int) for x in... |
def disparity_regression(x, maxdisp):
assert (len(x.shape) == 4)
disp_values = torch.arange(0, maxdisp, dtype=x.dtype, device=x.device)
disp_values = disp_values.view(1, maxdisp, 1, 1)
return torch.sum((x * disp_values), 1, keepdim=False) |
def tokenizer_class_from_name(class_name: str):
all_tokenizer_classes = (([v[0] for v in TOKENIZER_MAPPING.values() if (v[0] is not None)] + [v[1] for v in TOKENIZER_MAPPING.values() if (v[1] is not None)]) + NO_CONFIG_TOKENIZER)
for c in all_tokenizer_classes:
if (c.__name__ == class_name):
... |
class BertSoftmaxParallel(nn.DataParallel, BertSoftmaxFunction):
def __init__(self, module, device_ids):
nn.DataParallel.__init__(self, module=module, device_ids=device_ids)
self.label_size = self.module.label_size
self.device = self.module.device |
def main():
cfg = yaml.full_load(open('config.yml', 'r'))
inferenceConfig = cfg['INFERENCE']
os.environ['CUDA_VISIBLE_DEVICES'] = inferenceConfig['gpuID']
print(('=' * 2), 'Inferenc configs', ('=' * 5))
print(json.dumps(inferenceConfig, indent=1, sort_keys=True))
CHECKPOINT_FOLDER = inferenceCon... |
def pre_process_images(raw_images_path):
current_directory = os.getcwd()
IMAGE_SIZE = 1024
predictor = dlib.shape_predictor(paths_config.dlib)
os.chdir(raw_images_path)
images_names = glob.glob(f'*')
aligned_images = []
for image_name in tqdm(images_names):
try:
aligned_i... |
def main():
print(window_width, window_height)
top_widgets = []
left_widgets = []
for i in range(num_top):
top_widgets.append(ORCWidget(('HF_' + str(i)), [top_button_width_min, top_button_width_pref, top_button_width_max, top_button_height_min, top_button_height_pref, top_button_height_max]))
... |
class Encoder(Module):
def __init__(self, channels=(3, 16, 32, 64)):
super().__init__()
self.encBlocks = ModuleList([Block(channels[i], channels[(i + 1)]) for i in range((len(channels) - 1))])
self.pool = MaxPool2d(2)
def forward(self, x):
blockOutputs = []
for block in s... |
def PSNR(img1, img2):
mse = np.mean((((img1 / 255.0) - (img2 / 255.0)) ** 2))
if (mse == 0):
return 100
PIXEL_MAX = 1
return (20 * math.log10((PIXEL_MAX / math.sqrt(mse)))) |
def main():
parser = get_parser()
args = parser.parse_args()
spec = osp.basename(args.path)
try:
faiss_spec = parse_faiss_specs(spec.rstrip('/'))[0]
except:
print(spec)
raise
print('Faiss Spec:', faiss_spec, file=sys.stderr)
if faiss_spec.pca:
A = torch.from_n... |
class PLN(nn.Module):
def __init__(self, in_ch=3, mid_ch=12, out_ch=3):
super(PLN, self).__init__()
self.rebnconvin = REBNCONV(in_ch, mid_ch, dirate=1)
self.rebnconvout = REBNCONV(mid_ch, out_ch, dirate=1)
def forward(self, x):
hx = x
hxin = self.rebnconvin(hx)
hx... |
class RandomEnv(gym.Env):
def __init__(self):
super(RandomEnv, self).__init__()
self.action_space = spaces.Discrete(6)
self.observation_space = gym.spaces.Dict()
self.observation_space.spaces['image'] = gym.spaces.Box(low=0.0, high=1.0, shape=(10, 10, 10))
self.channels = [f'... |
class LBP_NET(nn.Module):
def __init__(self, T):
super(LBP_NET, self).__init__()
self.T = T
self.W1 = nn.Parameter(torch.randn(32, 3, 4, 4), requires_grad=True)
self.strd1 = 2
self.W2 = nn.Parameter(torch.randn(64, 32, 4, 4), requires_grad=True)
self.strd2 = 2
... |
def load_template(config: CfgNode, **kwargs):
if (config.template is not None):
template_class = TEMPLATE_CLASS[config.template]
template = template_class.from_config(config=config[config.template], **kwargs)
return template |
def normalize_advantages(advantages):
return ((advantages - np.mean(advantages)) / (advantages.std() + 1e-08)) |
class LSTMModel(nn.Module):
def __init__(self, input_dim, hidden_dim, layer_dim, output_dim):
super(LSTMModel, self).__init__()
self.hidden_dim = hidden_dim
self.layer_dim = layer_dim
self.lstm = nn.LSTM(input_dim, hidden_dim, layer_dim, batch_first=True)
self.fc = nn.Linear(... |
def export_plot(fig, plot_title):
path = get_plot_name(plot_title)
print(f'saving plot in {path}')
plt.savefig(path, dpi=EXPORT_RESOLUTION)
plt.clf() |
class RMSE(BaseMetric):
def _compute(self, pred: ty.T, target: ty.T) -> ty.T:
return (pred - target).pow(2).nanmean(dim=1).sqrt() |
class LeNet(nn.Module):
def __init__(self, fc1_hidden_size=500):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 20, 5, 1)
self.conv2 = nn.Conv2d(20, 50, 5, 1)
self.fc1 = nn.Linear(((4 * 4) * 50), fc1_hidden_size)
self.fc2 = nn.Linear(fc1_hidden_size, 10)
def forw... |
def read_image(filepath):
img_bytes = FILE_CLIENT.get(filepath)
image = mmcv.imfrombytes(img_bytes, flag='color', channel_order='rgb', backend='pillow')
return image |
def _gen_spnasnet(variant, channel_multiplier=1.0, pretrained=False, **kwargs):
arch_def = [['ds_r1_k3_s1_c16_noskip'], ['ir_r3_k3_s2_e3_c24'], ['ir_r1_k5_s2_e6_c40', 'ir_r3_k3_s1_e3_c40'], ['ir_r1_k5_s2_e6_c80', 'ir_r3_k3_s1_e3_c80'], ['ir_r1_k5_s1_e6_c96', 'ir_r3_k5_s1_e3_c96'], ['ir_r4_k5_s2_e6_c192'], ['ir_r1_k... |
class BYTETracker(object):
def __init__(self, args, frame_rate=30):
self.args = args
self.det_thresh = args.new_thresh
self.buffer_size = int(((frame_rate / 30.0) * args.track_buffer))
self.max_time_lost = self.buffer_size
self.reset()
def init_track(self, results):
... |
class HebbianTrainer(Trainer):
def __init__(self, model: torch.nn.Sequential, learning_rule: Union[(LearningRule, Dict[(str, LearningRule)])], optimizer: Optimizer, supervised_from: int=(- 1), freeze_layers: List[str]=None, complete_forward: bool=False, single_forward: bool=False, device: Optional[Union[(str, torch... |
def write_new_lm(new_lm_lines, ngram_counts, ngram_diffs):
for i in range(10):
g = re.search('ngram (\\d)=(\\d+)', new_lm_lines[i])
if g:
n = int(g.group(1))
if (n in ngram_diffs):
new_num_ngrams = (ngram_counts[n] + ngram_diffs[n])
new_lm_line... |
def validation(data_iter, net, save_scores=False, delta=0.8):
score_list = []
label_list = []
net.eval()
(losses, batch_num, acc, acc_num) = (0, 0, 0, 0)
criterion = nn.BCELoss()
for (batch_idx, batch) in enumerate(data_iter):
(qbatch, rbatch, qlength, rlength, label) = batch
qba... |
def load_data(root_path):
data = np.load(root_path)
N_test = int((0.1 * data.shape[0]))
data_test = data[(- N_test):]
data = data[0:(- N_test)]
N_validate = int((0.1 * data.shape[0]))
data_validate = data[(- N_validate):]
data_train = data[0:(- N_validate)]
return (data_train, data_valid... |
_type
def rgb_shift(image, r_shift=0.0, g_shift=0.0, b_shift=0.0):
(r, g, b) = tf.split(image, 3, axis=2)
r = (r + tf.random.uniform([], (- r_shift), r_shift))
g = (g + tf.random.uniform([], (- g_shift), g_shift))
b = (b + tf.random.uniform([], (- b_shift), b_shift))
image = tf.concat([r, g, b], axi... |
class PostProcessCocoTf(PostProcessCoco):
def __init__(self):
super().__init__()
self.use_inv_map = True
def __call__(self, results, ids, expected=None, result_dict=None):
processed_results = []
bs = len(results[0])
for idx in range(0, bs):
self.content_ids.ap... |
def read_vocab(path):
word2idx = {}
idx2word = []
with open(path, 'r', encoding='utf-8') as f:
for line in f:
word = line.split()
assert (len(word) == 2)
word = word[0]
if (word not in word2idx):
idx2word.append(word)
wo... |
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--rnn_size', type=int, default=1280, help='size of the rnn in number of hidden nodes in question gru')
parser.add_argument('--num_hid', type=int, default=1280, help='size of the rnn in number of hidden nodes in question gru')
parse... |
def getCharList(root):
charlist = []
for img_path in (glob.glob((root + '/*.jpg')) + glob.glob((root + '/*.png'))):
ch = os.path.basename(img_path).split('.')[0]
charlist.append(ch)
return charlist |
def echo(*args, **kwargs):
print('Received the following input:')
print(f'args = {args}')
print(f'kwargs = {kwargs}') |
def iresnet18(pretrained=False, **kwargs):
model = iResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
if pretrained:
os.makedirs(default_cache_path, exist_ok=True)
model.load_state_dict(torch.load(download_from_url(model_urls['iresnet18'], root=default_cache_path)))
return model |
class DeiTOnnxConfig(OnnxConfig):
torch_onnx_minimum_version = version.parse('1.11')
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
return OrderedDict([('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'})])
def atol_for_validation(self) -> float:
return 0.0001 |
class XTensorBoardCallback(tf.keras.callbacks.TensorBoard):
def __init__(self, log_dir, **kwargs):
super().__init__(log_dir=log_dir, **kwargs)
def on_epoch_end(self, epoch, logs=None):
logs.update({'lr': tf.keras.backend.get_value(self.model.optimizer.lr)})
super().on_epoch_end(epoch, lo... |
def load_str_list(fname):
with open(fname) as f:
lines = f.readlines()
lines = [l.strip() for l in lines]
return lines |
def _optimize_clone(optimizer, clone, num_clones, regularization_losses, **kwargs):
sum_loss = _gather_clone_loss(clone, num_clones, regularization_losses)
clone_grad = None
if (sum_loss is not None):
with tf.device(clone.device):
clone_grad = optimizer.compute_gradients(sum_loss, **kwar... |
def main(config):
if (is_main_process() and config.wandb.enable):
run = setup_wandb(config)
logger.info(f'''config:
{config}''')
logger.info(f'train_file: {config.train_file}')
setup_seed((config.seed + get_rank()))
device = torch.device(config.device)
cudnn.benchmark = True
(train_... |
def convert(pipeline_name, use_auth_token=None, local_model_path=None):
if ((use_auth_token is None) or (len(use_auth_token) == 0)):
use_auth_token = None
try:
(model_version, optimization_methods) = pipeline_name.split('/')
precision = ('float16' if ('FP16' in optimization_methods) else... |
def create_vocab(labels):
new_labels = []
for l in labels:
new_labels += l
unique = np.unique(new_labels)
label2id = {}
id2label = {}
counter = 0
for word in unique:
label2id[word] = counter
id2label[counter] = word
counter += 1
return (label2id, id2label) |
def test_to_ntuple():
single_number = 2
assert (mmcv.utils.to_1tuple(single_number) == (single_number,))
assert (mmcv.utils.to_2tuple(single_number) == (single_number, single_number))
assert (mmcv.utils.to_3tuple(single_number) == (single_number, single_number, single_number))
assert (mmcv.utils.to_... |
class MultiDiscrete(gym.Space):
def __init__(self, array_of_param_array):
self.low = np.array([x[0] for x in array_of_param_array])
self.high = np.array([x[1] for x in array_of_param_array])
self.num_discrete_space = self.low.shape[0]
def sample(self):
random_array = prng.np_rand... |
class FileOutput(LogOutput, metaclass=abc.ABCMeta):
def __init__(self, file_name, mode='w'):
mkdir_p(os.path.dirname(file_name))
self._log_file = open(file_name, mode)
def close(self):
if (self._log_file and (not self._log_file.closed)):
self._log_file.close()
def dump(se... |
def load_tf2_checkpoint_in_pytorch_model(pt_model, tf_checkpoint_path, tf_inputs=None, allow_missing_keys=False, output_loading_info=False):
try:
import tensorflow as tf
import torch
except ImportError:
logger.error('Loading a TensorFlow model in PyTorch, requires both PyTorch and Tensor... |
def test_film_correctly_forwards_input():
batch_size = 11
in_channels = 13
seq_len = 31
film_embedding_size = 7
film = FiLM(film_embedding_size, in_channels)
x = torch.testing.make_tensor(batch_size, in_channels, seq_len, device='cpu', dtype=torch.float32)
film_embedding = torch.testing.make... |
def get_plugin(cuda_file, extra_nvcc_options=[]):
cuda_file_base = os.path.basename(cuda_file)
(cuda_file_name, cuda_file_ext) = os.path.splitext(cuda_file_base)
if (cuda_file in _plugin_cache):
return _plugin_cache[cuda_file]
if verbose:
print(('Setting up TensorFlow plugin "%s": ' % cu... |
def distributed():
num_gpus = (int(os.environ['WORLD_SIZE']) if ('WORLD_SIZE' in os.environ) else 1)
distributed = (num_gpus > 1)
return distributed |
class ImageSetToSample(ImagePreprocessing):
def __init__(self, input_keys=['imageTensor'], target_keys=['label'], sample_key='sample', bigdl_type='float'):
super(ImageSetToSample, self).__init__(bigdl_type, input_keys, target_keys, sample_key) |
def main(_):
if FLAGS.tune:
from neural_compressor.quantization import fit
from neural_compressor.config import PostTrainingQuantConfig
from neural_compressor import set_random_seed
set_random_seed(9527)
op_name_dict = {'average_pooling2d': {'activation': {'dtype': ['fp32']}}... |
class _SyncBatchNorm(_BatchNorm):
def __init__(self, num_features, eps=1e-05, momentum=0.1, affine=True):
super(_SyncBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)
self._sync_master = SyncMaster(self._data_parallel_master)
self._parallel_id = None
... |
_module()
class SEResNeXt(SEResNet):
arch_settings = {50: (SEBottleneck, (3, 4, 6, 3)), 101: (SEBottleneck, (3, 4, 23, 3)), 152: (SEBottleneck, (3, 8, 36, 3))}
def __init__(self, depth, groups=32, width_per_group=4, **kwargs):
self.groups = groups
self.width_per_group = width_per_group
s... |
def tsv_writer(values, tsv_file_name):
ensure_directory(os.path.dirname(tsv_file_name))
tsv_file_name_tmp = (tsv_file_name + '.tmp')
with open(tsv_file_name_tmp, 'w') as fp:
assert (values is not None)
for value in values:
assert value
v = '{0}\n'.format('\t'.join(map... |
class get_features(nn.Module):
def __init__(self):
super(get_features, self).__init__()
self.resnet18 = models.resnet18(pretrained=True)
self.resnet18_removed = list(self.resnet18.children())[:(- 1)]
self.resnet18 = nn.Sequential(*self.resnet18_removed)
def forward(self, inputs):... |
class dcganDataset(Dataset):
def __init__(self, root, transform=None, targte_transform=None):
super(dcganDataset, self).__init__()
self.image_dir = os.path.join(opt.data_dir, root)
self.samples = []
self.img_label = []
self.img_flag = []
self.transform = transform
... |
class InceptionV3(nn.Module):
def __init__(self, inception_blocks=None, num_classes=1000, in_chans=3, drop_rate=0.0, global_pool='avg'):
super(InceptionV3, self).__init__()
self.num_classes = num_classes
self.drop_rate = drop_rate
if (inception_blocks is None):
inception_... |
def ssim(img1, img2, window_size=11, window=None, size_average=True, full=False, val_range=None):
if (val_range is None):
if (torch.max(img1) > 128):
max_val = 255
else:
max_val = 1
if (torch.min(img1) < (- 0.5)):
min_val = (- 1)
else:
... |
class ModelArguments():
model_name_or_path: str = field(metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'})
config_name: Optional[str] = field(default=None, metadata={'help': 'Pretrained config name or path if not the same as model_name'})
tokenizer_name: Optional[s... |
def main():
x_nodes = 784
z_dim = 36
autoencoder = AE(x_nodes, z_dim)
history = autoencoder.fit(X_train, X_train, epochs=10, batch_size=256, shuffle=True, validation_data=(X_test, X_test))
plot_acc(history, '(a) ')
plt.show()
plot_loss(history, '(b) ')
plt.show()
show_ae(au... |
def weights_init(m):
cname = m.__class__
if ((cname == nn.Linear) or (cname == nn.Conv2d) or (cname == nn.ConvTranspose2d)):
m.weight.data.normal_(0.0, 0.02)
elif (cname == nn.BatchNorm2d):
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
else:
print(('%s is not init... |
def get_model_parameters_number(model):
params_num = sum((p.numel() for p in model.parameters() if p.requires_grad))
return params_num |
class HypothesisHandler(ScorerHandler):
def put(self):
instance_id = int(self.get_argument('instance_id'))
list_of_tokens = self.request.body.decode('utf-8').strip().split()
self.scorer.recv_hyp(instance_id, list_of_tokens) |
class AsymBiChaFuse(nn.Module):
def __init__(self, channels=64, r=4):
super(AsymBiChaFuse, self).__init__()
self.channels = channels
self.bottleneck_channels = int((channels // r))
self.topdown = nn.Sequential(nn.AdaptiveAvgPool2d(1), nn.Conv2d(in_channels=self.channels, out_channels... |
def show_models():
model_names = models.__all__
numbers = list(range(1, (len(model_names) + 1)))
print(tabulate({'No.': numbers, 'Model Names': model_names}, headers='keys')) |
class LlamaCache():
def __init__(self, capacity_bytes: int=(2 << 30)):
self.cache_state: OrderedDict[(Tuple[(int, ...)], 'LlamaState')] = OrderedDict()
self.capacity_bytes = capacity_bytes
def cache_size(self):
return sum([state.llama_state_size for state in self.cache_state.values()])
... |
class conv_2nV1(nn.Module):
def __init__(self, in_hc=64, in_lc=256, out_c=64, main=0):
super(conv_2nV1, self).__init__()
self.main = main
mid_c = min(in_hc, in_lc)
self.relu = nn.ReLU(True)
self.h2l_pool = nn.AvgPool2d((2, 2), stride=2)
self.l2h_up = nn.Upsample(scale... |
class Stats():
def __init__(self, constitution=1, strength=1, dexterity=1, intelligence=5, aggression=1.0, armour_class=1, speed=1):
self.constitution = constitution
self.strength = strength
self.dexterity = dexterity
self.armour_class = armour_class
self.speed = speed
... |
def add_plot_parser(subparsers):
parser_plt = subparsers.add_parser('plot_curve', help='parser for plotting curves')
parser_plt.add_argument('json_logs', type=str, nargs='+', help='path of train log in json format')
parser_plt.add_argument('--keys', type=str, nargs='+', default=['mAP_0.25'], help='the metri... |
def vgg_19(inputs, num_classes=1000, is_training=True, dropout_keep_prob=0.5, spatial_squeeze=True, scope='vgg_19', fc_conv_padding='VALID'):
with tf.variable_scope(scope, 'vgg_19', [inputs]) as sc:
end_points_collection = (sc.name + '_end_points')
with slim.arg_scope([slim.conv2d, slim.fully_connec... |
class Block(nn.Module):
def __init__(self, inplanes, planes, num_reps, stride=1, dilation=1, norm_layer=None, norm_kwargs=None, start_with_relu=True, grow_first=True, is_last=False):
super(Block, self).__init__()
norm_kwargs = (norm_kwargs if (norm_kwargs is not None) else {})
if ((planes !=... |
class Mass(Logged):
default_data = 'Au03'
def __init__(self, data=default_data, silent=False):
self.setup_logger(silent=silent)
path = os.getenv('KEPLER_DATA')
if (not path):
path = os.path.join(os.path.expanduser('~'), 'kepler', 'local_data')
self.logger.warning(... |
class Outcome(Enum):
ParseError = 0
CompilationError = 1
TestingError = 2
Success = 3
def to_json(self) -> Any:
return OUTCOME_MAP[self]
def from_json(cls, d: str) -> 'Outcome':
return OUTCOME_REV_MAP[d] |
class MemorizedMaxPooling2D(MaxPooling2D):
def __init__(self, *args, **kwargs):
super(MemorizedMaxPooling2D, self).__init__(*args, **kwargs)
self.idx = None
def _pooling_function(self, inputs, pool_size, strides, padding, data_format):
(output, self.idx) = pool2d_argmax(inputs, pool_size... |
class VerticalFlip(object):
def __call__(self, clip):
if isinstance(clip[0], np.ndarray):
return [np.flipud(img) for img in clip]
elif isinstance(clip[0], PIL.Image.Image):
return [img.transpose(PIL.Image.FLIP_TOP_BOTTOM) for img in clip]
else:
raise TypeE... |
def array_equal_lists(list1, list2):
ia.do_assert(isinstance(list1, list))
ia.do_assert(isinstance(list2, list))
if (len(list1) != len(list2)):
return False
for (a, b) in zip(list1, list2):
if (not np.array_equal(a, b)):
return False
return True |
class TFResNetEncoder(tf.keras.layers.Layer):
def __init__(self, config: ResNetConfig, **kwargs) -> None:
super().__init__(**kwargs)
self.stages = [TFResNetStage(config, config.embedding_size, config.hidden_sizes[0], stride=(2 if config.downsample_in_first_stage else 1), depth=config.depths[0], name... |
def convert_img(params):
(img_filepath, out_path, downsample) = params
img_file = os.path.split(img_filepath)[1]
out_filepath = os.path.join(out_path, img_file)
if (not os.path.exists(out_path)):
os.mkdir(out_path)
assert os.path.exists(out_path), 'Cannot create output folder: {}'.format(out... |
def get_vocab_list(data_root_path, vocab_root_path, text_min_count):
try:
vocab = get_vocab(vocab_root_path, text_min_count)
except FileNotFoundError:
train_all_text = get_content(data_root_path)
vocab = build_vocab(vocab_root_path, train_all_text, text_min_count)
return vocab |
def imagenet_convnext_small_in22ft1k_pretrained(output_dim):
model_args = dict(depths=[3, 3, 27, 3], dims=[96, 192, 384, 768], num_classes=output_dim)
model = load_small_convnext('/scratch/nvg7279/convnext_models/convnext_small_22k_1k_224.pth', **model_args)
return _convnext_replace_fc(model, output_dim) |
def mbv1():
device = torch.device('cpu')
cfg_file = 'tests/configs/mobilenet/mobilenet_v1_x1_0.yaml'
cfg.merge_from_file(cfg_file)
model = build_recognizer(cfg, device)
print(model) |
def astroNNAgesPath(dr=None):
if (dr is None):
dr = _default_dr()
if (int(dr) < 14):
raise ValueError('astroNN ages catalog for DR < 14 not available')
elif (int(dr) > 14):
return astroNNPath(dr=dr)
else:
specReduxPath = apogeeSpectroReduxDirPath(dr=dr)
return os.... |
def evaluate_regions(folder_predicted: str, folder_gt: str, regions: dict, processes=default_num_threads):
region_names = list(regions.keys())
files_in_pred = subfiles(folder_predicted, suffix='.nii.gz', join=False)
files_in_gt = subfiles(folder_gt, suffix='.nii.gz', join=False)
have_no_gt = [i for i in... |
def layer_flops_distribution(config, model):
num_sample = config.arch.num_flops_stats_sample
repo = {}
for _ in range(num_sample):
cur_flops = (config.arch.target_flops * 10)
while ((cur_flops > (config.arch.target_flops * 1.05)) or (cur_flops < (config.arch.target_flops * 0.95))):
... |
def view_samples(images):
if (type(images) == torch.tensor):
images = images.cpu().numpy()
(fig, axes) = plt.subplots(figsize=(30, 30), nrows=8, ncols=8, sharey=True, sharex=True)
for (ax, img) in zip(axes.flatten(), images):
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
... |
def main():
tf.set_random_seed(10)
with tf.Session() as sess:
rnn_cell = tf.nn.rnn_cell.BasicRNNCell(10)
initial_state = rnn_cell.zero_state(4, dtype=tf.float32)
inputs = tf.Variable(tf.random_uniform(shape=(4, 2, 100)), name='input')
inputs = tf.identity(inputs, 'input_node')
... |
def combine_tricks(trick_1, trick_2):
if all([(not trick_1.tricked), (not trick_2.tricked)]):
return _TrickInfo(False, None, None)
else:
batch_size = max(filter(None, [trick_1.batch_size, trick_2.batch_size]))
group_size = sum(filter(None, [trick_1.group_size, trick_2.group_size]))
... |
_module
class DoubleHeadRCNN(TwoStageDetector):
def __init__(self, reg_roi_scale_factor, **kwargs):
super().__init__(**kwargs)
self.reg_roi_scale_factor = reg_roi_scale_factor
def forward_dummy(self, img):
outs = ()
x = self.extract_feat(img)
if self.with_rpn:
... |
def shape_mergeable(x, expected_shape):
mergeable = True
if (is_array_like(x) and is_array_like(expected_shape)):
x = np.array(x)
if (len(x.shape) == len(expected_shape)):
for (s, s_ex) in zip(x.shape, expected_shape):
if ((s_ex is not None) and (s != s_ex)):
... |
def test_interpolation_potential_vcirc_outsidegrid():
rzpot = potential.interpRZPotential(RZPot=potential.MWPotential, rgrid=(0.01, 2.0, 201), logR=False, interpvcirc=True, zsym=False)
rs = [0.005, 2.5]
for r in rs:
vcdiff = numpy.fabs(((rzpot.vcirc(r) - potential.vcirc(potential.MWPotential, r)) / ... |
def arg_to_varname(st: str):
st = trim_preceding_hyphens(st)
st = st.replace('-', '_')
return st.split('=')[0] |
def _transpose(training_targets, num_loc_list):
for im_i in range(len(training_targets)):
training_targets[im_i] = torch.split(training_targets[im_i], num_loc_list, dim=0)
targets_level_first = []
for targets_per_level in zip(*training_targets):
targets_level_first.append(torch.cat(targets_p... |
def test_digits_cosine_sample():
model = SumRedundancySelection(100, 'cosine', optimizer='sample', random_state=0)
model.fit(X_digits)
assert_array_equal(model.ranking, digits_cosine_sample_ranking)
assert_array_almost_equal(model.gains, digits_cosine_sample_gains, 4)
assert_array_almost_equal(model... |
def make_types(filename, no_optimization):
extension_types = {}
for other_pyxfile in all_pyxfiles:
module = other_pyxfile[:(- 4)]
with open(other_pyxfile, mode='r', encoding='utf-8') as pyxfile:
code = pyxfile.read().split('\n')
for (i, line) in enumerate(reversed(code)):
... |
def indentation(logical_line, previous_logical, indent_char, indent_level, previous_indent_level):
c = (0 if logical_line else 3)
tmpl = ('E11%d %s' if logical_line else 'E11%d %s (comment)')
if (indent_level % 4):
(yield (0, (tmpl % ((1 + c), 'indentation is not a multiple of four'))))
indent_e... |
class HybridEmbed(nn.Module):
def __init__(self, backbone, img_size=224, patch_size=1, feature_size=None, in_chans=3, embed_dim=768):
super().__init__()
assert isinstance(backbone, nn.Module)
img_size = to_2tuple(img_size)
patch_size = to_2tuple(patch_size)
self.img_size = im... |
class ContextGating(nn.Module):
def __init__(self, dimension, add_batch_norm=True):
super(ContextGating, self).__init__()
self.fc = nn.Linear(dimension, dimension)
self.add_batch_norm = add_batch_norm
self.batch_norm = nn.BatchNorm1d(dimension)
def forward(self, x):
x1 = ... |
_registry(operator_type='Max')
class Max(Operator):
def __init__(self):
super().__init__() |
def load_cifar10():
((X_train, y_train), (X_test, y_test)) = cifar10.load_data()
(X_train, X_test) = (preprocess(X_train), preprocess(X_test))
(y_train, y_test) = (to_categorical(y_train), to_categorical(y_test))
(_, img_rows, img_cols, channel) = X_train.shape
if (K.image_data_format() == 'channels... |
class GraphPropPredDataset(object):
def __init__(self, name, root='dataset', meta_dict=None):
self.name = name
if (meta_dict is None):
self.dir_name = '_'.join(name.split('-'))
self.original_root = root
self.root = osp.join(root, self.dir_name)
master ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.