code stringlengths 101 5.91M |
|---|
def check_release_file(run_lambda):
return run_and_parse_first_match(run_lambda, 'cat /etc/*-release', 'PRETTY_NAME="(.*)"') |
def find_path(start, goal, neighbors_fnct, reversePath=False, heuristic_cost_estimate_fnct=(lambda a, b: Infinite), distance_between_fnct=(lambda a, b: 1.0), is_goal_reached_fnct=(lambda a, b: (a == b))):
class FindPath(AStar):
def heuristic_cost_estimate(self, current, goal):
return heuristic_c... |
class Policy(nn.Module):
def __init__(self, action_space, encoding_dimension):
super().__init__()
self.critic_linear = nn.Linear(encoding_dimension, 1)
self.h_dim = encoding_dimension
if (action_space.__class__.__name__ == 'Discrete'):
num_outputs = action_space.n
... |
class _MemoryEfficientFP16OptimizerMixin(object):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._multiply_factor = 1.0
def has_flat_params(self):
return False
def state_dict(self):
state_dict = self.wrapped_optimizer.state_dict()
if (self... |
def scale_ocr_y(y, dimensions_scenegraph, dimensions_ocr):
return ((y * dimensions_scenegraph[1]) / dimensions_ocr[1]) |
def test_nested_malformed():
shape = (11, 13, 7)
module = make_module(*shape)
with pytest.raises(RuntimeError, match='Complex parameter requires both'):
module.load_state_dict({'mod.par.real': torch.randn(*shape)})
with pytest.raises(RuntimeError, match='Complex parameter requires both'):
... |
class SetVocab(dict):
def __init__(self, vocab):
self.update(vocab)
def ws2ids(self, ws):
return [(self[w] if (w in self) else 0) for w in ws]
def ids2sent(self, ids):
idx2w = dict([(i, w) for (w, i) in self.items()])
return [(idx2w[int(i)] if (i in idx2w) else 'UNK') for i i... |
class PyramidPoolingBranch(nn.Module):
def __init__(self, in_channels, out_channels, pool_out_size, upscale_out_size):
super(PyramidPoolingBranch, self).__init__()
self.upscale_out_size = upscale_out_size
self.pool = nn.AdaptiveAvgPool2d(pool_out_size)
self.conv = conv1x1_block(in_ch... |
class PreActBlock(nn.Module):
expansion = 1
def __init__(self, in_planes, planes, stride=1):
super(PreActBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.conv1 = conv3x3(in_planes, planes, stride)
self.bn2 = nn.BatchNorm2d(planes)
self.conv2 = conv3x3(pla... |
def build_annoFile(root, save_annotation_root, is_full=True):
assert osp.exists(root), 'Path: {} not exists!'.format(root)
mkdir_or_exist(save_annotation_root)
trainMetas = getKITTI2015Metas(root, 'training', mode='training', is_full=is_full)
evalMetas = getKITTI2015Metas(root, 'training', mode='evaluat... |
(scope='module')
def rleaky_hidden_reset_none_instance():
return snn.RLeaky(beta=0.5, V=0.5, all_to_all=False, init_hidden=True, reset_mechanism='none') |
class AudioPersistenz():
def __init__(self, loadPath: str, savePath: str=None, fileExtension: str='wav'):
self.savePath = (loadPath if (savePath is None) else savePath)
self.loadPath = loadPath
self.fileExtension = fileExtension
self.fileListUtil = FileListUtil()
self.pathUti... |
class TEAN(nn.Module):
def __init__(self, nclass, model1, model2):
super(TEAN, self).__init__()
self.model1 = model1
self.model2 = model2
self.model1.classifier[1] = nn.Linear((128 + 128), num_classes)
self.head = nn.Sequential(encoding.nn.Encoding(D=1280, K=n_codes), encodin... |
class CIFAR100SSL(datasets.CIFAR100):
def __init__(self, root, indexs, train=True, transform=None, target_transform=None, download=False):
super().__init__(root, train=train, transform=transform, target_transform=target_transform, download=download)
if (indexs is not None):
self.data = s... |
class UpsampleBlock(nn.Module):
def __init__(self, n_channels, scale, multi_scale, group=1):
super(UpsampleBlock, self).__init__()
if multi_scale:
self.up2 = _UpsampleBlock(n_channels, scale=2, group=group)
self.up3 = _UpsampleBlock(n_channels, scale=3, group=group)
... |
def communicate_1(tensors, communication_op, group, attention=False):
flat_tensor = flatten_tensors(tensors)
communication_op(tensor=flat_tensor, group=group)
if attention:
return (tensors / flat_tensor)
for (f, t) in zip(unflatten_tensors(flat_tensor, tensors), tensors):
with torch.no_g... |
def to_onehot(indexes, dim, dtype=None):
dtype = (indexes.dtype if (dtype is None) else dtype)
onehot = np.zeros((indexes.size, dim), dtype=dtype)
onehot[(np.arange(indexes.size), indexes.reshape((- 1)))] = 1
return onehot.reshape((indexes.shape + (dim,))) |
def get_diaresnet_cifar(num_classes, blocks, bottleneck, model_name=None, pretrained=False, root=os.path.join('~', '.torch', 'models'), **kwargs):
assert (num_classes in [10, 100])
if bottleneck:
assert (((blocks - 2) % 9) == 0)
layers = ([((blocks - 2) // 9)] * 3)
else:
assert (((bl... |
def projection(input_ops, y_task, n_hidden, sequence_lengths, class_weights, optmzr, batch_size=1):
timesteps = len(input_ops)
n_classes = len(class_weights)
w = tf.get_variable('weights', [(2 * n_hidden), n_classes], initializer=xavier_init((2 * n_hidden), n_classes))
b = tf.get_variable('biases', [n_c... |
def load_text(file_path: str, ids: List[str], groupByClip: bool=True):
dict_text = {}
with open(file_path) as f:
for line in f:
(id, text) = line.split(' ', 1)
if (id[:11] in ids):
dict_text[id] = text
if groupByClip:
dict_text = _groupByClip(dict_text... |
class TestMyModule(unittest.TestCase):
def setUpClass(self):
if (not os.path.exists(TASK_LOG_path)):
os.makedirs(TASK_LOG_path)
def tearDownClass(self):
shutil.rmtree(NEURAL_SOLUTION_WORKSPACE, ignore_errors=True)
def test_serialize(self):
request = {'key': 'value'}
... |
class UniversalCharEmbedding(nn.Module):
def __init__(self, langs, char_emb_dim, universal_charset_size, mapping_temperature=0.0):
super(UniversalCharEmbedding, self).__init__()
self.langs = langs
self.charsets = {l: get_charset(l) for l in langs}
self.char_emb_dim = char_emb_dim
... |
def osnet_x0_5(num_classes=1000, pretrained=True, loss='softmax', **kwargs):
model = OSNet(num_classes, blocks=[OSBlock, OSBlock, OSBlock], layers=[2, 2, 2], channels=[32, 128, 192, 256], loss=loss, **kwargs)
if pretrained:
init_pretrained_weights(model, key='osnet_x0_5')
return model |
class AttenResNet2(nn.Module):
def __init__(self, atten_activation, atten_channel=16, size1=(257, 1091), size2=(249, 1075), size3=(233, 1043), size4=(201, 979), size5=(137, 851)):
super(AttenResNet2, self).__init__()
self.pre = nn.Sequential(nn.Conv2d(1, atten_channel, kernel_size=(3, 3), padding=(1... |
def prototype_twitter_GaussPiecewise_VHRED_NormOp_ClusterExp3():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dic... |
def test_centerpoint_fpn():
second_cfg = dict(type='SECOND', in_channels=64, out_channels=[64, 128, 256], layer_nums=[3, 5, 5], layer_strides=[2, 2, 2], norm_cfg=dict(type='BN', eps=0.001, momentum=0.01), conv_cfg=dict(type='Conv2d', bias=False))
second = build_backbone(second_cfg)
centerpoint_fpn_cfg = dic... |
class CnnPolicy(object):
recurrent = False
def __init__(self, name, ob_space, ac_space):
with tf.variable_scope(name):
self._init(ob_space, ac_space)
self.scope = tf.get_variable_scope().name
def _init(self, ob_space, ac_space):
assert isinstance(ob_space, gym.spaces.... |
class Camera():
def __init__(self, robot_idx):
serial = CAMERA_SERIALS[robot_idx]
(image_width, image_height, camera_matrix, dist_coeffs) = get_camera_params(serial)
self.cap = get_video_cap(serial, image_width, image_height)
(self.map_x, self.map_y) = cv.initUndistortRectifyMap(came... |
def plot_figure2(df):
(fig, axs) = plt.subplots(nrows=1, ncols=2, figsize=(12, 3))
df['desired coverage (1-)'] = (1 - df['alpha'])
sns.barplot('desired coverage (1-)', 'desired coverage (1-)', data=df, alpha=0.3, ax=axs[0], edgecolor='k', ci=None, fill=False)
bplot = sns.barplot(x='desired coverage (1-)... |
def compute_mean_std(list_values):
np_values = np.array(list_values)
mean = np.mean(np_values)
std = np.std(np_values)
return (mean, std) |
def add_dict(left, right):
for (key, value) in right.items():
left[key] = (left.get(key, 0) + value.item()) |
def test_dense_reward(bin_pack_dense_reward: BinPack, dense_reward: DenseReward) -> None:
reward_fn = jax.jit(dense_reward)
step_fn = jax.jit(bin_pack_dense_reward.step)
(state, timestep) = bin_pack_dense_reward.reset(jax.random.PRNGKey(0))
for (item_id, is_valid) in enumerate(timestep.observation.items... |
def main():
(args, a_config, r_config) = parse_args()
if args.a_ckpt:
a_config.DATASET.TASK = 'Q2A'
a_config.GPUS = ','.join([str(k) for k in args.gpus])
a_result_csv = test_net(args, a_config, ckpt_path=args.a_ckpt, save_path=args.result_path, save_name=args.result_name)
if args.r_c... |
.script
def mish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
x_tanh_sp = F.softplus(x).tanh()
return grad_output.mul((x_tanh_sp + ((x * x_sigmoid) * (1 - (x_tanh_sp * x_tanh_sp))))) |
def _poison_fountain_homing(state, agent_name):
agent_sprite = state[agent_name][0]
fruits = state['fountains']
poison_fountains = list(filter((lambda s: (s.c2 < 0.6)), fruits))
return _target_homing(poison_fountains, agent_sprite) |
class RLSidetuneNetwork(nn.Module):
def __init__(self, n_frames, n_map_channels=0, use_target=True, output_size=512, num_tasks=1, extra_kwargs={}):
super(RLSidetuneNetwork, self).__init__()
assert ('sidetune_kwargs' in extra_kwargs), 'Cannot use sidetune network without kwargs'
self.sidetune... |
def crop_video(sub_set, video, crop_path, instanc_size):
video_crop_base_path = join(crop_path, sub_set, video)
if (not exists(video_crop_base_path)):
makedirs(video_crop_base_path)
sub_set_base_path = join(visdrone_base_path, sub_set)
video_base_path = join(sub_set_base_path, 'sequences', video... |
class FooModule(nn.Module):
def __init__(self):
super().__init__()
self.linear = nn.Linear(1, 2)
self.conv2d = nn.Conv2d(3, 1, 3)
self.conv2d_2 = nn.Conv2d(3, 2, 3) |
('submit')
def value_changed(message):
print('Socket recieved', message)
prefix = message['prompt']
topic = message['topic']
affect = message['affect']
knob = message['knob']
(out, ok) = generate(prefix, topic, affect, float(knob)) |
def cau_recall_mrr(preds, labels, cutoff):
recall = []
mrr = []
for (batch, b_label) in zip(preds, labels):
for (step, s_label) in zip(batch, b_label):
ranks = ((step[s_label] < step).sum() + 1)
recall.append((ranks <= cutoff))
mrr.append(((1 / ranks) if (ranks <=... |
class Item():
mode: str
scene: str
seq: str
stem: str
def get_split_file(cls, mode: str) -> Path:
return ((PATHS['mapfree'] / 'splits') / f'{mode}_files.txt')
def load_split(cls, mode: str) -> ty.S['Item']:
return [cls(mode, *s) for s in io.readlines(cls.get_split_file(mode), spl... |
def weights_from_hdf5(f):
if ('weight_names' in f.attrs):
for n in f.attrs['weight_names']:
(yield (n, f[n]))
else:
for k in f.keys():
for (n, w) in weights_from_hdf5(f[k]):
(yield (n, w)) |
def look_at(obj: Union[(bpy.types.Object, str)], location: Union[(Tuple[float], mathutils.Vector)], roll: float=0) -> None:
obj = zpy.objects.verify(obj)
if (not isinstance(location, mathutils.Vector)):
location = mathutils.Vector(location)
loc = obj.location
direction = (location - obj.location... |
class UNetResNet(nn.Module):
def __init__(self, in_channels=3, w=4, n_classes=2):
super(UNetResNet, self).__init__()
self.inc = inconv(in_channels, int((16 * w)))
self.down1 = down(int((16 * w)), int((32 * w)))
self.down2 = down(int((32 * w)), int((64 * w)))
self.down3 = down... |
def form_esnil_train_output(label: Text, spans_text: List[Text], explanation: Text):
output = label
for sp_text in spans_text:
output = '{} {} {}'.format(output, OUTPUT_SEP, sp_text)
output = '{} {} {}'.format(output, OUTPUT_SEP, explanation)
return output |
class DepthToSpace(nn.Module):
def __init__(self, block_size):
super().__init__()
self.bs = block_size
def forward(self, x):
(N, C, H, W) = x.size()
x = x.view(N, self.bs, self.bs, (C // (self.bs ** 2)), H, W)
x = x.permute(0, 3, 4, 1, 5, 2).contiguous()
x = x.vie... |
def _propose_leaf_modules(atorch_wrap_cls=None):
leaf_modules = None
if (atorch_wrap_cls is not None):
leaf_modules = list((set(_SHARDABLE_OPERATORS.values()) & set(atorch_wrap_cls)))
if ((leaf_modules is None) or (len(leaf_modules) == 0)):
leaf_modules = list(_SHARDABLE_OPERATORS.values())
... |
def min_dfscodes_to_tensors(min_dfscodes_path, min_dfscode_tensors_path, feature_map):
min_dfscodes = []
for filename in os.listdir(min_dfscodes_path):
if filename.endswith('.dat'):
min_dfscodes.append(filename)
with Pool(processes=MAX_WORKERS) as pool:
for (i, _) in tqdm(enumera... |
def _expected(observed):
o = observed
if (len(o) == 0):
return []
if (len(o) == 1):
return [([(sum(o[0]) / float(len(o[0])))] * len(o[0]))]
n = [sum(o[i]) for i in range(len(o))]
m = [sum((o[i][j] for i in range(len(o)))) for j in range(len(o[0]))]
s = float(sum(n))
return [[... |
def generate_zeros_from_spec(spec: jnp.ndarray) -> jnp.ndarray:
zeros: jnp.ndarray = jnp.zeros(spec.shape, spec.dtype)
return zeros |
def _sparse_inner_flatten(inputs, new_rank):
inputs_rank = inputs.dense_shape.get_shape().as_list()[0]
if (inputs_rank < new_rank):
raise ValueError('Inputs has rank less than new_rank. {} must have rank at least {}. Received rank {}, shape {}'.format(inputs, new_rank, inputs_rank, inputs.get_shape()))
... |
class RandomPendulumAll(ModifiablePendulumEnv):
def __init__(self, mass_set=[0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.05, 1.1, 1.15, 1.2, 1.25], length_set=[0.75, 0.8, 0.85, 0.9, 0.95, 1.0, 1.05, 1.1, 1.15, 1.2, 1.25]):
super(RandomPendulumAll, self).__init__()
self.mass_set = mass_set
self.length... |
class GeneralizedRCNN(nn.Module):
def __init__(self, cfg):
super(GeneralizedRCNN, self).__init__()
self.backbone = build_backbone(cfg)
self.neck = build_neck(cfg)
self.rpn = build_rpn(cfg, self.backbone.out_channels)
self.roi_heads = build_roi_heads(cfg, self.backbone.out_cha... |
def with_origin_column(dataset, imageColumn='image', originColumn='origin', bigdl_type='float'):
return callZooFunc(bigdl_type, 'withOriginColumn', dataset, imageColumn, originColumn) |
class Rouge():
def __init__(self):
self.beta = 1.2
def calc_score(self, candidate, refs):
assert (len(candidate) == 1)
assert (len(refs) > 0)
prec = []
rec = []
token_c = candidate[0].split(' ')
for reference in refs:
token_r = reference.split(... |
def test_svt():
(H, W) = (224, 224)
temp = torch.randn((1, 3, H, W))
model = SVT(embed_dims=[32, 64, 128], num_heads=[1, 2, 4], mlp_ratios=[4, 4, 4], qkv_bias=False, depths=[4, 4, 4], windiow_sizes=[7, 7, 7], norm_after_stage=True)
model.init_weights()
outs = model(temp)
assert (outs[0].shape ==... |
def main():
args = parse_args()
cfg = Config.fromfile(args.config)
init_default_scope(cfg.get('default_scope', 'mmdet'))
if (args.cfg_options is not None):
cfg.merge_from_dict(args.cfg_options)
dataset = DATASETS.build(cfg.test_dataloader.dataset)
predictions = mmengine.load(args.pkl_res... |
def test_SB1():
orb = orbit.SB1(K, e, omega, P, T0, gamma, dates)
vels = orb.get_velocities()
(fig, ax) = plt.subplots(nrows=1)
ax.axhline(gamma, color='0.5', ls=':')
ax.plot(dates, vels[0])
ax.set_xlabel('JD')
ax.set_ylabel('$v_A\\,\\mathrm{km/s}$')
fig.savefig((outdir + 'SB1.png'), dpi... |
def compute_rouge_l(output, reference, mode='f'):
assert (mode in list('fpr'))
lcs = _lcs_len(output, reference)
if (lcs == 0):
score = 0.0
else:
precision = (lcs / len(output))
recall = (lcs / len(reference))
beta = (precision / (recall + math.exp((- 12))))
f_sco... |
def parse_string(xml):
string = ''
dom = XML(xml)
for sentence in dom(XML_SENTENCE):
_anchors.clear()
_attachments.clear()
language = sentence.get(XML_LANGUAGE, 'en')
format = sentence.get(XML_TOKEN, [WORD, POS, CHUNK, PNP, REL, ANCHOR, LEMMA])
format = (((not isinsta... |
def compose(r1: Rule, r2: Rule, rc: RCEvaluator) -> Tuple[(CompRes, CompRes)]:
comp = rcCommon(connected=False, maximum=False)
config.rc.printMatches = True
config.rc.matchesWithIndex = True
config.rc.printMatchesOnlyHaxChem = True
res12 = checkRules(rc.eval(rcExp([((r1 * rcParallel) * r2), ((r1 * c... |
('xstance_predictor')
class XStancePredictor(Predictor):
def predict(self, sentence: str) -> JsonDict:
return self.predict_json({'sentence': sentence})
def _json_to_instance(self, json_dict: JsonDict) -> Instance:
question = json_dict['question']
comment = json_dict['comment']
re... |
_module()
class SparseRCNN(TwoStageDetector):
'Implementation of `Sparse R-CNN: End-to-End Object Detection with\n Learnable Proposals <
def __init__(self, *args, **kwargs):
super(SparseRCNN, self).__init__(*args, **kwargs)
assert self.with_rpn, 'Sparse R-CNN do not support external proposals... |
class TimeReductionLayer(nn.Module):
def __init__(self, in_channels: int=1, out_channels: int=1, kernel_size: int=3, stride: int=2) -> None:
super(TimeReductionLayer, self).__init__()
self.sequential = nn.Sequential(DepthwiseConv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=kern... |
def numpy_random(shape: List[int], str_dtype: str) -> np.ndarray:
if (np.prod(shape) > ((2 * (1024 ** 3)) / 16)):
raise ValueError(f'Too large tensor shape: shape = {shape!r}')
rand_float = (lambda size: np.random.uniform((- 1000000), 1000000, size))
ret: np.ndarray = None
if ('float' in str_dty... |
def resdropresnet20_cifar100(classes=100, **kwargs):
return get_resdropresnet_cifar(classes=classes, blocks=20, bottleneck=False, model_name='resdropresnet20_cifar100', **kwargs) |
def store_args(method):
argspec = inspect.getfullargspec(method)
defaults = {}
if (argspec.defaults is not None):
defaults = dict(zip(argspec.args[(- len(argspec.defaults)):], argspec.defaults))
if (argspec.kwonlydefaults is not None):
defaults.update(argspec.kwonlydefaults)
arg_name... |
class PReLU(Layer):
def __init__(self, n_output_plane=0, bigdl_type='float'):
super(PReLU, self).__init__(None, bigdl_type, n_output_plane)
def set_init_method(self, weight_init_method=None, bias_init_method=None):
callBigDlFunc(self.bigdl_type, 'setInitMethod', self.value, weight_init_method, b... |
def test_get_importance_per_top_groups():
data = synthetic_regression()
X = data['full']['X']
y = data['full']['y']
ebm = ExplainableBoostingRegressor()
ebm.fit(X, y)
df = get_importance_per_top_groups(ebm, X)
dict = get_individual_importances(ebm, X)
assert (df.shape[0] == len(ebm.term_... |
def get_uniform_policy(env, *args, **kwargs):
from .uniform_policy import UniformPolicy
policy = UniformPolicy(input_shapes=(env.active_observation_shape,), output_shape=env.action_space.shape)
return policy |
def load_vec_normalize(params: dict, PATHS: dict, env: VecEnv, eval_env: VecEnv):
if params['normalize']:
load_path = os.path.join(PATHS['model'], 'vec_normalize.pkl')
if os.path.isfile(load_path):
env = VecNormalize.load(load_path=load_path, venv=env)
eval_env = VecNormalize... |
class nnUNetTrainerV2_3ConvPerStage(nnUNetTrainerV2):
def initialize_network(self):
self.base_num_features = 24
if self.threeD:
conv_op = nn.Conv3d
dropout_op = nn.Dropout3d
norm_op = nn.InstanceNorm3d
else:
conv_op = nn.Conv2d
drop... |
def all():
image = cv2.imread('tests/assets/lena_224.jpg')
m = ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2, p=1.0)
print(m)
res = m(image)
cv2.imwrite('tests/assets/lena_color_jitter.jpg', res) |
def test_find_duplicates_dict_recursive_warning(cnn, mocker):
encoding_map = data_encoding_map()
threshold = 0.9
scores = True
outfile = True
find_dup_dict_mocker = mocker.patch('imagededup.methods.cnn.CNN._find_duplicates_dict')
with pytest.warns(SyntaxWarning):
cnn.find_duplicates(enco... |
_HEADS_REGISTRY.register()
class CustomROIHeads(StandardROIHeads):
def _init_box_head(self, cfg, input_shape):
ret = super()._init_box_head(cfg, input_shape)
del ret['box_predictor']
ret['box_predictor'] = CustomFastRCNNOutputLayers(cfg, ret['box_head'].output_shape)
return ret |
class InceptionV3(nn.Module):
def __init__(self, channels, init_block_channels, b_mid_channels, dropout_rate=0.5, in_channels=3, in_size=(299, 299), num_classes=1000):
super(InceptionV3, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
normal_units = [InceptionA... |
class LGBOptimizerHyperopt(object):
def __init__(self, objective: str='binary', is_unbalance: bool=False, verbose: bool=False, num_class: Optional[int]=None):
self.objective = objective
if ((objective == 'multiclass') and (not num_class)):
raise ValueError('num_class must be provided for... |
def parse_args():
parser = argparse.ArgumentParser(description='Convert COCO Stuff 10k annotations to mmsegmentation format')
parser.add_argument('coco_path', help='coco stuff path')
parser.add_argument('-o', '--out_dir', help='output path')
parser.add_argument('--nproc', default=16, type=int, help='num... |
def callBigDlFunc(bigdl_type, name, *args):
gateway = _get_gateway()
args = [_py2java(gateway, a) for a in args]
error = Exception(('Cannot find function: %s' % name))
for jinvoker in JavaCreator.instance(bigdl_type, gateway).value:
try:
api = getattr(jinvoker, name)
resu... |
def main(_):
problem_type = 'grasp_classification'
feature_combo = 'image_preprocessed_norm_sin2_cos2_width_3'
FLAGS.crop_height = 224
FLAGS.crop_width = 224
FLAGS.problem_type = problem_type
FLAGS.feature_combo = feature_combo
FLAGS.crop_to = 'center_on_gripper_grasp_box_and_rotate_upright'... |
class CFG():
def __init__(self):
self.__dict__['cfg'] = None
def __getattr__(self, name):
return getattr(self.__dict__['cfg'], name)
def __setattr__(self, name, val):
setattr(self.__dict__['cfg'], name, val) |
('conv_only')
def conv_only(convs=[(32, 8, 4), (64, 4, 2), (64, 3, 1)], **conv_kwargs):
def network_fn(X):
out = (tf.cast(X, tf.float32) / 255.0)
with tf.variable_scope('convnet'):
for (num_outputs, kernel_size, stride) in convs:
out = layers.convolution2d(out, num_output... |
def load_trained_network(workspace_dir, network_path, checkpoint=None):
checkpoint_dir = os.path.join(workspace_dir, 'checkpoints')
directory = '{}/{}'.format(checkpoint_dir, network_path)
(net, _) = load_network(directory, checkpoint)
return net |
class PartA2Net(Detector3DTemplate):
def __init__(self, model_cfg, num_class, dataset):
super().__init__(model_cfg=model_cfg, num_class=num_class, dataset=dataset)
self.module_list = self.build_networks()
def forward(self, batch_dict):
if self.training:
for cur_module in self... |
class double_conv(nn.Module):
def __init__(self, in_ch, out_ch, normaliz=True, activ=True):
super(double_conv, self).__init__()
ops = []
ops += [nn.Conv2d(in_ch, out_ch, 3, padding=1)]
if normaliz:
ops += [nn.BatchNorm2d(out_ch)]
if activ:
ops += [nn.R... |
def do_train(model, data_loader, optimizer, scheduler, checkpointer, device, checkpoint_period, arguments):
seed_torch()
logger = logging.getLogger('maskrcnn_benchmark.trainer')
logger.info('Start training')
meters = MetricLogger(delimiter=' ')
max_iter = len(data_loader)
start_iter = arguments... |
class MIT67Data(data.Dataset):
def __init__(self, root, is_train=False, transform=None, shots=(- 1), seed=0, preload=False, portion=0, fixed_pic=False, four_corner=False, return_raw=False, is_poison=False):
self.four_corner = four_corner
self.num_classes = 67
self.transform = transform
... |
def _build_variable_getter(rename=None):
def layer_variable_getter(getter, *args, **kwargs):
kwargs['rename'] = rename
return _model_variable_getter(getter, *args, **kwargs)
return layer_variable_getter |
class NormalDataset(Dataset):
def __init__(self, files, config: Namespace):
self.center = config.center
self.files = files
self.transforms = T.Compose([T.Resize((config.image_size, config.image_size), T.InterpolationMode.LANCZOS), T.CenterCrop(config.image_size), T.ToTensor()])
def __len... |
def average_segcover(segA, segB, ignore_background=False):
assert (segA.shape == segB.shape), f'{segA.shape} - {segB.shape}'
assert ((segA.shape[1] == 1) and (segB.shape[1] == 1))
bsz = segA.shape[0]
nonignore = (segA >= 0)
mean_scores = torch.tensor((bsz * [0.0])).to(segA.device)
N = torch.tens... |
def filter_regular(sols, tol, oper):
result = []
for sol in sols:
rco = diagnostics(sol)[1]
if (oper == 'select'):
if (rco > tol):
result.append(sol)
if (oper == 'remove'):
if (rco <= tol):
result.append(sol)
return result |
class ForcedBOSTokenLogitsProcessor(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def _expand_param_groups(params: List[Dict[(str, Any)]]) -> List[Dict[(str, Any)]]:
ret = defaultdict(dict)
for item in params:
assert ('params' in item)
cur_params = {x: y for (x, y) in item.items() if (x != 'params')}
for param in item['params']:
ret[param].update({'params'... |
def make_dir(dir_name):
if (os.path.isdir(dir_name) == False):
print(('Make directory: ' + dir_name))
os.mkdir(dir_name) |
def test_constantbeta_dehnencore_in_nfw_sigmar():
if WIN32:
return None
pot = [potential.NFWPotential(amp=2.3, a=1.3)]
denspot = potential.DehnenCoreSphericalPotential(amp=2.5, a=1.15)
betas = [0.25]
for (beta, dfh) in zip(betas, constantbeta_dfs_dehnencore_in_nfw):
numpy.random.seed... |
def add_bn(model):
for (k, m) in list(model.named_children()):
if (isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear) or isinstance(m, nn.ConvTranspose2d)):
b = nn.BatchNorm2d(m.out_channels, momentum=0.1, affine=True)
b.weight.data.fill_(1)
new_m = nn.Sequential(model.... |
def test_nemo_MN3ExponentialDiskPotential():
mn = potential.MN3ExponentialDiskPotential(normalize=1.0, hr=0.5, hz=0.1)
tmax = 3.0
(vo, ro) = (215.0, 8.75)
o = Orbit([1.0, 0.1, 1.1, 0.3, 0.1, 0.4], ro=ro, vo=vo)
run_orbitIntegration_comparison(o, mn, tmax, vo, ro)
return None |
def _recon_lcs(x, y):
(i, j) = (len(x), len(y))
table = _lcs(x, y)
def _recon(i, j):
if ((i == 0) or (j == 0)):
return []
elif (x[(i - 1)] == y[(j - 1)]):
return (_recon((i - 1), (j - 1)) + [(x[(i - 1)], i)])
elif (table[((i - 1), j)] > table[(i, (j - 1))]):
... |
class coco_val():
def __init__(self, args, transform=None, k_shot=1):
self.num_classes = 80
self.group = args.group
self.num_folds = args.num_folds
self.dataDir = '/home/ubuntu/Dataset/MSCOCO2017'
self.dataType = 'val2017'
self.annFile = '{}/annotations/instances_{}.j... |
def accuracy(logits, labels):
(_, indices) = torch.max(logits, dim=1)
correct = torch.sum((indices == labels))
return ((correct.item() * 1.0) / len(labels)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.