code stringlengths 101 5.91M |
|---|
def LCS_mask(src, tgt, stop_words):
m = len(src)
n = len(tgt)
if (stop_words is None):
stop_words = set()
mat = [([0] * (n + 1)) for row in range((m + 1))]
for row in range(1, (m + 1)):
for col in range(1, (n + 1)):
if ((src[(row - 1)] == tgt[(col - 1)]) and (src[(row - 1... |
class Expr(Node):
def __init__(self, start, end, expr):
Node.__init__(self, start, end)
self.expr = expr
def Requires(self, node):
return False
def __str__(self):
return self._StringHelper(self.__class__.__name__, str(self.expr)) |
class DenseInverseAutoRegressive(nn.Module):
def __init__(self, n):
super(DenseInverseAutoRegressive, self).__init__()
self.mean = Dense(n, n)
self.std = Dense(n, n)
def forward(self, input):
return ((input - self.mean(input)) / self.std(input)) |
def chunked_dataset_iterator(chunk_refs: List, read_chunk_fn: Callable[([Any], Iterator)], buffer_size: int, train: bool=True, seed: Optional[int]=None, shuffle: bool=True, use_windowed: bool=False, transform: Callable[([Any], Any)]=None, prefetch: bool=True, num_instances: int=1, instance_rank: int=0):
if ((not tr... |
def main():
rospy.init_node('model_free_version', log_level=rospy.WARN)
env = Env(is_training)
policy = TD3(S_DIM, A_DIM)
print()
policy.load((pkg_path + '/Models/TEST/test'))
replay_buffer = utils.ReplayBuffer(S_DIM, A_DIM)
total_step = 0
save_time = 0
episode_num = 1
success_nu... |
class TFAutoModelForMaskedImageModeling(_BaseAutoModelClass):
_model_mapping = TF_MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING |
def image_dataset_kwargs(parsed_args):
return {'source_names': parsed_args.source_names, 'target_names': parsed_args.target_names, 'root': parsed_args.root, 'split_id': parsed_args.split_id, 'height': parsed_args.height, 'width': parsed_args.width, 'train_batch_size': parsed_args.train_batch_size, 'test_batch_size'... |
def seresnext101_32x4d(**kwargs):
return get_seresnext(blocks=101, cardinality=32, bottleneck_width=4, model_name='seresnext101_32x4d', **kwargs) |
class PerformanceWidget():
def __init__(self, viz):
self.viz = viz
self.gui_times = ([float('nan')] * 60)
self.render_times = ([float('nan')] * 30)
self.norm_times = ([float('nan')] * 30)
self.predict_times = ([float('nan')] * 30)
def timing_text(self, times):
viz... |
def add_tabular_output(file_name):
if (file_name in _tabular_fds_hold.keys()):
_tabular_outputs.append(file_name)
_tabular_fds[file_name] = _tabular_fds_hold[file_name]
else:
_add_output(file_name, _tabular_outputs, _tabular_fds, mode='w') |
(version='2.0')
_registry('DyNAS')
class DyNAS(NASBase):
def __init__(self, conf_fname_or_obj):
super().__init__()
self.init_cfg(conf_fname_or_obj)
self.dynas_manager = DyNASManager(supernet=self.supernet, optimization_metrics=self.metrics, measurements=self.metrics, search_tactic='linas', n... |
def test_get_point_rgb_correspondences_raytracing() -> None:
origin = np.array([1., 0., 1.])
img_h = 2048
img_w = 1550
fx = 1683.
fy = 1683.
u = (img_w // 2)
v = (img_h - 1)
ray_dir = compute_pixel_ray_direction(u, v, fx, fy, img_w, img_h)
v0 = np.array([1, 10, 0]).astype(np.float32)... |
class RandomResize():
def __init__(self, min_size, max_size=None):
self.min_size = min_size
if (max_size is None):
max_size = min_size
self.max_size = max_size
def __call__(self, image, target):
size = random.randint(self.min_size, self.max_size)
image = funct... |
def test_snapshotKeplerPotential_Rforce_naz():
s = pynbody.new(star=1)
s['mass'] = 1.0
s['eps'] = 0.0
sp = potential.SnapshotRZPotential(s, num_threads=1)
spaz = potential.SnapshotRZPotential(s, num_threads=1, nazimuths=12)
assert (numpy.fabs((sp.Rforce(1.0, 0.0) - spaz.Rforce(1.0, 0.0))) < (10.... |
class LTOCF2(BasicModel):
def __init__(self, config: dict, dataset: BasicDataset):
super(LTOCF2, self).__init__()
self.config = config
self.dataset: dataloader.BasicDataset = dataset
self.__init_weight()
self.__init_ode()
def __init_weight(self):
self.num_users = ... |
def _ReadImageList(list_path):
with tf.gfile.GFile(list_path, 'r') as f:
image_paths = f.readlines()
image_paths = [entry.rstrip() for entry in image_paths]
return image_paths |
class AdamW_GCC2(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon value: {}'.... |
class MyLogger(object):
def __init__(self, fname, reinitialize=False, logstyle='%3.3f'):
self.root = fname
if (not os.path.exists(self.root)):
os.mkdir(self.root)
self.reinitialize = reinitialize
self.metrics = []
self.logstyle = logstyle
def reinit(self, item... |
def main(args):
device = ('cuda' if torch.cuda.is_available() else 'cpu')
(model, _) = clip.load(args.model_type_or_path, jit=False, device=device)
imgs = utils.load_json(args.anno)['images']
random.shuffle(imgs)
for img in tqdm(imgs):
image_id = img['cocoid']
dst_path = os.path.join... |
def need_apply(configs_mapping: Dict[(Tuple[(str, callable)], BaseConfig)], algo_name):
return any(((config.name == algo_name) for config in configs_mapping.values())) |
def worker(worker_id, start, end):
np.random.seed(worker_id)
env_args = dict(domain='rope_sac', task='easy', max_path_length=5, pixel_wrapper_kwargs=dict(observation_key='pixels', pixels_only=False, render_kwargs=dict(width=64, height=64, camera_id=0)))
env = DMControlEnv(**env_args)
total = 0
if (w... |
def sig_handler(signum, frame):
logger.warning(('Signal handler called with signal ' + str(signum)))
prod_id = int(os.environ['SLURM_PROCID'])
logger.warning(('Host: %s - Global rank: %i' % (socket.gethostname(), prod_id)))
if (prod_id == 0):
logger.warning(('Requeuing job ' + os.environ['SLURM_... |
def main():
start_time = time.time()
parser = argparse.ArgumentParser()
add_args(parser)
args = parser.parse_args()
print(args)
print('Is jax using decorators?', (not jax.config.read('jax_disable_jit')))
rng_seq = hk.PRNGSequence(args.random_seed)
p_log_prob = hk.transform((lambda x, z:... |
class CryptoAgent(Agent):
def __init__(self):
super(CryptoAgent, self).__init__()
self.key = None |
class AttentionReplace(AttentionControlEdit):
def __init__(self, prompts, tokenizer, num_steps: int, cross_replace_steps: float, self_replace_steps: float, device='cpu'):
super(AttentionReplace, self).__init__(prompts, num_steps, cross_replace_steps, self_replace_steps, tokenizer, device=device)
sel... |
def match_argument(args_A: List['ArgDef'], args_B: List['ArgDef'], verbose=True) -> List[Tuple[(int, int)]]:
sim = ArgDef.similarity(args_A, args_B, verbose=False)
sim_matrix = [[(5 - y) for y in x] for x in sim]
m = Munkres()
indices = m.compute(sim_matrix)
indices.sort(key=(lambda x: x[1]))
fi... |
class TFLiteRunner():
def __init__(self, tfnet_callable: TFNetCallable) -> None:
self.tfnet_callable = tfnet_callable
def __call__(self, input: Dict[(str, np.ndarray)]) -> Dict[(str, np.ndarray)]:
return {k: np.array(v) for (k, v) in self.tfnet_callable(**input).items()} |
class GhostObsFilter(ObsFilter):
def __init__(self, obs_filter: ObsFilter, ghost_name: PlayerName, further_than: float=0):
assert issubclass(type(obs_filter), ObsFilter)
self.obs_filter = obs_filter
self.ghost_name: PlayerName = ghost_name
self.further_than: float = further_than
... |
def run_posegraph_optimization(pose_graph_name, pose_graph_optimized_name, max_correspondence_distance, preference_loop_closure):
o3d.utility.set_verbosity_level(o3d.utility.VerbosityLevel.Debug)
method = o3d.pipelines.registration.GlobalOptimizationLevenbergMarquardt()
criteria = o3d.pipelines.registration... |
class CamembertConfig(PretrainedConfig):
model_type = 'camembert'
def __init__(self, vocab_size=30522, hidden_size=768, num_hidden_layers=12, num_attention_heads=12, intermediate_size=3072, hidden_act='gelu', hidden_dropout_prob=0.1, attention_probs_dropout_prob=0.1, max_position_embeddings=512, type_vocab_size... |
_module(name='Caffe2Xavier')
class Caffe2XavierInit(KaimingInit):
def __init__(self, **kwargs):
super().__init__(a=1, mode='fan_in', nonlinearity='leaky_relu', distribution='uniform', **kwargs)
def __call__(self, module):
super().__call__(module) |
def finish_dual_setup(prob: cp.Problem, S: np.ndarray, X: np.ndarray, quantile: float, Phi: np.ndarray, x_calib: np.ndarray, infinite_params={}):
prob.param_dict['S_test'].value = np.asarray([[S]])
prob.param_dict['Phi_test'].value = Phi.reshape(1, (- 1))
prob.param_dict['quantile'].value = quantile
ker... |
def get_select_student_channels_list(out_channels):
the_list = [(out_channels * 2.5), (out_channels * 2), (out_channels * 1.5), (out_channels * 1.25), out_channels, (out_channels / 1.25), (out_channels / 1.5), (out_channels / 2), (out_channels / 2.5)]
the_list = [min(2048, max(8, x)) for x in the_list]
the_... |
def remove_files_if_exist(file_paths):
for fp in file_paths:
if os.path.isfile(fp):
os.remove(fp) |
class CaseWithoutAVX512():
def test_unsupported_HW_or_OS(self):
model = resnet18(num_classes=10)
with pytest.raises(RuntimeError, match='Applying IPEX BF16 optimization needs the cpu support avx512.'):
bf16_model = InferenceOptimizer.quantize(model, precision='bf16', use_ipex=True) |
class DebertaOnnxConfig(OnnxConfig):
def inputs(self) -> Mapping[(str, Mapping[(int, str)])]:
if (self.task == 'multiple-choice'):
dynamic_axis = {0: 'batch', 1: 'choice', 2: 'sequence'}
else:
dynamic_axis = {0: 'batch', 1: 'sequence'}
if (self._config.type_vocab_size... |
def create_metric(metric):
metrics = []
Class = load_class(('evaluation.metrics.' + metric['class']))
if ('length' in metric):
for list_length in metric['length']:
metrics.append(Class(list_length))
else:
metrics.append(Class())
return metrics |
def partition_refs_to_creator(partition_refs, shuffle=False):
def data_creator(config, kv):
import mxnet as mx
invalidInputError(('batch_size' in config), 'batch_size must be set in config')
(data, label) = partitions_get_data_label(ray.get(partition_refs), allow_tuple=False, allow_list=Fals... |
def crps_minimization(std_dev_array, y, yHat_means):
return np.mean(ps.crps_gaussian(y, mu=yHat_means, sig=std_dev_array[0])) |
class DataProcessor(object):
def get_src_train_examples(self, data_dir):
return self._create_examples(self._read_pkl(os.path.join(data_dir, 'en_conll_train.pkl')), 'conll_train')
def get_src_dev_examples(self, data_dir):
return self._create_examples(self._read_pkl(os.path.join(data_dir, 'en_conl... |
def main_split_file():
excluded_show_name = 'friends'
archive_show_name2desc_ids = load_json(archive_show_name2desc_ids_path)
for path_mapping in [archive_split_name2data_path_mapping, release_split_name2data_path_mapping]:
for (split_name, split_path) in path_mapping.items():
desc_id2da... |
class VideoMAEModel(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class OutlierDetector():
def __init__(self):
pass
def detect_by_std_mean(self, data, n_dev):
if (len(data) == 0):
return []
data_std = np.std(data)
data_mean = np.mean(data)
anomaly_cut_off = (data_std * n_dev)
lower_limit = (data_mean - anomaly_cut_of... |
class MsmarcoDataset(Dataset):
def __init__(self, collection_path: str, tokenizer: PreTrainedTokenizer, p_max_len=192):
self.collection = []
self.docids = []
for filename in os.listdir(collection_path):
with open(f'{collection_path}/{filename}', 'r') as f:
lines =... |
def _mobilenet_v3_conf(arch: str, params: Dict[(str, Any)]):
reduce_divider = (2 if params.pop('_reduced_tail', False) else 1)
dilation = (2 if params.pop('_dilated', False) else 1)
width_mult = params.pop('_width_mult', 1.0)
bneck_conf = partial(InvertedResidualConfig, width_mult=width_mult)
adjust... |
class PegasusTokenizerFast(PreTrainedTokenizerFast):
offset = 103
vocab_files_names = VOCAB_FILES_NAMES
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
slow_tokenizer_class = PegasusTokenizer
model_input_names = ['attention_m... |
def sample(map, corridor_radius):
random_x = np.random.choice(range((corridor_radius + 2), ((map.shape[0] - corridor_radius) - 1), 1))
random_y = np.random.choice(range((corridor_radius + 2), ((map.shape[1] - corridor_radius) - 1), 1))
return [random_x, random_y] |
def main():
parser = argparse.ArgumentParser(description='Creates the ops.py file')
parser.add_argument('--input', type=str, required=True, help='input file with header')
parser.add_argument('--output', type=str, required=True, help='output file')
parser.add_argument('--lib', type=str, required=True, he... |
def test_forward_method_accepted():
cnn = CNN(model_config=CustomModel(model=ForwardModel(), transform=ForwardModel.transform, name=ForwardModel.name))
assert (cnn.model_config.name == ForwardModel.name)
assert (cnn.model_config.transform == ForwardModel.transform)
try:
cnn.encode_images(TEST_IM... |
def calc_error(est_disp=None, gt_disp=None, lb=None, ub=None):
error1 = torch.Tensor([0.0])
error2 = torch.Tensor([0.0])
error3 = torch.Tensor([0.0])
error5 = torch.Tensor([0.0])
epe = torch.Tensor([0.0])
if ((not torch.is_tensor(est_disp)) or (not torch.is_tensor(gt_disp))):
return {'1p... |
_model_architecture('s2t_transformer_w2v2', 's2t_transformer_b_w2v_6tenc_6dec')
def s2t_transformer_b_12aenc_6tenc_6dec(args):
args.translation_encoder_layers = getattr(args, 'translation_encoder_layers', 6)
base_architecture(args) |
_module
class ImageToTensor(object):
def __init__(self, keys):
self.keys = keys
def __call__(self, results):
for key in self.keys:
results[key] = to_tensor(results[key].transpose(2, 0, 1))
return results
def __repr__(self):
return (self.__class__.__name__ + '(keys... |
def read_image_file(path):
with open(path, 'rb') as f:
data = f.read()
assert (get_int(data[:4]) == 2051)
length = get_int(data[4:8])
num_rows = get_int(data[8:12])
num_cols = get_int(data[12:16])
images = []
parsed = np.frombuffer(data, dtype=np.uint8, offset... |
def load_multprec_system():
from phcpy.phcpy2c3 import py2c_syscon_number_of_multprec_polynomials
from phcpy.phcpy2c3 import py2c_syscon_load_multprec_polynomial
dim = py2c_syscon_number_of_multprec_polynomials()
result = []
for ind in range(1, (dim + 1)):
result.append(py2c_syscon_load_mult... |
def get_required_argument(dotmap, key, message, default=None):
val = dotmap.get(key, default)
if (val is default):
raise ValueError(message)
return val |
def scaffold_similarity(smiles_1: List[str], smiles_2: List[str]):
scaffold_to_smiles_1 = scaffold_to_smiles(smiles_1)
scaffold_to_smiles_2 = scaffold_to_smiles(smiles_2)
(scaffolds_1, smiles_sets_1) = zip(*scaffold_to_smiles_1.items())
(scaffolds_2, smiles_sets_2) = zip(*scaffold_to_smiles_2.items())
... |
def test_handle_hidden_limit_orders():
bid_order = LimitOrder(agent_id=1, time_placed=TIME, symbol=SYMBOL, quantity=10, side=Side.BID, is_hidden=True, limit_price=100)
agent = FakeExchangeAgent()
book = OrderBook(agent, SYMBOL)
book.handle_limit_order(bid_order)
assert (book.bids == [PriceLevel([(bi... |
def reload_data(data_paths):
exps_data = copy.copy(core.load_exps_data(data_paths, disable_variant=False, ignore_missing_keys=True))
plottable_keys = copy.copy(sorted(list(set(flatten((list(exp.progress.keys()) for exp in exps_data))))))
distinct_params = copy.copy(sorted(core.extract_distinct_params(exps_d... |
def _check_sequence_input(x, name, req_sizes):
msg = (req_sizes[0] if (len(req_sizes) < 2) else ' or '.join([str(s) for s in req_sizes]))
if (not isinstance(x, Sequence)):
raise TypeError('{} should be a sequence of length {}.'.format(name, msg))
if (len(x) not in req_sizes):
raise ValueErro... |
def create_model(sess, config, cate_list):
print(json.dumps(config, indent=4), flush=True)
model = Model(config, cate_list)
print('All global variables:')
for v in tf.global_variables():
if (v not in tf.trainable_variables()):
print('\t', v)
else:
print('\t', v, '... |
class ResizeBatch(Module):
def __init__(self, *size: int):
self.size = size
def forward(self, x):
return x.view(((x.size(0),) + self.size)) |
def collect_files(img_dir, gt_dir, split):
assert isinstance(img_dir, str)
assert img_dir
assert isinstance(gt_dir, str)
assert gt_dir
suffixes = ['.png', '.PNG', '.jpg', '.JPG', '.jpeg', '.JPEG']
imgs_list = []
for suffix in suffixes:
imgs_list.extend(glob.glob(osp.join(img_dir, ('*... |
def process_gallery_sysu_all(mode='all', data_path_ori='/home/share/reid_dataset/SYSU-MM01/'):
if (mode == 'all'):
rgb_cameras = ['cam1', 'cam2', 'cam4', 'cam5']
elif (mode == 'indoor'):
rgb_cameras = ['cam1', 'cam2']
file_path = os.path.join(data_path_ori, 'exp/test_id.txt')
files_rgb =... |
class CNNGeometric(nn.Module):
def __init__(self, output_dim=6, feature_extraction_cnn='vgg', feature_extraction_last_layer='', return_correlation=False, fr_feature_size=15, fr_kernel_sizes=[7, 5], fr_channels=[128, 64], feature_self_matching=False, normalize_features=True, normalize_matches=True, batch_normalizati... |
def writeWorld(output):
global wroteWorld
if wroteWorld:
return
writePreamble(output)
writeSuites(output)
if (options.root or (not options.part)):
writeRoot(output)
writeWorldDescr(output)
if options.noStaticInit:
writeInitialize(output)
wroteWorld = 1 |
def compute_detection_metrics(df: pd.DataFrame, max_dets: list=[30], max_ddg: float=(- 0.5)):
metrics_pdb = []
for pdb_id in df.pdb_id.unique():
df_pdb = df[(df.pdb_id == pdb_id)].sort_values('scores', ascending=False)
scores = df_pdb.scores.to_numpy()
ddg = df_pdb.ddg.to_numpy()
... |
class Occlusion_detector(nn.Module):
def __init__(self, input_channels=768, num_tokens=128, num_latents=64, latent_dim=768, cross_heads=8, latent_heads=8, cross_dim_head=96, latent_dim_head=96, attn_dropout=0.0, ff_dropout=0.0):
super().__init__()
self.latents1 = nn.Parameter(torch.randn(1, num_late... |
class SnippetInfill(ast.NodeTransformer):
def __init__(self, mask_identifier: str, api_call: str, prefix: str, library: str, replace_type: str='argument'):
self.mask_identifier = mask_identifier
self.api_call = api_call
self.num_replaced = 0
self.line_no = (- 1)
self.prefix =... |
def test_SE2_inverse_transform_point_cloud_identity() -> None:
transformed_pts = np.array([[0.5, 0], [1, (- 0.5)], [1.5, 0], [2, (- 1)]])
dst_se2_src = SE2(rotation=np.eye(2), translation=np.zeros(2))
pts = dst_se2_src.inverse_transform_point_cloud(transformed_pts.copy())
assert np.allclose(pts, transfo... |
class RandomIdentitySampler(Sampler):
def __init__(self, data_source, batch_size, num_instances):
self.data_source = data_source
self.batch_size = batch_size
self.num_instances = num_instances
self.num_pids_per_batch = (self.batch_size // self.num_instances)
self.index_dic = ... |
def nlvr2_paired_eval_collate(inputs):
(qids, batch) = ([], [])
for (id_, *tensors) in inputs:
qids.append(id_)
batch.append(tensors)
batch = nlvr2_paired_collate(batch)
batch['qids'] = qids
return batch |
class BilinearDecoder(nn.Module):
def __init__(self, input_dim: int, dropout: float=0.0, act=(lambda x: x)):
super(BilinearDecoder, self).__init__()
self.dropout = nn.Dropout(dropout)
self.act = act
self.relation = Parameter(torch.FloatTensor(input_dim, input_dim))
self.reset... |
def test():
api_name = 'torch.nn.Conv2d'
api = TorchAPI(api_name)
MyPytorch = TorchLibrary('torch-output')
print(MyPytorch.generate_code(api, OracleType.CRASH))
print(MyPytorch.generate_code(api, OracleType.CUDA))
print(MyPytorch.generate_code(api, OracleType.PRECISION))
MyPytorch.test_with_... |
def analyze_pred_dist_single_step(pred_distribution: np.ndarray, k=5):
ent = scipy.stats.entropy(pred_distribution)
level_of_ent = (int(ent) * 3)
topk_idx = pred_distribution.argsort()[(- k):][::(- 1)]
(words, probs) = ([], [])
decoded_word = bpe_tokenizer.decode(int(topk_idx[0]))
for index in t... |
def get_config():
name = 'finite_drift'
n_arm = 3
agents = collections.OrderedDict([('stationary_ts', functools.partial(FiniteBernoulliBanditTS, n_arm)), ('nonstationary_ts', functools.partial(DriftingFiniteBernoulliBanditTS, n_arm))])
environments = collections.OrderedDict([('env', functools.partial(Dr... |
class ScalarField(object):
name = attr.ib(type=str)
upper_bound = attr.ib(type=float)
lower_bound = attr.ib(type=float) |
class NoAugWaterbirdsCelebATransform(BaseWaterbirdsCelebATransform):
def __init__(self, train):
super().__init__(augment=False, normalize_stats=IMAGENET_STATS) |
def get_latent_grads(backdoor_label, model, inputs, labels):
model.eval()
model.zero_grad()
pred = model(inputs)
z = torch.zeros_like(pred)
z[(list(range(labels.shape[0])), labels)] = 1
pred = (pred * z)
pred.sum().backward(retain_graph=True)
gradients = model.get_gradient()[(labels == b... |
class LSTM_Univariate(nn.Module):
def __init__(self, feats):
super(LSTM_Univariate, self).__init__()
self.name = 'LSTM_Univariate'
self.lr = 0.002
self.n_feats = feats
self.n_hidden = 1
self.lstm = nn.ModuleList([nn.LSTM(1, self.n_hidden) for i in range(feats)])
d... |
class DataHandlerTest(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def fake_folders(self, kind):
if (kind['matching'] == False):
if (kind['res'] == 'hr'):
return ['data2.gif', 'data1.png', 'data0.jpeg']
elif (kind['res'] =... |
def prototype_ubuntu_GaussPiecewise_NormOp_VHRED_Exp13():
state = prototype_state()
state['end_sym_utterance'] = '__eot__'
state['unk_sym'] = 0
state['eos_sym'] = 1
state['eod_sym'] = (- 1)
state['first_speaker_sym'] = (- 1)
state['second_speaker_sym'] = (- 1)
state['third_speaker_sym'] ... |
def get_dataset(name: str, use_lcc: bool=True, data_dir=DEFAULT_DATA_PATH) -> InMemoryDataset:
path = os.path.join(data_dir, name)
if (name in ['Cora', 'Citeseer', 'Pubmed']):
dataset = Planetoid(path, name)
elif (name in ['Computers', 'Photo']):
dataset = Amazon(path, name)
elif (name =... |
def check_box_3d_format(input_data):
if isinstance(input_data, np.ndarray):
if (input_data.ndim == 2):
if (input_data.shape[1] != 7):
raise TypeError('Given input does not have valid number of attributes. Should be N x 7 for box_3d.')
elif (input_data.ndim == 1):
... |
def validate(val_loader, tracking_module, step, part='train', fusion_list=None, fuse_prob=False):
logger = logging.getLogger('global_logger')
for (i, sequence) in enumerate(val_loader):
logger.info('Test: [{}/{}]\tSequence ID: KITTI-{}'.format(i, len(val_loader), sequence.name))
seq_loader = Dat... |
_grad()
def convert_efficientnet_checkpoint(model_name, pytorch_dump_folder_path, save_model, push_to_hub):
original_model = model_classes[model_name](include_top=True, weights='imagenet', input_tensor=None, input_shape=None, pooling=None, classes=1000, classifier_activation='softmax')
tf_params = original_mode... |
def Variable(initial_value, dtype=None):
return tf.Variable(initial_value=initial_value, trainable=True, dtype=dtype) |
def create_lm_sequence(dp_json):
((prompt_keyword, prompt_text), (completion_keyword, completion_text)) = list(dp_json.items())
prompt = ((prompt_keyword.upper() + ' ') + str(prompt_text))
completion = ((completion_keyword.upper() + ' ') + str(completion_text))
return ((prompt + ' ') + completion) |
class HyperAnalysisTransform(nn.Module):
def __init__(self, num_filters=192):
super(HyperAnalysisTransform, self).__init__()
self.conv_h1 = nn.Conv2d(num_filters, num_filters, 3, stride=1, padding=1)
self.relu_h1 = nn.ReLU()
self.conv_h2 = nn.Conv2d(num_filters, num_filters, 5, strid... |
('cnndm')
class CNNDMDatasetReader(DatasetReader):
def __init__(self, lazy: bool=True, bert_model_name: str='bert-base-uncased', max_bpe: int=None, token_indexers: Dict[(str, TokenIndexer)]=PretrainedBertIndexer('bert-base-uncased'), debug: bool=False, bertsum_oracle: bool=True, semantic_red_map: bool=True, semanti... |
class ResNet(nn.Module):
def __init__(self, block, num_blocks, num_classes, nf, bias):
super(ResNet, self).__init__()
self.in_planes = nf
self.conv1 = conv3x3(3, (nf * 1))
self.bn1 = nn.BatchNorm2d((nf * 1))
self.layer1 = self._make_layer(block, (nf * 1), num_blocks[0], strid... |
class OpenVINOModel():
def __init__(self, base_model):
self.ie = IECore()
self.exec_net = None
self.base_model = base_model
self.device = 'CPU'
torch.square = (lambda x: torch.pow(x, 2))
def _get_input_names(self, inputs):
names = []
for (name, tensor) in ... |
def get_config(num_predators):
state_initialization = StateInitialization(num_predators=num_predators, step_scaling_factor=0.1, threshold_trial_len=200)
agent_friction_force = physics_lib.Drag(coeff_friction=0.25)
predator_friction_force = physics_lib.Drag(coeff_friction=0.04)
predator_random_force = ph... |
def parser():
PARSER = argparse.ArgumentParser(description='Training parameters.')
PARSER.add_argument('--dataset', default='CIFAR10', type=str, choices=['CIFAR10', 'CelebA', 'Imagenette', 'ImageNet32', 'ImageNet64'], help='Data to be used.')
PARSER.add_argument('--img_resize', default=32, type=int, help='C... |
def test(model, loader):
model.eval()
device = next(model.parameters()).device
correct = 0
loss = 0
total = 0
for (i, (x, y)) in enumerate(loader):
x = x.to(device)
y = y.to(device)
with torch.no_grad():
yhat = model(x)
(_, pred) = yhat.max(1)
... |
class GraphSignature(torch.nn.Module):
def __init__(self, args, in_channels, out_channels):
super(GraphSignature, self).__init__()
self.args = args
if self.args.use_gcn_sig:
self.conv1 = MetaGCNConv(in_channels, (2 * out_channels), cached=False)
self.fc1 = nn.Linear((... |
def CheckRValueReference(filename, clean_lines, linenum, nesting_state, error):
line = clean_lines.elided[linenum]
match = Match('^(.*\\S)&&', line)
if (not match):
match = Match('(.*)&&\\S', line)
if ((not match) or ('(&&)' in line) or Search('\\boperator\\s*$', match.group(1))):
return... |
def add_crd_args(parser):
group = parser.add_argument_group('CRD')
group.add_argument('--teacher_model_arch', '--tma', default='roberta_base', type=str, metavar='N', help='teacher model arch')
group.add_argument('--teacher_model_checkpoint', '--tmc', default=None, type=str, metavar='N', help='teacher model ... |
class UNet2DModel(ModelMixin, ConfigMixin):
_to_config
def __init__(self, sample_size: Optional[Union[(int, Tuple[(int, int)])]]=None, in_channels: int=3, out_channels: int=3, center_input_sample: bool=False, time_embedding_type: str='positional', freq_shift: int=0, flip_sin_to_cos: bool=True, down_block_types:... |
def get_labelname(label):
num_labels = len(labelmap.item)
found = False
for i in xrange(0, num_labels):
if (label == labelmap.item[i].label):
found = True
return labelmap.item[i].display_name
assert (found == True) |
def to_file(out, u_rels, k, min_ims, complete_line):
line_to_synset = {}
with open(complete_line, 'w') as f:
for (i, (key, value)) in enumerate(out.items()):
if value:
line_to_synset[i] = key
f.write((((str(i) + ' ') + ' '.join([str(v) for v in value.values()]... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.