code stringlengths 101 5.91M |
|---|
class BoxSpaceSensor(Sensor):
def __init__(self, name: typing.Text, shape: typing.Tuple[(int, ...)], lower_bound: _FLOAT_OR_ARRAY=(- np.pi), upper_bound: _FLOAT_OR_ARRAY=np.pi, dtype=np.float64) -> None:
super(BoxSpaceSensor, self).__init__(name)
self._shape = shape
self._dtype = dtype
... |
_GENERATOR_REGISTRY.register()
class DefaultAnchorGenerator(nn.Module):
box_dim: int = 4
def __init__(self, *, sizes, aspect_ratios, strides, offset=0.5):
super().__init__()
self.strides = strides
self.num_features = len(self.strides)
sizes = _broadcast_params(sizes, self.num_fea... |
def imagenet_vit_small_pretrained(output_dim):
model = timm.create_model('vit_small_patch16_224', pretrained=True)
return _vit_replace_fc(model, output_dim) |
def main(_):
logging.info('Start')
experiments_path = FLAGS.experiments_path
config_name = FLAGS.config_name
config = common.load_config(os.path.join(experiments_path, config_name))
dataset = config['dataset']
classes = config['num_classes']
channels = config['channels']
epochs = config[... |
def run_inference(filepaths, IFrameCompressor: nn.Module, outputdir: Path, entropy_estimation: bool=False, trained_net: str='', description: str='', **args: Any):
with amp.autocast(enabled=args['half']):
with torch.no_grad():
if entropy_estimation:
metrics = eval_model_entropy_es... |
def create_row(time, data, metricname):
return namedtuple('DataRow', 'monitor')(namedtuple('DataRowMonitor', ('l', 'r'))(time, data[metricname])) |
class TorchCPUOpBuilder(CUDAOpBuilder):
def extra_ldflags(self):
if self.build_for_cpu:
return ['-fopenmp']
return ['-lcurand']
def cxx_args(self):
import torch
args = []
if (not self.build_for_cpu):
CUDA_LIB64 = os.path.join(torch.utils.cpp_extens... |
class Bert4FnFunction(BaseFunction):
def __init__(self):
super().__init__()
def forward(self, batch=None):
(input_ids, attention_mask, word_pos, label_ids) = batch
sequence_output = self.bert(input_ids=input_ids, attention_mask=attention_mask)[0]
(batch_size, max_len, feat_dim) =... |
class XHead(BaseModule):
def __init__(self, in_channels: int, feat_channels: Sequence[int], x_channels: int, x: str) -> None:
super().__init__()
conv_layers = []
for ch in feat_channels:
conv_layers.append(ConvModule(in_channels=in_channels, out_channels=ch, kernel_size=3, paddin... |
class KerasModel(BaseModel):
def __init__(self, model, **kwargs):
self.component = None
self._model = model
if (not isinstance(model, tf.keras.Model)):
self._model_object = tf.keras.models.load_model(self._model)
else:
self._model_object = self._model
... |
class TestUnroll3qOrMore(QiskitTestCase):
def test_ccx(self):
qr1 = QuantumRegister(2, 'qr1')
qr2 = QuantumRegister(1, 'qr2')
circuit = QuantumCircuit(qr1, qr2)
circuit.ccx(qr1[0], qr1[1], qr2[0])
dag = circuit_to_dag(circuit)
pass_ = Unroll3qOrMore()
after_da... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
def test_warning_when_missing_initializer():
wide = Wide(100, 1)
deeptabular = TabMlp(column_idx=column_idx, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):], mlp_hidden_dims=[32, 16], mlp_dropout=[0.5, 0.5])
deeptext = BasicRNN(vocab_size=vocab_size, embed_dim=32, padding_idx=0)
model = Wi... |
def isolate_glossary(word, glossary):
if ((word == glossary) or (glossary not in word)):
return [word]
else:
splits = word.split(glossary)
segments = [segment.strip() for split in splits[:(- 1)] for segment in [split, glossary] if (segment != '')]
return ((segments + [splits[(- 1... |
def build_graph(graph):
node_map = {}
for n in graph.node:
node = init_node(n)
node_map[n.name] = node
for n in node_map:
for i in node_map[n]['node'].input:
if (':' in i):
i = i[:i.find(':')]
i = i.lstrip('^')
if (i not in node_map... |
def add_hist_seq(df: 'SparkDataFrame', cols: List[str], user_col: str, sort_col: str, min_len: int, max_len: int, num_seqs: int) -> 'SparkDataFrame':
return callZooFunc('float', 'addHistSeq', df, cols, user_col, sort_col, min_len, max_len, num_seqs) |
class Struc2VecTrainer(VecTrainer):
def __init__(self, embed_dim, train_data, city, tester):
super().__init__(embed_dim, train_data, city, tester)
self.vec_model = Struc2Vec(num_walks=200)
def save_model(self, model):
obj = {'embed_dim': self.embed_dim, 'city': self.city, 'distmult': mod... |
def process_reference_line(working_line, journals_matches, pprint_repnum_len, pprint_repnum_matchtext, publishers_matches, removed_spaces, standardised_titles, kbs):
if (((len(journals_matches) + len(pprint_repnum_len)) + len(publishers_matches)) == 0):
tagged_line = working_line
else:
startpos ... |
class Node(object):
def __init__(self, name, kind, layer=None):
self.name = name
self.kind = kind
self.layer = (LayerAdapter(layer, kind) if layer else None)
self.parents = []
self.children = []
self.data = None
self.output_shape = None
self.metadata =... |
def skintone_mad(data_file):
with open(data_file, 'r') as f:
data = json.load(f)
mads = []
all_values = []
for prompt in data:
model_values = data[prompt]
scores = []
avg_tone = []
for skintone in range(1, 11):
scores.append(0)
total_tones = 0
... |
def create_conv2_model(input_dim, input_channels=1, num_kernels=None, kernel_size=4, pool_size=2, n=1):
if (num_kernels is None):
num_kernels = [8, 16]
modules = [('conv1', nn.Conv2d(input_channels, num_kernels[0], kernel_size, bias=False)), ('repu1', RePU(n)), ('pool1', nn.MaxPool2d(pool_size)), ('conv... |
.skipif((not hasattr(m, 'load_monostate_variant')), reason='no std::monostate')
def test_variant_monostate(doc):
assert (m.load_monostate_variant(None) == 'std::monostate')
assert (m.load_monostate_variant(1) == 'int')
assert (m.load_monostate_variant('1') == 'std::string')
assert (m.cast_monostate_vari... |
class InceptConv(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size, stride, padding):
super(InceptConv, self).__init__()
self.conv = nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
self.bn ... |
def make_data_loader(dataset, batch_size, args):
shuffle = args.shuffle
if shuffle:
sampler = data_utils.samplers.RandomSampler(dataset, replacement=True, num_samples=(batch_size * args.train_iters))
else:
sampler = torch.utils.data.SequentialSampler(dataset)
world_size = torch.distribut... |
def overlap(dataset0, dataset1, args):
word_set0 = set()
word_set1 = set()
for d0 in dataset0:
if (args['type'] == 'single'):
sentence = d0['sentence']
elif (args['type'] == 'pair'):
sentence0 = d0['sentence1']
sentence1 = d0['sentence2']
sente... |
def wrap_module(module, *module_args, **module_kwargs):
def wrap(*args, **kwargs):
model = module(*module_args, **module_kwargs)
return model(*args, **kwargs)
return wrap |
def _get_city_pairs(folder, split='train'):
def get_path_pairs(img_folder, mask_folder):
img_paths = []
mask_paths = []
for (root, _, files) in os.walk(img_folder):
for filename in files:
if filename.startswith('._'):
continue
i... |
class TestGraphInputOutputDetection(unittest.TestCase):
tf.compat.v1.disable_v2_behavior()
mb_fp32_pb_url = '
pb_path = '/tmp/.neural_compressor/mobilenet_fp32.pb'
platform = platform.system().lower()
if (platform == 'windows'):
pb_path = 'C:\\tmp\\.neural_compressor\\mobilenet_fp32.pb'
... |
def setup_args():
description = 'Collect codec metrics and performances.'
parser = argparse.ArgumentParser(description=description)
subparsers = parser.add_subparsers(dest='codec', help='Select codec')
subparsers.required = True
parser.add_argument('image', type=str, help='image filepath')
parse... |
def set_user_categories(user_id, user):
conn = getDb()
with closing(conn.cursor()) as cur:
cur.execute('DELETE FROM user_categories WHERE user_ID = %s', [user_id])
data = [(user_id, category_id) for category_id in user.categories]
cur.executemany('INSERT INTO user_categories VALUES(%s, %... |
(version='2.0')
def check_config(prune_config):
assert (prune_config['start_step'] >= 0), 'start_step should be greater than 0'
assert (prune_config['end_step'] >= (- 1)), 'end_step should be greater than 0'
assert (prune_config['end_step'] >= prune_config['start_step']), 'end_step should be greater than st... |
class Aggregation(torch.autograd.Function):
def forward(ctx, A, X, W):
out = torch.mm(X, W)
out = torch.mm(A, out)
return out
def backward(ctx, d_output):
pass
return (None, None, None) |
def get_mol(smiles):
mol = Chem.MolFromSmiles(smiles)
if (mol is None):
return None
Chem.Kekulize(mol)
return mol |
def chamfer_loss_separate(output, target, weight=10000.0, phase='train', debug=False):
from chamferdist.chamferdist import ChamferDistance
cdist = ChamferDistance()
(model2scan, scan2model, idx1, idx2) = cdist(output, target)
if (phase == 'train'):
return (model2scan, scan2model, idx1, idx2)
... |
class MultiscaleDiscriminator(nn.Module):
def modify_commandline_options(parser, is_train):
assert isinstance(parser, argparse.ArgumentParser)
parser.add_argument('--num_D', type=int, default=2, help='number of discriminators to be used in multiscale')
parser.add_argument('--norm_D', type=st... |
def generate_signature(features, predictions):
if (not isinstance(features, dict)):
raise ValueError(('generate_signature excepted features to be dict, but got %s' % features))
inputs = dict(zip(features, map((lambda x: utils.build_tensor_info(x)), features.values())))
if (not isinstance(predictions... |
def make_handler(base_url, wiki_version, models, tagger_ner, argss, logger):
class GetHandler(BaseHTTPRequestHandler):
def __init__(self, *args, **kwargs):
self.model = models
self.tagger_ner = tagger_ner
self.argss = argss
self.logger = logger
sel... |
class InProcessCommunicator(Communicator):
BYTES_PER_ELEMENT = 8
tls = threading.local()
mailbox = None
barrier = None
lock = threading.Lock()
def initialize(cls, rank, world_size, init_ttp=False):
cls.tls.instance = cls(rank, world_size)
def __init__(self, rank, world_size, init_ttp... |
def specificity(classify=(lambda document: False), documents=[]):
(TP, TN, FP, FN) = confusion_matrix(classify, documents)
return (float(TN) / ((TN + FP) or 1)) |
class GATSummarizeModel(nn.Module):
def __init__(self, config):
super(GATSummarizeModel, self).__init__()
self.config = config
self.use_nfeat = self.config.node_emb_layer['use_nfeature']
self.use_cuda = self.config.use_cuda
self.graph_config = getattr(self.config, 'gat')
... |
def test_prediction_with_dataframe(model, data_with_covariates):
model.predict(data_with_covariates, fast_dev_run=True) |
def build_densepose_head(cfg: CfgNode, input_channels: int):
from .roi_heads.registry import ROI_DENSEPOSE_HEAD_REGISTRY
head_name = cfg.MODEL.ROI_DENSEPOSE_HEAD.NAME
return ROI_DENSEPOSE_HEAD_REGISTRY.get(head_name)(cfg, input_channels) |
class TestJumanjiSpecsToGymSpaces():
def test_array(self) -> None:
jumanji_spec = specs.Array((1, 2), jnp.int32)
gym_space = gym.spaces.Box((- np.inf), np.inf, (1, 2), jnp.int32)
converted_spec = specs.jumanji_specs_to_gym_spaces(jumanji_spec)
assert (type(converted_spec) == type(gym... |
def exponential_fit(counts, mode, target_day=np.array([1])):
predicted_counts = []
for i in range(len(counts)):
if (mode == 'eval_mode'):
num_days_back = target_day[(- 1)]
train_ts = counts[i][:(- num_days_back)]
elif (mode == 'predict_future'):
train_ts = cou... |
def string_find(args):
params = functionParams(args, ('source', 'target', 'start', 'plain'))
source = params.get('source', '')
pattern = params.get('target', '')
start = (int(('0' + params.get('start', 1))) - 1)
plain = int(('0' + params.get('plain', 1)))
if ((source == '') or (pattern == '')):
... |
def stl10_root(_extracted=False):
CLASS_NAMES = ('airplane', 'bird')
ARCHIVE_NAME = 'stl10_binary'
NUM_FOLDS = 10
def mock_target(attr, partial='torchvision.datasets.stl10.STL10'):
return f'{partial}.{attr}'
def make_binary_file(num_elements, root, name):
file = os.path.join(root, na... |
class CIFAR10ReinitServer(ReinitServer):
def init_test_loader(self):
self.test_loader = get_data_loader(EXP_NAME, data_type='test', batch_size=1000, num_workers=8, pin_memory=True)
def init_clients(self):
rand_perm = torch.randperm(NUM_TRAIN_DATA).tolist()
indices = []
len_slice ... |
class BitextOutput(object):
def __init__(self, output_file, backwards, right_to_left, bpe_symbol, prefix_len=None, target_prefix_frac=None, source_prefix_frac=None):
(source, hypo, score, target, pos_score) = reprocess(output_file)
if backwards:
self.hypo_fracs = source_prefix_frac
... |
def to_md(comment_dict):
doc = ''
if ('short_description' in comment_dict):
doc += comment_dict['short_description']
doc += '\n\n'
if ('long_description' in comment_dict):
doc += md_parse_line_break(comment_dict['long_description'])
doc += '\n'
if (('Args' in comment_dict... |
class upBlock(nn.Module):
def __init__(self, in_c, out_c, conv_num=2):
super().__init__()
additional_conv = []
layer_length = 4
for i in range(1, (conv_num + 1)):
additional_conv += [nn.ConstantPad2d((2, 1, 2, 1), 0), nn.ConvTranspose2d(out_c, out_c, kernel_size=4, stride... |
def setup_multi_processes(cfg):
logger = get_root_logger()
if (platform.system() != 'Windows'):
mp_start_method = cfg.get('mp_start_method', None)
current_method = mp.get_start_method(allow_none=True)
if (mp_start_method in ('fork', 'spawn', 'forkserver')):
logger.info(f'Mult... |
class MQF2Distribution(Distribution):
def __init__(self, picnn: torch.nn.Module, hidden_state: torch.Tensor, prediction_length: int, is_energy_score: bool=True, es_num_samples: int=50, beta: float=1.0, threshold_input: float=100.0, validate_args: bool=False) -> None:
self.picnn = picnn
self.hidden_s... |
def shufflenet_v2_x2_0(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ShuffleNetV2:
return _shufflenetv2('shufflenetv2_x2.0', pretrained, progress, [4, 8, 4], [24, 244, 488, 976, 2048], **kwargs) |
def resnet101_largefov(x, num_cls, momentum=0.9, eps=1e-05, use_global_stats=False, name=None, lr_mult=10, reuse=None):
name = ('' if (name is None) else name)
x = _Resnet(x, (3, 4, 23, 3), (64, 256, 512, 1024, 2048), True, momentum, eps, use_global_stats, strides=(1, 2, 1, 1), dilates=(1, 1, 2, 4), name=name, ... |
class nnUNetTrainerV2_warmup(nnUNetTrainerV2):
def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None, unpack_data=True, deterministic=True, fp16=False):
super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,... |
def _unordered_query_matcher(request1, request2):
if (request1.query == request2.query):
return True
dict1 = dict(request1.query)
dict2 = dict(request2.query)
if (dict1 == dict2):
return True
if (dict1.keys() != dict2.keys()):
return False
for (key, value) in dict1.items(... |
class Node():
def __init__(self, x_ind, y_ind, yaw_ind, direction, x_list, y_list, yaw_list, directions, steer=0.0, parent_index=None, cost=None):
self.x_index = x_ind
self.y_index = y_ind
self.yaw_index = yaw_ind
self.direction = direction
self.x_list = x_list
self.y... |
class MLPDir(BaseDir):
def __init__(self, in_channels, hidden_channels, n_mods, out_channels, **kwargs):
super().__init__(**kwargs)
in_channels += 6
mlp = []
for _ in range((n_mods - 1)):
mlp.append(nn.Linear(in_channels, hidden_channels))
mlp.append(nn.ReLU()... |
class ActionHistory(object):
def __init__(self, history: List[Action], action_space_size: int):
self.history = list(history)
self.action_space_size = action_space_size
def clone(self):
return ActionHistory(self.history, self.action_space_size)
def add_action(self, action: Action):
... |
def remove_page_boundary_lines(docbody):
number_head_lines = number_foot_lines = 0
if (not document_contains_text(docbody)):
return docbody
page_break_posns = get_page_break_positions(docbody)
number_head_lines = get_number_header_lines(docbody, page_break_posns)
number_foot_lines = get_numb... |
def run_app():
app = QtWidgets.QApplication(sys.argv)
MainWindow = QtWidgets.QMainWindow()
ui = Ui_MainWindow(MainWindow)
MainWindow.showMaximized()
sys.exit(app.exec_()) |
def model_fn(features, mode, params):
hub_module = params['hub_module']
finetune_layer = params['finetune_layer']
num_classes = params['num_classes']
initial_learning_rate = params['initial_learning_rate']
momentum = params['momentum']
lr_decay_factor = params['lr_decay_factor']
decay_steps ... |
.parametrize('experiment_name', ['chem1', 'chem2', 'chem3'])
.parametrize('model_name', ['compfs1', 'lasso'])
def test_chem(experiment_name: str, model_name: str) -> None:
experiment_no = '1'
experiment_helper(experiment_name=experiment_name, model_name=model_name, experiment_no=experiment_no) |
def lstsq(A, b):
P = array_map(np.linalg.pinv, [A], (A.ndim - 2))
return array_map(np.dot, [P, b], (A.ndim - 2)) |
def _assert_valid_results(results):
assert isinstance(results, dict)
assert len(results)
model = list(results.keys())[0]
assert ('epochs' in results[model])
assert isinstance(results[model]['epochs'], dict)
assert len(results[model]['epochs']) |
class Ya(BaseBow):
def __init__(self):
super().__init__('ya', weight=1, damage=D.Dice.from_str('d7'), material=M.Metal, hit=0) |
class LabelEncoder(object):
def __init__(self, try_to_fit_numeric=False):
self.lbl = sk_preproc.LabelEncoder()
self._try_to_fit_numeric = try_to_fit_numeric
def fit(self, x):
self.lbl.fit(x)
if self._try_to_fit_numeric:
logger.debug('Try to fit numeric in LabelEncoder... |
class EncodingModel(object):
def __init__(self, feature_list, name, aux, feature_types, centroid_types, must_link_rules, must_not_link_rules):
self.feature_list = feature_list
self.name = name
self.aux = aux
self.feature_types = feature_types
self.centroid_types = centroid_ty... |
class ResNet_FeatureExtractor(nn.Module):
def __init__(self, input_channel, output_channel=512):
super(ResNet_FeatureExtractor, self).__init__()
self.ConvNet = ResNet(input_channel, output_channel, BasicBlock, [1, 2, 5, 3])
def forward(self, input):
return self.ConvNet(input) |
class DiscriminatorModel2(nn.Module):
def __init__(self):
super(DiscriminatorModel2, self).__init__()
input_dim = (784 + 100)
output_dim = 1
self.label_embedding = nn.Embedding(10, 100)
self.hidden_layer1 = nn.Sequential(nn.Linear(input_dim, 1024), nn.LeakyReLU(0.2), nn.Dropo... |
class TestOptimizerInterface(TfGraphTestCase):
def test_tf_make_optimizer_with_type(self):
optimizer_type = tf.compat.v1.train.AdamOptimizer
lr = 0.123
optimizer = make_optimizer(optimizer_type, learning_rate=lr, name='testOptimizer')
assert isinstance(optimizer, optimizer_type)
... |
class CIFDensity(Density):
def __init__(self, prior, p_u_density, bijection, q_u_density):
super().__init__()
self.bijection = bijection
self.prior = prior
self.p_u_density = p_u_density
self.q_u_density = q_u_density
def p_parameters(self):
return [*self.bijectio... |
def test_uniform_range_as_range():
from lasagne.init import Uniform
sample = Uniform((0.0, 1.0)).sample((300, 400))
assert (sample.shape == (300, 400))
assert (0.0 <= sample.min() < 0.1)
assert (0.9 < sample.max() <= 1.0) |
def _demo_mm_inputs(input_shape, num_classes):
(N, C, H, W) = input_shape
rng = np.random.RandomState(0)
imgs = rng.rand(*input_shape)
segs = rng.randint(low=0, high=(num_classes - 1), size=(N, 1, H, W)).astype(np.uint8)
img_metas = [{'img_shape': (H, W, C), 'ori_shape': (H, W, C), 'pad_shape': (H, ... |
def resnet_l4(relu_end=True):
model = resnet101(pretrained=True)
l4 = model.layer4
if (not relu_end):
l4[(- 1)].relu_end = False
l4[0].conv2.stride = (1, 1)
l4[0].downsample[0].stride = (1, 1)
return l4 |
class ImageNetSR(Dataset):
def __init__(self, size=None, degradation=None, downscale_f=4, min_crop_f=0.5, max_crop_f=1.0, random_crop=True):
self.base = self.get_base()
assert size
assert (size / downscale_f).is_integer()
self.size = size
self.LR_size = int((size / downscale_... |
class MolDataset(Dataset):
def __init__(self, keys, data_dir, id_to_y, random_rotation=0.0, pos_noise_std=0.0):
self.keys = keys
self.data_dir = data_dir
self.id_to_y = id_to_y
self.random_rotation = random_rotation
self.amino_acids = ['ALA', 'ARG', 'ASN', 'ASP', 'ASX', 'CYS'... |
def calc_prf(match, gold, test):
if (gold == 0):
if (test == 0):
return (1.0, 1.0, 1.0)
return (0.0, 1.0, 0.0)
if ((test == 0) or (match == 0)):
return (0.0, 0.0, 0.0)
precision = (match / float(test))
recall = (match / float(gold))
try:
fscore = ((2 * mat... |
def create_weightspace(value):
num = value['num']
space = []
sum = 0
rand = 1
for i in range((num - 1)):
while ((sum + rand) >= 1):
rand = round(np.random.rand(), 2)
space.append(rand)
sum += rand
rand = 1
space.append(round((1 - sum), 2))
return s... |
class AnyOf(SymbolMatcher):
def __init__(self, bind_name: str, matchers: List[SymbolMatcher]) -> None:
super().__init__(bind_name)
self.matchers = matchers
def matches(self, sym: Symbol) -> Optional[Dict[(str, Any)]]:
bindings = None
for matcher in self.matchers:
matc... |
class SelectPercentileClassificationTest(unittest.TestCase):
def test_default_configuration(self):
(transformation, original) = _test_preprocessing(SelectPercentileClassification)
self.assertEqual(transformation.shape[0], original.shape[0])
self.assertEqual(transformation.shape[1], int((orig... |
def main():
if (args.data_name == 'train'):
if (args.h_flip == 1):
with open('{}/split{}/train_224_h_flip.txt'.format(args.data_dir, args.split_num), 'r') as f:
lines = f.readlines()
f_ = open('{}/split{}/train_224_h_flip.lst'.format(args.out_dir, args.split_num),... |
class RotationTransform():
def __init__(self, angle):
self.angle = angle
def __call__(self, x):
return TorchVisionFunc.rotate(x, self.angle, fill=(0,)) |
def explained_variance_1d(ypred, y, valids=None):
if (valids is not None):
ypred = ypred[valids.astype(np.bool)]
y = y[valids.astype(np.bool)]
assert ((y.ndim == 1) and (ypred.ndim == 1))
vary = np.var(y)
if np.isclose(vary, 0):
if (np.var(ypred) > 0):
return 0
... |
def evaluate(net_apply, params, net_state, train_set, test_set, predict_fn, metrics_fns, log_prior_fn):
(net_state, test_predictions) = onp.asarray(predict_fn(net_apply, params, net_state, test_set))
(net_state, train_predictions) = onp.asarray(predict_fn(net_apply, params, net_state, train_set))
test_stats... |
def load_data(data_dir, partition, url):
download_and_extract_archive(url, data_dir)
all_data = []
all_label = []
for h5_name in glob.glob(os.path.join(data_dir, 'modelnet40_ply_hdf5_2048', ('ply_data_%s*.h5' % partition))):
with h5py.File(h5_name, 'r') as f:
data = f['data'][:].asty... |
class QXIconButton(QPushButton):
def __init__(self, icon, tooltip=None, shortcut=None, click_func=None, first_repeat_delay=300, repeat_delay=20):
super().__init__(icon, '')
self.setIcon(icon)
if (shortcut is not None):
tooltip = f"{tooltip} ( {StringsDB['S_HOT_KEY']}: {shortcut} ... |
class FlaxUpsample2D(nn.Module):
out_channels: int
dtype: jnp.dtype = jnp.float32
def setup(self):
self.conv = nn.Conv(self.out_channels, kernel_size=(3, 3), strides=(1, 1), padding=((1, 1), (1, 1)), dtype=self.dtype)
def __call__(self, hidden_states):
(batch, height, width, channels) = ... |
def load_tf_linear(weights, layer):
if isinstance(weights, list):
if (len(weights) == 2):
layer.bias.data = torch.tensor(weights[1]).view(layer.bias.data.shape)
weights = weights[0]
layer.weight.data = torch.tensor(weights).transpose((- 1), 0).view(layer.weight.data.shape) |
class Model(object):
def __init__(self, config, scope, emb_mat, rep=True):
self.scope = scope
self.config = config
self.emb_mat = emb_mat
self.global_step = tf.get_variable('global_step', shape=[], dtype='int32', initializer=tf.constant_initializer(0), trainable=False)
if (co... |
class TfExampleDecoderTest(tf.test.TestCase):
def _EncodeImage(self, image_tensor, encoding_type='jpeg'):
with self.test_session():
if (encoding_type == 'jpeg'):
image_encoded = tf.image.encode_jpeg(tf.constant(image_tensor)).eval()
elif (encoding_type == 'png'):
... |
def pack_innermost_dim_as_hex_string(ndarray, dtype, pad_to_nbits, reverse_inner=False, prefix='0x'):
if ((type(ndarray) != np.ndarray) or (ndarray.dtype != np.float32)):
ndarray = np.asarray(ndarray, dtype=np.float32)
def fun(x):
return array2hexstring(x, dtype, pad_to_nbits, reverse=reverse_in... |
def display_in_terminal(obj):
try:
import PIL
from libsixel import sixel_output_new, sixel_dither_new, sixel_dither_initialize, sixel_dither_set_palette, sixel_dither_set_pixelformat, sixel_dither_get, sixel_encode, sixel_dither_unref, sixel_output_unref, SIXEL_PIXELFORMAT_RGBA8888, SIXEL_PIXELFORMA... |
def make_dataloaders(data_with_covariates, **kwargs):
training_cutoff = '2016-09-01'
max_encoder_length = 4
max_prediction_length = 3
kwargs.setdefault('target', 'volume')
kwargs.setdefault('group_ids', ['agency', 'sku'])
kwargs.setdefault('add_relative_time_idx', True)
kwargs.setdefault('ti... |
def apply_pq_coupler_config_settings(schema, config):
new_schema = []
flattened = False
for layer in schema:
if (layer['type'] == 'flatten'):
flattened = True
if (layer.get('num_u_channels', 0) > 0):
layer = {**layer, 'p_coupler': get_p_coupler_config(config, flattene... |
def aggregate_rank_corrs(full_df, task, num_layers, METRICS, sub_df_fn, list_layers=None):
if (list_layers == None):
list_layers = list(range(num_layers))
rho = {metric: [] for metric in METRICS}
rho_p = {metric: [] for metric in METRICS}
tau = {metric: [] for metric in METRICS}
tau_p = {met... |
class RetinaNetModule(torch.nn.Module):
def __init__(self, cfg, in_channels, BBAM=False):
super(RetinaNetModule, self).__init__()
self.cfg = cfg.clone()
self.BBAM = BBAM
anchor_generator = make_anchor_generator_retinanet(cfg)
head = RetinaNetHead(cfg, in_channels)
box... |
class Bottleneck(_Bottleneck):
expansion = 4
def __init__(self, inplanes, planes, groups=1, base_width=4, base_channels=64, radix=2, reduction_factor=4, avg_down_stride=True, **kwargs):
super(Bottleneck, self).__init__(inplanes, planes, **kwargs)
if (groups == 1):
width = self.planes... |
class DownAttBlock(nn.Module):
def __init__(self, in_channels, out_channels, length):
super(DownAttBlock, self).__init__()
self.pool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
self.res_blocks = ResBlockSequence(in_channels=in_channels, out_channels=out_channels, length=length)
de... |
def m_elbo(model, x, K=1):
(qz_xs, px_zs, zss) = model(x)
(lpx_zs, klds) = ([], [])
for (r, qz_x) in enumerate(qz_xs):
kld = kl_divergence(qz_x, model.pz(*model.pz_params))
klds.append(kld.sum((- 1)))
for d in range(len(px_zs)):
lpx_z = px_zs[d][d].log_prob(x[d]).view(*px... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.