code stringlengths 101 5.91M |
|---|
class ModelOutputTester(unittest.TestCase):
def test_get_attributes(self):
x = ModelOutputTest(a=30)
self.assertEqual(x.a, 30)
self.assertIsNone(x.b)
self.assertIsNone(x.c)
with self.assertRaises(AttributeError):
_ = x.d
def test_index_with_ints_and_slices(sel... |
class Logger(object):
def __init__(self, output_name):
dirname = os.path.dirname(output_name)
if (not os.path.exists(dirname)):
os.mkdir(dirname)
self.log_file = open(output_name, 'w')
self.infos = {}
def append(self, key, val):
vals = self.infos.setdefault(ke... |
class TestSoftCopyAttention(object):
def copy_source(self):
return float_tensor_var([[0.0, 0.2, 0.4, 0.6], [0.1, 0.3, 0.5, 0.7], [0.1, 0.2, 0.3, 0.4], [0.01, 0.02, 0.03, 0.04], [0.01, 0.03, 0.05, 0.07]])
def alignments(self):
values = GPUVariable(torch.LongTensor([[1, 3], [1, 1], [3, 2], [3, 0],... |
def ResNet18(in_channels, num_classes):
return ResNet(BasicBlock, [2, 2, 2, 2], in_channels=in_channels, num_classes=num_classes) |
def get_model(input_shape, weights_dir, resume, bayesian, vnet, prior_std, kernel_size, activation, padding, kl_alpha, kl_start_epoch, kl_alpha_increase_per_epoch, ensemble, num_gpus, initial_epoch, scale_factor=1, weights_path=None):
os.makedirs((weights_dir + '/bayesian'), exist_ok=True)
os.makedirs((weights_... |
def cnn_7layer_imagenet(in_ch=3, in_dim=32, width=64, linear_size=512):
model = nn.Sequential(nn.Conv2d(in_ch, width, 3, stride=1, padding=1), nn.BatchNorm2d(width), nn.ReLU(), nn.Conv2d(width, width, 3, stride=1, padding=1), nn.BatchNorm2d(width), nn.ReLU(), nn.Conv2d(width, (2 * width), 3, stride=2, padding=1), n... |
def _int_list_from_bigint(bigint):
if (bigint < 0):
raise error.Error('Seed must be non-negative, not {}'.format(bigint))
elif (bigint == 0):
return [0]
ints = []
while (bigint > 0):
(bigint, mod) = divmod(bigint, (2 ** 32))
ints.append(mod)
return ints |
def main():
parser = HfArgumentParser(TensorFlowBenchmarkArguments)
benchmark_args = parser.parse_args_into_dataclasses()[0]
benchmark = TensorFlowBenchmark(args=benchmark_args)
try:
benchmark_args = parser.parse_args_into_dataclasses()[0]
except ValueError as e:
arg_error_msg = 'Arg... |
class DualkSchurFunctions(KBoundedQuotientBasis):
def __init__(self, kBoundedRing):
KBoundedQuotientBasis.__init__(self, kBoundedRing, 'dks')
kHLP = kBoundedRing.kHallLittlewoodP()
self.module_morphism(self._dks_to_khlp_on_basis, codomain=kHLP).register_as_coercion()
kHLP.module_morp... |
def load_real_images():
images = []
src_dir = os.path.join(datadir, src_instance_name)
with open(os.path.join(src_dir, 'transforms_train.json')) as f:
data_src = [x['file_path'] for x in json.load(f)['frames']]
tgt_dir = os.path.join(datadir, tgt_instance_name)
if (args.dataset == 'photoshap... |
class TorchPoseRepresentation(PoseRepresentation):
def __init__(self, header: PoseHeader, rep_modules1: List=[], rep_modules2: List=[], rep_modules3: List=[]):
super(TorchPoseRepresentation, self).__init__(header, rep_modules1, rep_modules2, rep_modules3)
self.limb_pt1s = torch.tensor(self.limb_pt1s... |
def train(opt, netG):
if (opt.vae_levels < (opt.scale_idx + 1)):
D_curr = getattr(networks_2d, opt.discriminator)(opt).to(opt.device)
if ((opt.netG != '') and (opt.resumed_idx == opt.scale_idx)):
D_curr.load_state_dict(torch.load('{}/netD_{}.pth'.format(opt.resume_dir, (opt.scale_idx - 1... |
def quantize_node(root_module, graph, node, activation_post_process):
def module_has_qparams_attr_with_index(module, qparams, i):
for name in qparams.keys():
if hasattr(module, (name + str(i))):
return True
return False
def get_next_qparams_idx(module, qparams):
... |
def c(alf, bet, i, j, gn=1):
f = _c(alf, bet, i, j)
return (f if (gn == 1) else ((gn(alf, bet, j) / gn(alf, bet, i)) * f)) |
class ChunkStream():
def __init__(self, fp):
self.fp = fp
self.queue = []
def read(self):
cid = None
if self.queue:
(cid, pos, length) = self.queue.pop()
self.fp.seek(pos)
else:
s = self.fp.read(8)
cid = s[4:]
po... |
class Treccani(Benchmark):
def __init__(self, dimensions=2):
Benchmark.__init__(self, dimensions)
self._bounds = list(zip(([(- 5.0)] * self.N), ([5.0] * self.N)))
self.custom_bounds = [((- 2), 2), ((- 2), 2)]
self.global_optimum = [[(- 2.0), 0.0]]
self.fglob = 0
def fun(s... |
def gaussian_pdf(sd, x):
if (sd <= 0):
raise ValueError('standard deviation must be positive but is {}'.format(sd))
else:
return ((np.e ** ((- 0.5) * ((x / sd) ** 2))) / sd) |
class FiveCrops(object):
def __init__(self, size, mean=[0.0, 0.0, 0.0], std=[1.0, 1.0, 1.0], interpolation=Image.BILINEAR, tenCrops=False):
self.size = size
self.interpolation = interpolation
self.mean = mean
self.std = std
self.to_Tensor = ToTensor()
self.normalize =... |
def test_compute_class_weight():
y = np.asarray([2, 2, 2, 3, 3, 4])
classes = np.unique(y)
cw = compute_class_weight('balanced', classes=classes, y=y)
class_counts = np.bincount(y)[2:]
assert_almost_equal(np.dot(cw, class_counts), y.shape[0])
assert (cw[0] < cw[1] < cw[2]) |
def bn_weight_change(bn: torch.nn.Module):
bw_shape = bn.weight.shape
delattr(bn, 'weight')
delattr(bn, 'bias')
delattr(bn, 'running_var')
delattr(bn, 'running_mean')
bn.register_buffer('weight', torch.rand(bw_shape))
bn.register_buffer('bias', torch.rand(bw_shape))
bn.register_buffer('r... |
class SchemeHomset_points_abelian_variety_field(SchemeHomset_points_projective_field):
def _element_constructor_(self, *v, **kwds):
if (len(v) == 1):
v = v[0]
return self.codomain()._point(self.extended_codomain(), v, **kwds)
def _repr_(self):
s = ('Abelian group of points on... |
def save(saver, sess, logdir):
model_name = 'model.ckpt'
checkpoint_path = os.path.join(logdir, model_name)
if (not os.path.exists(logdir)):
os.makedirs(logdir)
saver.save(sess, checkpoint_path, write_meta_graph=False)
print('The weights have been converted to {}.'.format(checkpoint_path)) |
class TestStyleGAN2Generator():
def setup_class(cls):
cls.default_cfg = dict(out_size=64, style_channels=16, num_mlps=4, channel_multiplier=1)
def test_stylegan2_g_cpu(self):
g = StyleGANv2Generator(**self.default_cfg)
res = g(None, num_batches=2)
assert (res.shape == (2, 3, 64, ... |
def denormalize(sql, schema, return_parse_tree=False, **kwargs):
dn = Denormalizer(schema, **kwargs)
ast = (sql if isinstance(sql, dict) else parse(sql))
dn.denormalize(ast)
if return_parse_tree:
return (ast, dn.contains_self_join)
else:
dn_sql = format(ast, schema, quote_values=not_... |
def create_exp_dir(path, scripts_to_save=None):
import time
time.sleep(2)
if (not os.path.exists(path)):
os.makedirs(path)
print('Experiment dir : {}'.format(path))
if (scripts_to_save is not None):
os.makedirs(os.path.join(path, 'scripts'))
for script in scripts_to_save:
... |
.parametrize('ctx, func_name', ctxs)
.parametrize('w_shape , channel_axis', [((8, 4, 3, 3), 0), ((32, 16, 3, 3), (- 4)), ((16, 1), 1), ((8, 4, 16), (- 1)), ((4, 2, 8), 2)])
.parametrize('eps', [1e-05])
.parametrize('output_stat', [False])
def test_weight_standardization_double_backward(rng, ctx, func_name, w_shape, cha... |
def process_channel(channelxml: ET.ElementTree, resolver: ResolverType, track_progress: bool=False) -> tuple[(str, list[float], list[Sample], list[Parameter])]:
channel = channelxml.getroot()
inputfile = channel.attrib.get('InputFile', '')
histopath = channel.attrib.get('HistoPath', '')
samples = tqdm.t... |
(resources={'machine': 1})
def multicast(args_dict, notification_address, world_size, world_rank, object_size):
store = utils.create_store_using_dict(args_dict)
object_id = store_lib.ObjectID((b'\x00' * 20))
if (world_rank == 0):
array = np.random.randint((2 ** 30), size=(object_size // 4), dtype=np... |
def test_downloader():
makeStationList(client_list=['SCEDC'], min_lat=35.5, max_lat=35.6, min_lon=(- 117.8), max_lon=(- 117.4), start_time='2019-09-01 00:00:00.00', end_time='2019-09-03 00:00:00.00', channel_list=['HH[ZNE]', 'HH[Z21]', 'BH[ZNE]', 'EH[ZNE]', 'SH[ZNE]', 'HN[ZNE]', 'HN[Z21]', 'DP[ZNE]'], filter_networ... |
def filter_story(input_, dim_, sent_id):
if ((dim_ == '<|xNeed|>') or (dim_ == '<|xAttr|>') or (dim_ == '<|xIntent|>')):
return input_[:(sent_id + 1)]
return input_ |
class LSQUnivariateSpline(UnivariateSpline):
def __init__(self, x, y, t, w=None, bbox=([None] * 2), k=3, ext=0, check_finite=False):
if check_finite:
w_finite = (np.isfinite(w).all() if (w is not None) else True)
if ((not np.isfinite(x).all()) or (not np.isfinite(y).all()) or (not w_... |
def set_printoptions(precision=None, threshold=None, edgeitems=None, linewidth=None, profile=None, sci_mode=None):
if (profile is not None):
if (profile == 'default'):
PRINT_OPTS.precision = 4
PRINT_OPTS.threshold = 1000
PRINT_OPTS.edgeitems = 3
PRINT_OPTS.lin... |
class AZNet(hk.Module):
def __init__(self, num_actions, num_channels: int=64, num_blocks: int=5, resnet_v2: bool=True, name='az_net'):
super().__init__(name=name)
self.num_actions = num_actions
self.num_channels = num_channels
self.num_blocks = num_blocks
self.resnet_v2 = res... |
def register_types(module):
root_module = module.get_root()
module.add_enum('QueueDiscSizePolicy', ['SINGLE_INTERNAL_QUEUE', 'SINGLE_CHILD_QUEUE_DISC', 'MULTIPLE_QUEUES', 'NO_LIMITS'])
module.add_enum('QueueSizeUnit', ['PACKETS', 'BYTES'], import_from_module='ns.network')
module.add_class('Address', imp... |
def test_serialize_infinity():
def reduction_infinity_1(a: dace.float64[3]):
return a.max()
sdfg = reduction_infinity_1.to_sdfg()
json_string = json.dumps(sdfg.to_json())
assert (json_string.find('Infinity') == (- 1))
def reduction_infinity_2(a: dace.float64[3]):
return np.max(a)
... |
def S8():
A = Matrix(GF(2), [[1, 0, 0, 0, 0, 1, 1, 1], [0, 1, 0, 0, 1, 0, 1, 1], [0, 0, 1, 0, 1, 1, 0, 1], [0, 0, 0, 1, 1, 1, 1, 1]])
M = BinaryMatroid(A, 'abcdefgh')
M.rename(('S8: ' + repr(M)))
return M |
class PackageImporter(Importer):
modules: Dict[(str, types.ModuleType)]
def __init__(self, file_or_buffer: Union[(str, torch._C.PyTorchFileReader, Path, BinaryIO)], module_allowed: Callable[([str], bool)]=(lambda module_name: True)):
self.zip_reader: Any
if isinstance(file_or_buffer, torch._C.Py... |
class linkedTextTypeSub(supermod.linkedTextType):
def __init__(self, ref=None, mixedclass_=None, content_=None):
supermod.linkedTextType.__init__(self, mixedclass_, content_) |
class LabelEncoder(object):
def __init__(self, dictionary: Dictionary) -> None:
self.dictionary = dictionary
def __call__(self, label: str) -> List[str]:
return self.dictionary.encode_line(label, append_eos=False, add_if_not_exist=False) |
def main(args):
with open(args.input_file, 'r') as f:
lines = f.readlines()
ref_pts = np.array([[(- 0.), (- 0.)], [0., (- 0.)], [0.000225, 0.], [(- 0.), 0.], [0., 0.]])
for (i, line) in enumerate(lines):
line = line.strip()
items = line.split()
img_path = items[0]
src... |
def load_all_logs(log_dir: str) -> Dict:
logs_name_list = []
for dir_file in os.listdir(log_dir):
if dir_file.endswith(LOG_EXTENSION):
logs_name_list.append(dir_file)
log_dict_list = []
for file_name in logs_name_list:
with open(os.path.join(log_dir, file_name), 'rb') as log_... |
(scope='module')
def simple_dataframe_array_pandas():
columns_array = ['user_id', 'item_id', 'timestamp']
data_array = [(1, [2, 1, 0], 19842), (1, [4, 1], 19844), (1, [3, 1, 0], 19843), (1, [5, 1], 19845), (1, [6, 1, 0], 19846), (1, [7, 1], 19847), (2, [1, 0, 1], 19841), (2, [2, 0], 19842), (2, [3, 0, 1], 19843... |
def load_infogan_dsprites_decoder():
cfg = config['global_config']
cfg.update(config['test_config'][0])
work_dir = '/deep/group/disentangle/InfoGAN-CR/dsprites_results/'
data = np.random.randn(50000, 64, 64, 1)
(_, height, width, depth) = data.shape
latent_list = []
for i in range(cfg['unifo... |
class Mish(nn.Module):
def __init__(self, inplace: bool=False):
super(Mish, self).__init__()
def forward(self, x):
return mish(x) |
class Block8(nn.Module):
def __init__(self, scale=1.0, noReLU=False):
super().__init__()
self.scale = scale
self.noReLU = noReLU
self.branch0 = BasicConv2d(1792, 192, kernel_size=1, stride=1)
self.branch1 = nn.Sequential(BasicConv2d(1792, 192, kernel_size=1, stride=1), BasicC... |
def autosummary(name: str, value: TfExpressionEx, passthru: TfExpressionEx=None, condition: TfExpressionEx=True) -> TfExpressionEx:
tfutil.assert_tf_initialized()
name_id = name.replace('/', '_')
if tfutil.is_tf_expression(value):
with tf.name_scope(('summary_' + name_id)), tf.device(value.device):
... |
def register_Ns3UanPhyPer_methods(root_module, cls):
cls.add_constructor([])
cls.add_constructor([param('ns3::UanPhyPer const &', 'arg0')])
cls.add_method('CalcPer', 'double', [param('ns3::Ptr< ns3::Packet >', 'pkt'), param('double', 'sinrDb'), param('ns3::UanTxMode', 'mode')], is_pure_virtual=True, is_virt... |
def _convert_recs_to_tensor(recs: PandasDataFrame) -> torch.Tensor:
return _build_tensor_from_grouped_items(_groupby_recs_items(recs), (- 3)) |
def get_answer(paragraphs, question, reasoningType):
((q1_b, q2_b), (q1_i, q2_i)) = model.get_output('span-predictor', question, paragraphs)
if (reasoningType == 0):
print('Only run bridging')
answer1_b = model.get_output('qa', [q1_b], paragraphs)[0][0]
q2_b = q2_b.replace('[ANSWER]', an... |
def load_param_test_data(output_path: str):
return (load_data_tensors_TW(join(output_path, 'vectors', 'test', 'identifiers_param_test_datapoints_x.npy')), load_data_tensors_TW(join(output_path, 'vectors', 'test', 'tokens_param_test_datapoints_x.npy')), load_data_tensors_TW(join(output_path, 'vectors', 'test', 'para... |
def rollout(model, episode, env, tasks, demo_task_counter, live_task_counter, modalities, cfg, id_to_task_dict=None, embeddings=None):
(state_obs, rgb_obs, depth_obs, actions, _, reset_info, idx) = episode
seq_len_max = (state_obs.shape[0] - 1)
for mod in modalities:
groundtruth_task = id_to_task_di... |
def make_datasets(split):
is_train = (split == 'train')
paths_catalog = import_file('maskrcnn.config.paths_catalog', cfg.PATHS_CATALOG, True)
DatasetCatalog = paths_catalog.DatasetCatalog
dataset_list = eval(('cfg.DATASETS.' + split.upper()))
transforms = build_transforms(is_train)
datasets = bu... |
def plugin(query_value_replaced: List[str], values_in_order: List[str]) -> str:
q_length = len(query_value_replaced)
query_w_values = query_value_replaced[:]
value_idx = [idx for idx in range(q_length) if (query_value_replaced[idx] == VALUE_NUM_SYMBOL.lower())]
assert (len(value_idx) == len(values_in_or... |
class RatesOracle(nn.Module):
def __init__(self, config, num_neurons, device, **kwargs):
super().__init__()
assert (config.REQUIRES_RATES == True), 'Oracle requires rates'
if (config.LOSS.TYPE == 'poisson'):
self.classifier = nn.PoissonNLLLoss(reduction='none', log_input=config.L... |
def subsample_dataset(dataset, idxs):
dataset.data = np.array(dataset.data)[idxs].tolist()
dataset.target = np.array(dataset.target)[idxs].tolist()
dataset.uq_idxs = dataset.uq_idxs[idxs]
return dataset |
def compute_deconv_layer_sizes(h_in, w_in, kernel_sizes, strides, paddings=None):
if (paddings == None):
for (kernel, stride) in zip(kernel_sizes, strides):
(h_in, w_in) = compute_deconv_output_size(h_in, w_in, kernel, stride)
print('Output Size:', (h_in, w_in))
else:
for... |
class BasePyTorchExporter(Exporter):
def __init__(self, model: torch.nn.Module, is_layer_exportable_fn: Callable, save_model_path: str, repr_dataset: Callable):
super().__init__(model, is_layer_exportable_fn, save_model_path)
self.model = copy.deepcopy(self.model)
self.repr_dataset = repr_da... |
def ref_confusion_matrix(x, l, axis):
orig_x = x.copy()
x = np.rollaxis(x, axis, x.ndim).reshape((- 1), x.shape[axis])
ll = np.rollaxis(l, axis, x.ndim).flatten()
y = np.zeros((orig_x.shape[axis], orig_x.shape[axis]), int)
for (x_, ll_) in zip(x, ll):
index = (- 1)
for (i, x__) in en... |
class USTimeZone(tzinfo):
def __init__(self, hours, reprname, stdname, dstname):
self.stdoffset = timedelta(hours=hours)
self.reprname = reprname
self.stdname = stdname
self.dstname = dstname
def __repr__(self):
return self.reprname
def tzname(self, dt):
if se... |
class Pose():
def __init__(self, header: PoseHeader, body: PoseBody):
self.header = header
self.body = body
def read(buffer: bytes, pose_body: Type[PoseBody]=NumPyPoseBody, **kwargs):
reader = BufferReader(buffer)
header = PoseHeader.read(reader)
body = pose_body.read(hea... |
class TupleEncoder(Encoder):
def __init__(self, observation_shape: Shape):
super().__init__()
(shape1, shape2) = observation_shape
assert isinstance(shape1, (tuple, list))
assert isinstance(shape2, (tuple, list))
self.fc1 = nn.Linear(shape1[0], 256)
self.fc2 = nn.Line... |
class DiscreteFQEImpl(DiscreteQFunctionMixin, FQEBaseImpl):
_q_func_forwarder: ContinuousEnsembleQFunctionForwarder
_targ_q_func_forwarder: ContinuousEnsembleQFunctionForwarder
def compute_loss(self, batch: TorchMiniBatch, q_tpn: torch.Tensor) -> torch.Tensor:
return self._q_func_forwarder.compute_e... |
class BiAttention(nn.Module):
def __init__(self, x_dim, y_dim, z_dim, glimpse, dropout=[0.2, 0.5]):
super(BiAttention, self).__init__()
self.glimpse = glimpse
self.logits = weight_norm(BCNet(x_dim, y_dim, z_dim, glimpse, dropout=dropout, k=3), name='h_mat', dim=None)
def forward(self, v,... |
def start_memory_tracing(modules_to_trace: Optional[Union[(str, Iterable[str])]]=None, modules_not_to_trace: Optional[Union[(str, Iterable[str])]]=None, events_to_trace: str='line', gpus_to_trace: Optional[List[int]]=None) -> MemoryTrace:
if is_psutil_available():
process = psutil.Process(os.getpid())
e... |
class WeightedLeastSquares(ComboObjectiveFunction):
_model = None
def __init__(self, mesh, active_cells=None, alpha_s=1.0, alpha_x=None, alpha_y=None, alpha_z=None, alpha_xx=0.0, alpha_yy=0.0, alpha_zz=0.0, length_scale_x=None, length_scale_y=None, length_scale_z=None, mapping=None, reference_model=None, refere... |
def dataset_labels(dataset):
labels = set([x.sentiment for x in dataset])
if all((re.match('^[0-9]+$', label) for label in labels)):
labels = [str(x) for x in sorted(map(int, list(labels)))]
else:
labels = sorted(list(labels))
return labels |
def DeeplabMulti(num_classes=21):
model = ResNetMulti(Bottleneck, [3, 4, 23, 3], num_classes)
return model |
def get_timestamp_embeddings(audio, model):
(embedmel, tmel) = model.get_timestamp_mels(audio, window_size=(6 * 160))
(embed1, t1) = model.get_timestamp_embeddings(audio)
(embed2, t2) = model.get_timestamp_embeddings(audio, window_size=(model.timestamp_window * 5))
embed = torch.cat((embed1, embed2, emb... |
def main(args):
path_val_data = '../../data/crowdsourced/visdial_1.0_val_crowdsourced.json'
path_images_root = '../../data/images/'
dense_annotations_jsonpath = '../../data/crowdsourced/visdial_1.0_val_dense_annotations_crowdsourced.json'
model_preds_root = '../../models/visdialconv/'
analyzer = Pre... |
def get_model_from_name(args, idx=(- 1)):
if ((idx != (- 1)) and (idx == (args.num_models - 1))):
width_ratio = args.width_ratio
else:
width_ratio = (- 1)
if (args.model_name == 'net'):
return Net(args)
elif (args.model_name == 'simplenet'):
return SimpleNet(args)
eli... |
class TinyImageNetDataset(DataInterface):
def __init__(self, **kwargs):
self.kwargs = kwargs
def shard_descriptor(self):
return self._shard_descriptor
_descriptor.setter
def shard_descriptor(self, shard_descriptor):
self._shard_descriptor = shard_descriptor
self.train_set... |
def _seg_69():
return [(126500, 'M', u''), (126501, 'X'), (126503, 'M', u''), (126504, 'X'), (126505, 'M', u''), (126506, 'M', u''), (126507, 'M', u''), (126508, 'M', u''), (126509, 'M', u''), (126510, 'M', u''), (126511, 'M', u''), (126512, 'M', u''), (126513, 'M', u''), (126514, 'M', u''), (126515, 'X'), (126516,... |
def test_single_model_greedy_acquisition_builder_repr_includes_class_name() -> None:
builder = _ArbitraryGreedySingleBuilder()
assert (type(builder).__name__ in repr(builder)) |
def build_dataloader(dataset, dataset_opt, num_gpu=1, dist=False, sampler=None, seed=None):
phase = dataset_opt['phase']
(rank, _) = get_dist_info()
if (phase == 'train'):
if dist:
batch_size = dataset_opt['batch_size_per_gpu']
num_workers = dataset_opt['num_worker_per_gpu']
... |
def load_state(path, prefix):
gen.load_state_dict(torch.load(os.path.join(path, 'net_archive', '{0}_gen.pt'.format(prefix)), map_location=load_location_map))
gen_opt.load_state_dict(torch.load(os.path.join(path, 'net_archive', '{0}_gen_opt.pt'.format(prefix)), map_location=load_location_map))
dis.load_state... |
class ResizeAndGrayscaleWrapper(gym.core.Wrapper):
def __init__(self, env, w, h):
super(ResizeAndGrayscaleWrapper, self).__init__(env)
self.observation_space = spaces.Box(0, 255, shape=[w, h], dtype=np.uint8)
self.w = w
self.h = h
def _observation(self, obs):
obs = cv2.cv... |
def ref_bool_scatter(sdata, mask):
gdata_shape = (mask.shape + sdata.shape[1:])
mask_bool = mask.astype(bool)
gdata = np.zeros(gdata_shape)
gdata[mask_bool] = sdata
return gdata |
class FFN(nn.Module):
def __init__(self, features):
super(FFN, self).__init__()
self.layer1 = nn.Linear(features, features)
self.layer2 = nn.Linear(features, features)
self.relu = nn.ReLU()
self.drop = nn.Dropout(0.2)
def forward(self, x):
out = self.drop(self.rel... |
def D_gp_loss(dis_input, dis_out):
batch_size = dis_input.size(0)
grad_penalty = autograd.grad(outputs=dis_out.mean(), inputs=dis_input, create_graph=True, retain_graph=True, only_inputs=True)[0]
grad_penalty = grad_penalty.pow(2)
assert (grad_penalty.size() == dis_input.size())
real_grad = grad_pen... |
_function
def exterior_algebra_basis(n, degrees):
if (n == 0):
return [[0 for _ in degrees]]
if (len(degrees) == 1):
if (degrees[0] == n):
return [[1]]
return []
if (not degrees):
return []
if (min(degrees) > n):
return []
if (sum(degrees) < n):
... |
()
def tracer_mock():
tracer = MagicMock()
tracer.register_code_object.side_effect = range(100)
tracer.register_predicate.side_effect = range(100)
return tracer |
(Output('right-column-data', 'children'), Input('data-explanation-state', 'data'))
def update_view(data):
params = json.loads(data)
state = copy.deepcopy(board.state)
for (param, value) in params.items():
state.set_param('data', param, value)
return create_right_column(state) |
def clip_grad_norm_(parameters: _tensor_or_tensors, max_norm: float, norm_type: float=2.0) -> torch.Tensor:
if isinstance(parameters, torch.Tensor):
parameters = [parameters]
parameters = [p for p in parameters if (p.grad is not None)]
max_norm = float(max_norm)
norm_type = float(norm_type)
... |
def run_treebank(mode, paths, treebank, short_name, temp_output_file, command_args, extra_args):
constituency_dir = paths['CONSTITUENCY_DATA_DIR']
(short_language, dataset) = short_name.split('_')
train_file = os.path.join(constituency_dir, f'{short_name}_train.mrg')
dev_file = os.path.join(constituency... |
class Formatter():
def __init__(self):
global _ellipses
self.max_depth = 20
self.max_args = 128
self.rational_to_decimal = False
self.precision = 10
self.ellipses = to_format(_ellipses)
self.max_visited = 10000
self.fpa_pretty = True
def pp_ellipse... |
class TransformerDecoderLayer(Module):
__constants__ = ['batch_first', 'norm_first']
def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation=F.relu, layer_norm_eps=1e-05, batch_first=False, norm_first=False, device=None, dtype=None) -> None:
factory_kwargs = {'device': device, '... |
def legacy_get_enum(size_average, reduce, emit_warning=True):
return get_enum(legacy_get_string(size_average, reduce, emit_warning)) |
def init_trial_path(args, is_save=True):
prename = ((((((args.dataset + '_') + str(args.test_dataset)) + '_') + str(args.n_shot_test)) + '_') + args.enc_gnn)
result_path = os.path.join(args.result_path, prename)
os.makedirs(result_path, exist_ok=True)
trial_id = 0
path_exists = True
while path_e... |
def loss_dcgan_dis(netD, netG, x_real, z_rand, label):
with torch.no_grad():
x_fake = netG(z_rand, label).detach()
d_real = netD(x_real, label)
d_fake = netD(x_fake, label)
loss_real = F.binary_cross_entropy_with_logits(d_real, 1)
loss_fake = F.binary_cross_entropy_with_logits(d_fake, 0)
... |
def test(epoch, ternary, rel, norel, split='Test'):
model.eval()
if (not (len(rel[0]) == len(norel[0]))):
print('Not equal length for relation dataset and non-relation dataset.')
return
ternary = cvt_data_axis(ternary)
rel = cvt_data_axis(rel)
norel = cvt_data_axis(norel)
accurac... |
def check_docker():
if (not check_cmd(['docker', 'version'])):
if (not on_linux):
error("Docker not found.\nIf you are using Docker Toolbox, make sure you are running 'satex'\nwithin the 'Docker quickstart Terminal'.")
else:
error('Docker not found.')
docker_argv = docker... |
def slow(test_case):
if (not _run_slow_tests):
test_case = unittest.skip('test is slow')(test_case)
return test_case |
def download_image(row):
fname = _file_name(row)
if os.path.isfile(fname):
row['status'] = 200
row['file'] = fname
row['mimetype'] = magic.from_file(row['file'], mime=True)
row['size'] = os.stat(row['file']).st_size
return row
try:
response = requests.get(row[... |
class DisDocument(Document):
def __init__(self, dpath, epath):
Document.__init__(self, dpath)
self.datatype = 'dis'
self.eduPath = epath
def read(self):
basename = os.path.basename(self.path)
for e in ['.out', '.dis', '.txt', '.edus']:
basename = basename.repl... |
def test_alpha_in_predict() -> None:
mapie_reg = MapieQuantileRegressor()
mapie_reg.fit(X, y)
with pytest.warns(UserWarning, match='WARNING: ensemble is not util*'):
mapie_reg.predict(X, ensemble=True) |
class mnist_model(nn.Module):
def __init__(self):
super(mnist_model, self).__init__()
self.layer1 = nn.Conv2d(1, 16, kernel_size=5, stride=1, padding=0)
self.layer2 = nn.Conv2d(16, 16, kernel_size=5, stride=1, padding=0)
self.layer3 = nn.Linear(256, 100, bias=True)
self.layer... |
_model_architecture(model_name='s2t_transformer', arch_name='s2t_transformer')
def base_architecture(args):
args.encoder_freezing_updates = getattr(args, 'encoder_freezing_updates', 0)
args.conv_kernel_sizes = getattr(args, 'conv_kernel_sizes', '5,5')
args.conv_channels = getattr(args, 'conv_channels', 1024... |
class L2Loss(nn.Module):
def __init__(self, reduction='mean', loss_weight=1.0):
super(L2Loss, self).__init__()
self.reduction = reduction
self.loss_weight = loss_weight
def forward(self, pred, target):
loss = (self.loss_weight * l2_loss(pred, target, reduction=self.reduction))
... |
def test_dpt_head():
with pytest.raises(AssertionError):
head = DPTHead(in_channels=[768, 768, 768, 768], channels=4, num_classes=19, in_index=[0, 1, 2, 3])
head = DPTHead(in_channels=[768, 768, 768, 768], channels=4, num_classes=19, in_index=[0, 1, 2, 3], input_transform='multiple_select')
inputs =... |
def create_mpi_script(driver_path, args, hostname, gpus, resource_info, machine_id, partitions, search, port=22):
cmd = ('ssh -p %d %s "mkdir -p %s"' % (port, hostname, REMOTE_PARALLAX_ROOT))
parallax_log.warning(colored(('\n$ %s' % cmd), 'red'))
proc = subprocess.Popen(args=cmd, shell=True)
proc.wait()... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.