code stringlengths 101 5.91M |
|---|
class NDCG(BaseMetric):
def __init__(self, recommendations, config, params, eval_objects):
super().__init__(recommendations, config, params, eval_objects)
self._cutoff = self._evaluation_objects.cutoff
self._relevance = self._evaluation_objects.relevance.discounted_relevance
self._re... |
def read_tfrecord(example, train):
features = {'image': tf.io.FixedLenFeature([], tf.string), 'class': tf.io.FixedLenFeature([], tf.int64)}
example = tf.io.parse_single_example(example, features)
image = tf.image.decode_jpeg(example['image'], channels=3)
image = (tf.cast(image, tf.float32) / 255.0)
... |
def make_examples(DATA_DIR, train_file, predict_file, evaluate, version_2_with_negative):
processor = (SquadV2Processor() if version_2_with_negative else SquadV1Processor())
if evaluate:
examples = processor.get_dev_examples(DATA_DIR, filename=predict_file)
else:
examples = processor.get_tra... |
def register_Ns3LteEnbMac_methods(root_module, cls):
cls.add_constructor([param('ns3::LteEnbMac const &', 'arg0')])
cls.add_constructor([])
cls.add_method('DoDispose', 'void', [], is_virtual=True)
cls.add_method('DoReceivePhyPdu', 'void', [param('ns3::Ptr< ns3::Packet >', 'p')])
cls.add_method('GetF... |
class ReplayBuffer(object):
def __init__(self, state_dim, action_dim, max_size=int(1000000.0)):
self.max_size = max_size
self.ptr = 0
self.size = 0
self.state = np.zeros((max_size, state_dim))
self.action = np.zeros((max_size, action_dim))
self.next_state = np.zeros((... |
class ArgoCSVDataset(torch.utils.data.Dataset):
def __init__(self, input_folder, input_preprocessed, args):
self.input_preprocessed = input_preprocessed
self.args = args
if args.use_preprocessed:
with open(input_preprocessed, 'rb') as f:
self.data = pickle.load(f)... |
def convert_mxnet_to_torch(filename):
import mxnet
save_dict = mxnet.nd.load(filename)
renamed_dict = dict()
bn_param_mx_pt = {'beta': 'bias', 'gamma': 'weight', 'mean': 'running_mean', 'var': 'running_var'}
for (k, v) in save_dict.items():
v = torch.from_numpy(v.asnumpy())
toks = k.... |
def main(_argv):
if FLAGS.config_path:
with gfile.GFile(FLAGS.config_path) as config_file:
config_flags = yaml.load(config_file)
for (flag_key, flag_value) in config_flags.items():
setattr(FLAGS, flag_key, flag_value)
if isinstance(FLAGS.tasks, string_types):
... |
class BaseOptions():
def __init__(self):
self.initialized = False
def initialize(self, parser):
parser.add_argument('--dataroot', type=str, default='.', help='path to images (should have subfolders train, test etc)')
parser.add_argument('--batch_size', type=int, default=1, help='input ba... |
def set_random_seed(seed):
if (seed >= 0):
np.random.seed(seed)
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) |
def evaluate(args, model, tokenizer, prefix=''):
eval_task_names = (('mnli', 'mnli-mm') if (args.task_name == 'mnli') else (args.task_name,))
eval_outputs_dirs = ((args.output_dir, (args.output_dir + '-MM')) if (args.task_name == 'mnli') else (args.output_dir,))
results = {}
for (eval_task, eval_output_... |
def get_mnist_datasets(train_transform, test_transform, train_classes=range(6), open_set_classes=range(6, 10), balance_open_set_eval=False, split_train_val=True, seed=0):
np.random.seed(seed)
train_dataset_whole = CustomMNIST(root=mnist_root, transform=train_transform, train=True)
train_dataset_whole = subs... |
def cot(all_potential_countries) -> operations.GraphOfOperations:
operations_graph = operations.GraphOfOperations()
operations_graph.append_operation(operations.Generate(1, 1))
operations_graph.append_operation(operations.Score(1, False, partial(num_errors, all_potential_countries)))
operations_graph.ap... |
class TVoid(object):
thisown = _swig_property((lambda x: x.this.own()), (lambda x, v: x.this.own(v)), doc='The membership flag')
__repr__ = _swig_repr
def __init__(self, *args):
_snap.TVoid_swiginit(self, _snap.new_TVoid(*args))
def Save(self, arg2):
return _snap.TVoid_Save(self, arg2)
... |
class AugmenterValidationScoresEvaluator(AugmenterEvaluatorBase):
def __init__(self, validation_scorers_dict: Dict[(str, ValidationScorerBase)], namespace='', run_logger=None):
super().__init__(namespace, run_logger)
self.validation_scorers_dict = validation_scorers_dict
def evaluate(self, augme... |
.mujoco
def test_mtsac_inverted_double_pendulum():
env_names = ['InvertedDoublePendulum-v2', 'InvertedDoublePendulum-v2']
task_envs = [GarageEnv(env_name=name) for name in env_names]
env = MultiEnvWrapper(task_envs, sample_strategy=round_robin_strategy)
test_envs = MultiEnvWrapper(task_envs, sample_stra... |
def get_survey(data_type, rx_type, tx_type):
n_spacings = np.logspace(0, 2, 3)
y = np.zeros_like(n_spacings)
z = np.full_like(n_spacings, (- 1.0))
a_locations = np.column_stack((((- 1.5) * n_spacings), y, z))
b_locations = np.column_stack(((1.5 * n_spacings), y, z))
m_locations = np.column_stack... |
def _get_trajectory_dataset_fn(stack_size: int, trajectory_length: int=1) -> Callable[([tf.data.Dataset], tf.data.Dataset)]:
batch_fn = _BatchToTransition().create_transitions
def make_trajectory_dataset(episode: tf.data.Dataset) -> tf.data.Dataset:
timesteps: tf.data.Dataset = episode[rlds.STEPS]
... |
def baseline_detaset_find_examples_fn(search_funcs=None, **kwargs):
search_funcs.heuristic_fn = (lambda *args, **lambda_kwargs: 0)
results = dataset_find_adversarial_examples(search_funcs=search_funcs, **kwargs)
return results |
class expectedAlertNondeterministic():
def __init__(self, caller_name, device_type=None, fn_has_device_arg=True):
self.device_type = device_type
self.error_message = (caller_name + ' does not have a deterministic implementation, but you set')
self.fn_has_device_arg = fn_has_device_arg
de... |
def test_soft_voting_no_proba(create_X_y):
from sklearn.linear_model import Perceptron
(X, y) = create_X_y
clf = Perceptron()
clf.fit(X, y)
with pytest.raises(ValueError):
DESMI([clf, clf, clf, clf], voting='soft').fit(X, y) |
def threshold(input, threshold, value, inplace=False):
if inplace:
return torch._C._nn.threshold_(input, threshold, value)
return torch._C._nn.threshold(input, threshold, value) |
class GLPNFeatureExtractor(GLPNImageProcessor):
def __init__(self, *args, **kwargs) -> None:
warnings.warn('The class GLPNFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please use GLPNImageProcessor instead.', FutureWarning)
super().__init__(*args, **kwargs) |
def ct_tokenizer(nlp):
prefix_re = re.compile('^([\\["\'()*+-?/<>#%]+|[><][=])+')
suffix_re = re.compile('([\\]"\'),-.:;*]|\'s)$')
infix_re = re.compile('[%(),-./;=?]+')
tokenizer = Tokenizer(nlp.vocab, prefix_search=prefix_re.search, suffix_search=suffix_re.search, infix_finditer=infix_re.finditer, tok... |
def build_norm_layer(cfg, num_features, postfix=''):
assert (isinstance(cfg, dict) and ('type' in cfg))
cfg_ = cfg.copy()
layer_type = cfg_.pop('type')
if (layer_type not in norm_cfg):
raise KeyError('Unrecognized norm type {}'.format(layer_type))
else:
(abbr, norm_layer) = norm_cfg[... |
def TF2FLRD(filenames, batchsize=10, buffersize=100, fetchbatch=2, shuffle=True, parse=_parse_, oneshot=False):
fetchsize = (batchsize * fetchbatch)
train_dataset = tf.data.TFRecordDataset(filenames=filenames)
train_dataset = train_dataset.prefetch(fetchsize)
train_dataset = train_dataset.map(parse)
... |
class VarLSTM(VarRNNBase):
def __init__(self, *args, **kwargs):
super(VarLSTM, self).__init__(*args, mode='LSTM', Cell=nn.LSTMCell, **kwargs)
def forward(self, x, hx=None):
return super(VarLSTM, self).forward(x, hx) |
class FeatureAlphaDropout(_DropoutNd):
def forward(self, input: Tensor) -> Tensor:
return F.feature_alpha_dropout(input, self.p, self.training) |
def add_noise(images, mean=0, std=0.1):
normal_dst = Normal(mean, std)
noise = normal_dst.sample(images.shape)
noisy_image = (noise + images)
return noisy_image |
def get_random_string(length: int) -> str:
letters = string.ascii_lowercase
result_str = ''.join((random.choice(letters) for _ in range(length)))
return result_str |
def init_cnn(m):
if (getattr(m, 'bias', None) is not None):
nn.init.constant_(m.bias, 0)
if isinstance(m, (nn.Conv2d, nn.Linear)):
nn.init.kaiming_normal_(m.weight)
for l in m.children():
init_cnn(l) |
def linear_synthetic_policy_continuous(context: np.ndarray) -> np.ndarray:
check_array(array=context, name='context', expected_dim=2)
return context.mean(1) |
.parametrize('nuclide_name', ['Ni-56', 'Fe-52', 'Cr-48'])
def test_decay_energy_chain(gamma_ray_simulation_state, atomic_dataset, nuclide_name):
nuclide = rd.Nuclide(nuclide_name)
isotopic_mass_fractions = gamma_ray_simulation_state.composition.isotopic_mass_fraction
composition = gamma_ray_simulation_state... |
class CC_head(nn.Module):
def __init__(self, indim, outdim, scale_cls=10.0, learn_scale=True, normalize=True):
super().__init__()
self.L = weight_norm(nn.Linear(indim, outdim, bias=False), name='weight', dim=0)
self.scale_cls = nn.Parameter(torch.FloatTensor(1).fill_(scale_cls), requires_gra... |
def index(request):
response = HttpResponse()
response.set_cookie('cookie', 'value')
return response |
def map_aa_idx_to_tok_set(esm_sampler_fixture):
return set((esm_sampler_fixture.model.alphabet.get_tok(idx) for idx in esm_sampler_fixture.valid_aa_idx)) |
def signal_name(sig):
if (sig == SIGHUP):
return 'hangup'
if (sig == SIGINT):
return 'interrupt'
if (sig == SIGQUIT):
return 'quit'
if (sig == SIGILL):
return 'illegal instruction'
if (sig == SIGABRT):
return 'abort'
if (sig == SIGFPE):
return 'flo... |
def compute_rouge_approximation(pred_summary, groundtruth):
pred_counts = Counter()
for sent in pred_summary:
pred_counts.update([k for k in sent.split() if (k not in string.punctuation)])
ref_counts = {}
for (i, summary) in enumerate(groundtruth):
ref_counts[i] = Counter()
for s... |
def masked_mse_loss(scaler, null_val):
def loss(preds, labels):
if scaler:
preds = scaler.inverse_transform(preds)
labels = scaler.inverse_transform(labels)
return masked_mse_tf(preds=preds, labels=labels, null_val=null_val)
return loss |
def main():
for att in (0, 1):
steps = list(range(100, 2600, 100))
logdir = os.path.join('logdirs/-nl2code-hearthstone-fef2c5b', 'att{}'.format(att))
for step in steps:
if (not os.path.exists(os.path.join(logdir, 'model_checkpoint-{:08d}'.format(step)))):
continue... |
class MLP(tf.keras.layers.Layer):
def __init__(self, num_layers, hidden_dim, output_dim):
super(MLP, self).__init__()
self.linear_or_not = True
self.num_layers = num_layers
if (num_layers < 1):
raise ValueError('number of layers should be positive!')
elif (num_lay... |
def get_start_end_idx(video_size, clip_size, clip_idx, num_clips, use_offset=False):
delta = max((video_size - clip_size), 0)
if (clip_idx == (- 1)):
start_idx = random.uniform(0, delta)
elif use_offset:
if (num_clips == 1):
start_idx = math.floor((delta / 2))
else:
... |
def test_gpflow_reparam_sampler_returns_reparam_sampler_with_correct_samples() -> None:
num_samples = 20000
sampler = _QuadraticPredictor().reparam_sampler(num_samples)
samples = sampler.sample(tf.constant([[2.5]], gpflow.default_float()))
assert (samples.shape == [num_samples, 1, 1])
sample_mean = ... |
def cnn(input_var, filters, strides, name, padding, hidden_nonlinearity=tf.nn.relu, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer()):
with tf.compat.v1.variable_scope(name):
h = input_var
for (index, (filter_iter, stride)) i... |
def code_for_backward_function(module: 'daceml.torch.DaceModule', forward_sdfg: dace.SDFG, backward_sdfg: dace.SDFG, backward_result: BackwardResult, forwarded_arrays: Dict[(str, data.Data)]) -> str:
(inputs, outputs) = get_arglist(module)
sdfg_name = forward_sdfg.name
ret_str = return_type_str(outputs)
... |
def compute_boundary_distance(mesh: fenics.Mesh, boundaries: Optional[fenics.MeshFunction]=None, boundary_idcs: Optional[List[Union[(int, str)]]]=None, tol: float=0.1, max_iter: int=10) -> fenics.Function:
function_space = fenics.FunctionSpace(mesh, 'CG', 1)
dx = measure.NamedMeasure('dx', mesh)
comm = mesh... |
class Model(nn.Module):
def __init__(self):
super(Model, self).__init__()
self.conv = nn.Conv2d(6, 16, 5)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv(x)), 2)
x = x.view((- 1), 256)
return F.relu(x) |
class PoolFormerGroupNorm(nn.GroupNorm):
def __init__(self, num_channels, **kwargs):
super().__init__(1, num_channels, **kwargs) |
def _solve_expression(f, x, explicit_solutions, multiplicities, to_poly_solve, solution_dict, algorithm, domain):
from sage.structure.element import Expression
if f.is_relational():
if (f.operator() is not operator.eq):
if (algorithm == 'sympy'):
from sympy import S, solveset... |
def find_critical_alpha(id, a0, mse_criterion, alpha_min, alpha_max, model_builder, alpha_tol=1e-06, vtol=0.001, **model_kwargs):
if (mse_criterion == 'perfect'):
def mse_criterion(v):
return (abs(v) < vtol)
elif (mse_criterion == 'random'):
model = model_builder(alpha=0.5, **model_k... |
class ResNeXt(nn.Module):
def __init__(self, baseWidth, cardinality, layers, num_classes):
super(ResNeXt, self).__init__()
block = Bottleneck
self.cardinality = cardinality
self.baseWidth = baseWidth
self.num_classes = num_classes
self.inplanes = 64
self.outpu... |
def start_server(args):
th.set_num_threads(NUM_THREAD)
server_namebook = dgl.contrib.read_ip_config(filename=args.ip_config)
port = server_namebook[args.server_id][2]
if (check_port_available(port) == False):
print(('Error: port %d is not available.' % port))
exit()
my_server = KGESe... |
class POIarray():
def __init__(self, parameter, values: (Collection | np.array)):
if (not is_valid_parameter(parameter)):
raise ValueError(f'{parameter} is not a valid parameter!')
if (not isinstance(values, Collection)):
raise TypeError('A list/array of values of the POI is ... |
class NotebookFinder(object):
def __init__(self):
self.loaders = {}
def find_module(self, fullname, path=None):
nb_path = find_notebook(fullname, path)
if (not nb_path):
return
key = path
if path:
key = os.path.sep.join(path)
if (key not in... |
def convert_balloon_to_coco(ann_file, out_file, image_prefix):
data_infos = mmcv.load(ann_file)
annotations = []
images = []
obj_count = 0
for (idx, v) in enumerate(mmcv.track_iter_progress(data_infos.values())):
filename = v['filename']
img_path = osp.join(image_prefix, filename)
... |
_kl(Dirichlet, Dirichlet)
def _kl_dirichlet_dirichlet(p, q):
sum_p_concentration = p.concentration.sum((- 1))
sum_q_concentration = q.concentration.sum((- 1))
t1 = (sum_p_concentration.lgamma() - sum_q_concentration.lgamma())
t2 = (p.concentration.lgamma() - q.concentration.lgamma()).sum((- 1))
t3 =... |
def test_from_symbol_table_3(inferred_signature):
config.configuration.test_creation.negate_type = 0.0
with mock.patch('pynguin.utils.randomness.next_float') as float_mock:
float_mock.return_value = 0.0
knowledge = UsageTraceNode('ROOT')
knowledge.children['__eq__'].arg_types[0].add(int)... |
class TimeIt(object):
def __init__(self, prefix=''):
self.prefix = prefix
self.start_times = dict()
self.elapsed_times = defaultdict(int)
self._with_name_stack = []
self._with_args_stack = []
def __call__(self, name, reset_on_stop=False):
self._with_name_stack.app... |
class OUNoise():
def __init__(self, action_dimension, scale=0.1, mu=0, theta=0.15, sigma=0.2):
self.action_dimension = action_dimension
self.scale = scale
self.mu = mu
self.theta = theta
self.sigma = sigma
self.state = (np.ones(self.action_dimension) * self.mu)
... |
def add_sub_call_rc_final(ctx: LeanGenContext, called_func: LeanFunctionInfo, pc_offset: int, is_tail_call: bool):
if (ctx.rc_steps is not None):
ctx.concat_final(ctx.rc_steps.add_sub_call_rc_final(called_func.rc, pc_offset, is_tail_call)) |
def collect_one_rollout_mdp(env, expert, horizon=200, render=False, pause=0, threshold=(- 1)):
o = env.reset()
traj = dict(observations=[], actions=[], rewards=[], next_observations=[], terminals=[], agent_infos=[], env_infos=[])
ret = 0
for i in range(horizon):
(a, valid, _, _) = expert.get_act... |
def test_eq_other_type(control_flow_distance):
assert (not control_flow_distance.__eq__(MagicMock())) |
class SyncBatchNorm(SyncBatchNorm_):
def _check_input_dim(self, input):
if (TORCH_VERSION == 'parrots'):
if (input.dim() < 2):
raise ValueError(f'expected at least 2D input (got {input.dim()}D input)')
else:
super()._check_input_dim(input) |
class MLP(nn.Module):
def __init__(self, dim, hidden_dim, out_dim=None) -> None:
super().__init__()
out_dim = (out_dim or dim)
self.fc1 = nn.Conv2d(dim, hidden_dim, 1)
self.act = nn.GELU()
self.fc2 = nn.Conv2d(hidden_dim, out_dim, 1)
def forward(self, x: Tensor) -> Tensor... |
def report_dynamic_errors(dataset, old_new_file, new_new_file, max_t, current_t):
old_new_path = ((RESULT_ROOT / dataset) / old_new_file)
new_new_path = ((RESULT_ROOT / dataset) / new_new_file)
if (max_t > current_t):
try:
o_n = pd.read_csv(old_new_path)
n_n = pd.read_csv(new... |
def _wrap_io_open(file, mode, encoding, errors):
binary = ('b' in mode)
if binary:
kwargs = {}
else:
kwargs = {'encoding': encoding, 'errors': errors}
if ((not PY2) or binary):
return io.open(file, mode, **kwargs)
f = io.open(file, '{}b'.format(mode.replace('t', '')))
ret... |
def pad_tensor_n(xs, max_len):
ret = np.zeros(((len(xs), max_len) + xs[0].shape[1:]), dtype=xs[0].dtype)
for (idx, x) in enumerate(xs):
ret[idx][:len(x)] = x
return ret |
class LayoutBuilder():
def _init(self, parameters):
self._parameters = parameters
def parameters(self):
return self._parameters
def __len__(self):
raise AssertionError('missing implementation')
def numbatype(self):
raise AssertionError('missing implementation')
def sn... |
def ref_deconvolution_2d(x, w, b, base_axis, pad, stride, dilation, group, channel_last=False, output_padding=(0, 0)):
if channel_last:
transpose_x = refs.ChannelLastToFirstTranspose(x.ndim, len(pad))
transpose_w = refs.ChannelLastToFirstTranspose(w.ndim, len(pad))
return transpose_x.inv(ref... |
def evaluate_all_datasets(arch: Text, datasets: List[Text], xpaths: List[Text], splits: List[Text], config_path: Text, seed: int, raw_arch_config, workers, logger):
(machine_info, raw_arch_config) = (get_machine_info(), deepcopy(raw_arch_config))
all_infos = {'info': machine_info}
all_dataset_keys = []
... |
def load_state_dict_hf(model_name, device=None, dtype=None):
mapped_device = ('cpu' if (dtype not in [torch.float32, None]) else device)
resolved_archive_file = cached_file(model_name, WEIGHTS_NAME, _raise_exceptions_for_missing_entries=False)
return torch.load(resolved_archive_file, map_location=mapped_dev... |
class MemoryViewIndexNode(BufferIndexNode):
is_memview_index = True
is_buffer_access = False
warned_untyped_idx = False
def analyse_types(self, env, getting=True):
from . import MemoryView
self.is_pythran_mode = has_np_pythran(env)
indices = self.indices
(have_slices, ind... |
_function_api('triline_feature', [('F', 'Grid faeture', '[3, G, D]', True)])
def _query_on_triline(x, G, feature_size, min_=[(- 1), (- 1), (- 1)], max_=[1, 1, 1], use_ste=False, f_init=None, fix_parameters=False, rng=None):
f_init = (f_init if (f_init is not None) else I.NormalInitializer(0.001))
shape = [3, G,... |
def _process_deriv_spec(deriv):
if (deriv is not None):
try:
(ords, vals) = zip(*deriv)
except TypeError:
msg = 'Derivatives, `bc_type`, should be specified as a pair of iterables of pairs of (order, value).'
raise ValueError(msg)
else:
(ords, vals) = ... |
class SimpleReplayBuffer(ReplayBuffer):
def __init__(self, max_replay_buffer_size, observation_dim, action_dim, env_info_sizes):
self._observation_dim = observation_dim
self._action_dim = action_dim
self._max_replay_buffer_size = max_replay_buffer_size
self._observations = np.zeros((... |
def check_vit_in_transformers():
if (not has_VIT):
raise ImportError('transformers version >= 4.5.0 required for using modeling_vit') |
def write_output(elem: Dict[(str, Any)], output_dir: str):
filename = os.path.basename(elem['filepath'].replace('gs://', ''))
output_filepath = os.path.join(output_dir, filename)
start_secs = round(elem['audio_start_seconds'], 3)
end_secs = round(elem['audio_end_seconds'], 3)
start_end_str = make_st... |
def test_defs_always_cached(socket_disabled, isolate_modules):
modules_to_clear = [name for name in sys.modules if (name.split('.')[0] == 'pyhf')]
for module_name in modules_to_clear:
del sys.modules[module_name]
pyhf = importlib.import_module('pyhf')
spec = {'channels': [{'name': 'singlechannel... |
def remove_file_if_exists(file_name: str) -> None:
if os.path.exists(file_name):
os.remove(file_name)
else:
print('The file does not exist') |
def maximum_calibration_error(y_hat: Prediction, y: Tensor, n_bins: int=10) -> Tensor:
if ((y_hat.soft is None) or (y_hat.hard is None)):
return torch.as_tensor(float('nan'))
batch_size = y_hat.soft.size(0)
if (batch_size == 0):
return torch.as_tensor(float('nan'))
(acc_binned, conf_binn... |
class Function_stieltjes(GinacFunction):
def __init__(self):
GinacFunction.__init__(self, 'stieltjes', nargs=1, conversions=dict(mathematica='StieltjesGamma', sympy='stieltjes'), latex_name='\\gamma') |
def latent_map(fname, ofname, start_idx):
mat = loadmat(fname)
if ('latent' not in mat.keys()):
print('Skipping file without latents:', fname)
latent_all = mat['latent']
assert (latent_all.shape[0] == latent_all.size), ('Latent is not 1D for file: ' + fname)
latent_all = latent_all.reshape((... |
def test_checkpoint_name():
checkpoint = utils.checkpoint_name('saved_models', 'kk_oscar_forward_charlm.pt', None)
assert (os.path.split(checkpoint) == ('saved_models', 'kk_oscar_forward_charlm_checkpoint.pt'))
checkpoint = utils.checkpoint_name('saved_models', 'kk_oscar_forward_charlm', None)
assert (o... |
class PTBTokenizer():
def tokenize(self, captions_for_image):
cmd = ['java', '-cp', STANFORD_CORENLP_3_4_1_JAR, 'edu.stanford.nlp.process.PTBTokenizer', '-preserveLines', '-lowerCase']
final_tokenized_captions_for_image = {}
image_id = [k for (k, v) in captions_for_image.items() for _ in ran... |
def main():
args = parse_args()
root_path = args.root_path
out_dir = (args.out_dir if args.out_dir else root_path)
mmcv.mkdir_or_exist(out_dir)
img_dir = osp.join(root_path, 'imgs')
gt_dir = osp.join(root_path, 'annotations')
set_name = {}
for split in args.split_list:
set_name.u... |
(config_path='../../conf', config_name='lang_ann.yaml')
def main(cfg: DictConfig) -> None:
data_module = hydra.utils.instantiate(cfg.datamodule)
bert = hydra.utils.instantiate(cfg.model)
data_module.setup()
if cfg.training:
dataset = data_module.train_datasets
else:
dataset = data_mo... |
def validate(val_loader, net, criterion, optim, scheduler, curr_epoch, writer, curr_iter, optim_at=None, scheduler_at=None):
net.eval()
val_loss = AverageMeter()
iou_acc = 0
error_acc = 0
dump_images = []
for (val_idx, data) in enumerate(val_loader):
if args.no_pos_dataset:
(... |
def load_cmrc2018():
dataset_dict = load_dataset('cmrc2018')
print(dataset_dict)
dataset_dict = cast(DatasetDict, dataset_dict)
dataset_dict = dataset_dict.rename_columns({'question': 'text2', 'context': 'text1'})
dataset_dict = dataset_dict.map(add_label, batched=True, remove_columns=['id', 'answer... |
.parametrize('a, feat_idxs, expected', [(B, [0], []), (B, [0, 1], [[0, 1, 0, 1, 1, 0]]), (B, [0, 1, 2, 3, 4, 5], [[1, 0, 1, 0, 1, 0], [0, 1, 0, 1, 1, 0], [1, 0, 0, 1, 0, 1]])])
def test_expand_collection(a, feat_idxs, expected):
children = expand_collection(a, feat_idxs)
assert np.array_equal(np.array(children)... |
def column_Log(SUK, iota, U, prec=106):
R = RealField(prec)
return [R(SUK.number_field().abs_val(v, iota, prec)).log() for v in U] |
def bmat(*args, **kwargs):
with warnings.catch_warnings(record=True):
warnings.filterwarnings('ignore', '.*the matrix subclass is not the recommended way.*')
return np.bmat(*args, **kwargs) |
def standardize_class_weights(class_weight, output_names):
return standardize_sample_or_class_weights(class_weight, output_names, 'class_weight') |
def use_cpu_device():
with jax.default_device(jax.local_devices(backend='cpu')[0]):
(yield) |
_torch
_staging_test
class TrainerIntegrationWithHubTester(unittest.TestCase):
def setUpClass(cls):
cls._token = TOKEN
HfFolder.save_token(TOKEN)
def tearDownClass(cls):
for model in ['test-trainer', 'test-trainer-epoch', 'test-trainer-step']:
try:
delete_repo... |
def read_json_data(file_name):
with open(file_name) as f:
article_list = [json.loads(line) for line in f]
return article_list |
def startpoint_difference(pred, label):
x_distance = (pred[0][2] - label[0][2])
y_distance = (pred[0][3] - label[0][3])
distance = math.sqrt(((x_distance * x_distance) + (y_distance * y_distance)))
return distance |
class OpenAIGPTConfig(PretrainedConfig):
model_type = 'openai-gpt'
attribute_map = {'max_position_embeddings': 'n_positions', 'hidden_size': 'n_embd', 'num_attention_heads': 'n_head', 'num_hidden_layers': 'n_layer'}
def __init__(self, vocab_size=40478, n_positions=512, n_embd=768, n_layer=12, n_head=12, afn... |
def gen_while_gradient(op, g_output):
from caffe2.python.core import BlobReference
assert (op.type == 'While'), 'Expected While op'
assert (len(op.input) > 0), 'Expected at least one input in While op'
assert (len(op.output) == len(g_output)), 'Different number of gradient blobs and While op outputs'
... |
def getfortranname(rout):
try:
name = rout['f2pyenhancements']['fortranname']
if (name == ''):
raise KeyError
if (not name):
errmess(('Failed to use fortranname from %s\n' % rout['f2pyenhancements']))
raise KeyError
except KeyError:
name = rout... |
def _read_sequence_example(filename_queue, n_labels=50, n_samples=59049, n_segments=10):
reader = tf.TFRecordReader()
(_, serialized_example) = reader.read(filename_queue)
(context, sequence) = tf.parse_single_sequence_example(serialized_example, context_features={'raw_labels': tf.FixedLenFeature([], dtype=... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.