code stringlengths 101 5.91M |
|---|
def remove_symbols_and_diacritics(s: str, keep=''):
def replace_character(char):
if (char in keep):
return char
elif (char in ADDITIONAL_DIACRITICS):
return ADDITIONAL_DIACRITICS[char]
elif (unicodedata.category(char) == 'Mn'):
return ''
elif (unic... |
_tokenizers
class CodeGenTokenizationTest(TokenizerTesterMixin, unittest.TestCase):
tokenizer_class = CodeGenTokenizer
rust_tokenizer_class = CodeGenTokenizerFast
test_rust_tokenizer = True
from_pretrained_kwargs = {'add_prefix_space': True}
test_seq2seq = False
def setUp(self):
super().... |
class OptimWrapper():
def __init__(self, opt, wd, true_wd: bool=False, bn_wd: bool=True):
(self.opt, self.true_wd, self.bn_wd) = (opt, true_wd, bn_wd)
self.opt_keys = list(self.opt.param_groups[0].keys())
self.opt_keys.remove('params')
self.read_defaults()
self.wd = wd
de... |
def convert_xvector(base_model_name, hf_config, downstream_dict):
model = WavLMForXVector.from_pretrained(base_model_name, config=hf_config)
model.projector.weight.data = downstream_dict['connector.weight']
model.projector.bias.data = downstream_dict['connector.bias']
for (i, kernel_size) in enumerate(h... |
def load_all_image_paths_track_val(opt, phase):
image_dir = ((opt.ImagesRoot + phase) + '/')
inpainted_back_dir = ((opt.BackRoot + phase) + '/')
instance_gt_dir = ((opt.InstanceGTRoot + phase) + '/')
instance_mask_rcnn_dir = ((opt.Instance_maskrcnn + phase) + '/')
semantic_psp_dir = ((opt.SemanticRo... |
def getDataLoader(batch_size, num_of_questions, max_step):
handle = DataReader('dataset/assist2009/builder_train.csv', 'dataset/assist2009/builder_test.csv', max_step, num_of_questions)
dtrain = torch.tensor(handle.getTrainData().astype(float).tolist(), dtype=torch.float32)
dtest = torch.tensor(handle.getTe... |
class AvKeyframeVideoCompressor(VideoLoader):
def __init__(self, csv=None, video_dict=None, framerate=1, size=112, centercrop=False, max_num_frames=5, **kwargs):
super().__init__(csv, video_dict, framerate, size, centercrop)
self.max_num_frames = max_num_frames
def _get_video_dim(self, video_fn)... |
class MultiSumBlock(PlainNetBasicBlockClass):
def __init__(self, block_list, no_create=False, **kwargs):
super(MultiSumBlock, self).__init__(**kwargs)
self.block_list = block_list
if (not no_create):
self.module_list = nn.ModuleList(block_list)
self.in_channels = np.max([... |
def test_diskdf_method_inputAsQuantity_special():
from galpy.df import dehnendf, shudf
from galpy.util import conversion
(ro, vo) = (7.0, 230.0)
df = dehnendf(ro=ro, vo=vo)
dfnou = dehnendf()
dfs = shudf(ro=ro, vo=vo)
dfsnou = shudf()
assert (numpy.fabs((df((((0.6 * (vo ** 2.0)) * (units... |
def standard_retrieve(nbt, dim):
from ast import literal_eval
from phcpy.phcpy2c3 import py2c_numbtrop_standard_retrieve as load
(fail, strdata) = load(nbt, dim)
data = literal_eval(strdata)
wnd = [int(data[k]) for k in range(nbt)]
dirs = []
for i in range(nbt):
dirs.append([data[((n... |
class MUSTC(Dataset):
SPLITS = ['train', 'dev', 'tst-COMMON', 'tst-HE']
LANGUAGES = ['de', 'es', 'fr', 'it', 'nl', 'pt', 'ro', 'ru']
def __init__(self, root: str, lang: str, split: str) -> None:
assert ((split in self.SPLITS) and (lang in self.LANGUAGES))
_root = (((Path(root) / f'en-{lang}'... |
class CHMMArguments():
train_path: Optional[str] = field(default='', metadata={'help': 'training data name'})
valid_path: Optional[str] = field(default='', metadata={'help': 'development data name'})
test_path: Optional[str] = field(default='', metadata={'help': 'test data name'})
output_dir: Optional[s... |
class HtmlReport(EventSink):
folder_name = 'htmlreport'
def __init__(self, dataroot):
self.dataroot = dataroot
self.data = {}
os.makedirs(os.path.join(dataroot, self.folder_name), exist_ok=True)
def load_epochs_data(self, epochs, consts):
assert (not self.data)
for (i... |
_model_architecture(model_name='head_selection_s2t_transformer', arch_name='head_selection_s2t_transformer')
def base_architecture(args):
s2t_base_architecture(args)
args.encoder_attn_head_select = getattr(args, 'encoder_attn_head_select', False)
args.decoder_self_attn_head_select = getattr(args, 'decoder_s... |
def binary(o1, o2, step, op='NONE'):
if is_fixed(o1):
val = simplify(o1['z3']).as_long()
if ((op in ['MUL', 'AND', 'DIV', 'SDIV']) and (0 == val)):
return {'type': 'constant', 'step': step, 'z3': BitVecVal(0, 256)}
if ((op in ['XOR', 'ADD']) and (0 == val)):
return o2... |
def test_python_to_cpp_to_python_from_process():
assert (_run_in_process(_python_to_cpp_to_python) == 0) |
def _check_params(start, end, include_start, include_end):
if ((start is None) and (include_start is False)):
raise ValueError('include_start should be True given start=None')
if ((end is None) and (include_end is False)):
raise ValueError('include_end should be True given end=None')
if isin... |
class CrossEntropyLoss(torch.autograd.Function):
def forward(ctx, logits, labels, smoothing, lse_square_scale=0.0, ignored_index=(- 100), inplace_backward=False, process_group=None):
(n_rows, n_cols) = logits.shape
assert (labels.shape == (n_rows,))
world_size = (1 if (process_group is None)... |
def quaddobl_next_loop(hom, idx, sols, verbose=False):
from phcpy.solver import number_of_symbols
result = []
dim = (number_of_symbols(hom) - 1)
quaddobl_set_parameter_homotopy(hom, idx, verbose)
(idx, tval) = (0, 0.0)
fmt = 'pole step : %.3e, estimated distance : %.3e, Hessian step : %.3e'
... |
class AVATAR_OT_WearCloth(bpy.types.Operator):
bl_idname = 'avt.wear_cloth'
bl_label = 'Wear Cloth'
bl_description = 'Dress human with selected cloth'
def execute(self, context):
global avt_path
scn = context.scene
obj = context.active_object
iconname = bpy.context.scene.... |
_config
def gsn_side_fcn5s():
cfg = {'learner': {'model': 'GenericSidetuneNetwork', 'model_kwargs': {'side_class': 'FCN5', 'side_weights_path': None, 'side_kwargs': {'img_channels': 3, 'eval_only': False, 'normalize_outputs': False}}}} |
def _crop(image, offset_height, offset_width, crop_height, crop_width):
original_shape = tf.shape(image)
rank_assertion = tf.Assert(tf.equal(tf.rank(image), 3), ['Rank of image must be equal to 3.'])
cropped_shape = control_flow_ops.with_dependencies([rank_assertion], tf.stack([crop_height, crop_width, orig... |
(reraise=True)
def main_worker(rank, ngpus_per_node, config, config_manager, port):
save_dir = str(config['Trainer']['save_dir'])
logger.add(os.path.join('runs', save_dir, 'loguru.log'), level='TRACE', diagnose=True)
seed = config.get('RandomSeed', 10)
config_arch = deepcopy(config['Arch'])
model_ch... |
class FlaxAutoModelForSequenceClassification(_BaseAutoModelClass):
_model_mapping = FLAX_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING |
class Trim(BaseWaveformTransform):
supports_multichannel = True
def __init__(self, top_db: float=30.0, p: float=0.5):
super().__init__(p)
self.top_db = top_db
def apply(self, samples: NDArray[np.float32], sample_rate: int):
(samples, lens) = librosa.effects.trim(samples, top_db=self.... |
class BinaryFocalLoss(Loss):
def __init__(self, alpha=0.25, gamma=2.0):
super().__init__(name='binary_focal_loss')
self.alpha = alpha
self.gamma = gamma
def __call__(self, gt, pr):
return F.binary_focal_loss(gt, pr, alpha=self.alpha, gamma=self.gamma, **self.submodules) |
class MjrContextWrapper(object):
def __init__(self, wrapped, size_src=None):
self._wrapped = wrapped
self._size_src = size_src
def ptr(self):
return self._wrapped
def obj(self):
return self._wrapped.contents
def linewidth(self):
return self._wrapped.contents.linew... |
class MAE(ZooKerasCreator, JavaValue):
def __init__(self, bigdl_type='float'):
super(MAE, self).__init__(None, bigdl_type) |
def get_task(task_name):
module = importlib.import_module(f'.{task_name}', package=__package__)
CustomTask = getattr(module, 'CustomTask')
return CustomTask |
class TrainerMemoryTracker():
stages = {'__init__': 'init', 'train': 'train', '_inner_training_loop': 'train', 'evaluate': 'eval', 'predict': 'test'}
def __init__(self, skip_memory_metrics=False):
self.skip_memory_metrics = skip_memory_metrics
if (not is_psutil_available()):
self.ski... |
def unitwise_norm(x, norm_type=2.0):
if (x.ndim <= 1):
return x.norm(norm_type)
else:
return x.norm(norm_type, dim=tuple(range(1, x.ndim)), keepdim=True) |
class SHMArray(np.ndarray):
def __new__(cls, shape, dtype, shm_name=None, create=False):
shm = shared_memory.SharedMemory(create=create, name=shm_name, size=(np.prod(shape) * np.dtype(dtype).itemsize))
obj = super().__new__(cls, shape=shape, dtype=dtype, buffer=shm.buf)
obj.shm = shm
... |
def check_random_state(seed):
if ((seed is None) or (seed is numpy.random)):
return numpy.random.mtrand._rand
if isinstance(seed, (numbers.Integral, numpy.integer)):
return numpy.random.RandomState(seed)
if isinstance(seed, numpy.random.RandomState):
return seed
raise ValueError(... |
class FCN4Reshaped(FCN4):
def forward(self, x, cache={}, time_idx: int=(- 1)):
x = super().forward(x, time_idx)
x = F.avg_pool2d(x, x.size()[3]).view(x.shape[0], 64)
return x |
def get_imdb(name):
if (not (name in __sets)):
raise KeyError('Unknown dataset: {}'.format(name))
return __sets[name]() |
def get_conf(py_conf=None):
logger.info(f'Entering get_conf, original py_conf is {py_conf}')
logger.info(('current working director is %s' % os.getcwd()))
attribute_class = py_conf
if py_conf:
if isinstance(py_conf, str):
attribute_class = reflect_util.get_class(py_conf)
properti... |
def test_filepath_error():
wide = Wide(np.unique(X_wide).shape[0], 1)
deeptabular = TabMlp(mlp_hidden_dims=[16, 4], column_idx=column_idx, cat_embed_input=embed_input, continuous_cols=colnames[(- 5):])
model = WideDeep(wide=wide, deeptabular=deeptabular)
with pytest.raises(ValueError):
trainer =... |
def main():
parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments))
if ((len(sys.argv) == 2) and sys.argv[1].endswith('.json')):
(model_args, data_args, training_args) = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]))
else:
(model_args, data_args,... |
def _resnet(arch: str, block: Type[Union[(BasicBlock, Bottleneck)]], layers: List[int], pretrained: bool, progress: bool, **kwargs: Any) -> ResNet:
model = ResNet(block, layers, **kwargs)
if pretrained:
state_dict = load_state_dict_from_url(model_urls[arch], progress=progress)
model.load_state_d... |
class MetaActionAngle(type):
def __new__(meta, name, bases, attrs):
for key in copy.copy(attrs):
if (key[0] == '_'):
skey = copy.copy(key[1:])
if (skey == 'evaluate'):
skey = '__call__'
for base in bases:
ori... |
class Evaluation():
def __init__(self, config, logger, experiment_id):
self.config = config
self.logger = logger
self.device = torch.device(self.config.training.device)
self.experiment_id = experiment_id
self.path_to_model = os.path.join(self.config.env.experiments_dir, self.... |
class FilterResponseNormNd(nn.Module):
def __init__(self, ndim, num_features, eps=1e-06, learnable_eps=False):
assert (ndim in [3, 4, 5]), 'FilterResponseNorm only supports 3d, 4d or 5d inputs.'
super(FilterResponseNormNd, self).__init__()
shape = ((1, num_features) + ((1,) * (ndim - 2)))
... |
class TVMType(ctypes.Structure):
_fields_ = [('type_code', ctypes.c_uint8), ('bits', ctypes.c_uint8), ('lanes', ctypes.c_uint16)]
CODE2STR = {0: 'int', 1: 'uint', 2: 'float', 4: 'handle'}
def __init__(self, type_str):
super(TVMType, self).__init__()
if isinstance(type_str, np.dtype):
... |
class priorityDictionary(dict):
def __init__(self):
self.__heap = []
dict.__init__(self)
def smallest(self):
if (len(self) == 0):
raise IndexError('smallest of empty priorityDictionary')
heap = self.__heap
while ((heap[0][1] not in self) or (self[heap[0][1]] !... |
class AtariHeadDataloader():
def __init__(self, directory, batch_size=32, stack=3, controls=18, size=(84, 84), percentile=None, top_n=None, augment=False, preload=False, merge=False, dqn=False, action_delay=0, print_stats=False):
self.batch_size = batch_size
self.stack = stack
self.controls ... |
def get_teacher_name(model_path):
segments = model_path.split('/')[(- 2)].split('_')
if (segments[0] != 'wrn'):
return segments[0]
else:
return ((((segments[0] + '_') + segments[1]) + '_') + segments[2]) |
class BertSplade(BertForMaskedLM):
def forward(self, input_ids, attention_mask, token_type_ids=None, position_ids=None, return_dict=False):
outputs = super().forward(input_ids=input_ids, attention_mask=attention_mask, token_type_ids=token_type_ids, position_ids=position_ids, return_dict=True)
(vocab... |
def total_params():
total_parameters = 0
for variable in tf.trainable_variables():
shape = variable.get_shape()
variable_parametes = 1
for dim in shape:
variable_parametes *= dim.value
total_parameters += variable_parametes
print('Total number of trainable paramet... |
class img_dataset(Dataset):
def __init__(self, get_visual_path: Callable[([str], dict)], get_text_annotation: Callable[([str], dict)], get_all_model_ids: Callable[([], dict)]):
super().__init__()
self.get_visual_path = get_visual_path
self.get_text_annotation = get_text_annotation
se... |
class conv2D(Layer):
def __init__(self, size, outchn, x=None, name=None, stride=1, pad='SAME', usebias=True, values=None, kernel_data=None, bias_data=None, dilation_rate=1, weight_norm=False):
self.x = x
self.size = size
self.outchn = outchn
self.name = name
self.stride = str... |
_searchspace('discrete')
class DiscreteSearchSpace(BaseSearchSpace):
def __init__(self, bound=None, interval=None, value=None, type=None):
if (bound and (interval is None)):
if (isinstance(bound[0], int) and isinstance(bound[1], int)):
interval = 1
else:
... |
class NONLocalBlock2D(_NonLocalBlockND):
def __init__(self, in_channels, inter_channels=None, sub_sample=True, bn_layer=True):
super(NONLocalBlock2D, self).__init__(in_channels, inter_channels=inter_channels, dimension=2, sub_sample=sub_sample, bn_layer=bn_layer) |
class OnnxSeq2SeqConfigWithPast(OnnxConfigWithPast):
def outputs(self) -> Mapping[(str, Mapping[(int, str)])]:
common_outputs = super(OnnxConfigWithPast, self).outputs
for (name, axes_names) in common_outputs.items():
sequence_name = ('encoder_sequence' if ('encoder' in name) else 'decod... |
def main():
args = parse_args()
if (not os.path.exists(args.result_root)):
os.mkdir(args.result_root)
cfg = Config.fromfile(args.config)
print('load config.')
dataset = build_dataset(cfg.data.test)
print(f'Dataset: {len(dataset)}')
print('cfg.data.test', cfg.data.test)
if (args.l... |
def map_roberta(mapping, vocab):
inverse_vocab = {str(v): k for (k, v) in vocab.items()}
EXTRA_TOKENS = {'<s>': 0, '<pad>': 1, '</s>': 2, '<unk>': 3}
offset = len(EXTRA_TOKENS)
output_vocab = EXTRA_TOKENS
for (word_id, position) in mapping.items():
if (word_id in inverse_vocab):
... |
def read_into_df(fileName, delimiter=';', header='infer'):
return pd.read_csv(fileName, delimiter=delimiter, header=header) |
def rand_brightness(x):
x = (x + (torch.rand(x.size(0), 1, 1, 1, dtype=x.dtype, device=x.device) - 0.5))
return x |
def run_xacro_in_file(filename):
assert (filename != '')
assert subprocess.check_output(['xacro', '--inorder', 'tests/{}'.format(filename)], cwd=path) |
def test_decoder():
config = anyconfig.load('/home/luning/dev/projects/master-tf/configs/master.yaml')
config = easydict.EasyDict(config)
image = tf.random.normal([10, 48, 160, 3])
model = MasterModel(config.model, 10, (48, 160))
ys = model.decode(image, padding=tf.constant(True))
decoded_tensor... |
class MLMAccuracyWVC(EvalMetric):
def __init__(self, allreduce=False, num_replicas=1):
super(MLMAccuracyWVC, self).__init__('MLMAccWVC', allreduce, num_replicas)
def update(self, outputs):
with torch.no_grad():
logits = outputs['mlm_logits_wvc']
label = outputs['mlm_label... |
class LambdaLayer(nn.Module):
def __init__(self, lambd):
super(LambdaLayer, self).__init__()
self.lambd = lambd
def forward(self, x):
return self.lambd(x) |
def run(method, x_unvec, y, idx_feat_dict, num_feature, max_num_feature, num_class, max_num_sample, feature_selection, k_idx, k, num_search, perm_indices):
print(('-' * 72))
print('Partition k = {}'.format(k_idx))
(x_train_unvec, y_train, x_val_unvec, y_val, _, _) = emr.get_k_fold_partition(x_unvec, y, k_id... |
class LatentLayersKLLoss(_Loss):
def __init__(self, args):
super().__init__()
self.args = args
def forward(self, layer_samples, lang_idx, update_num, sample_size):
prior = self.args.prior
samples = layer_samples[lang_idx]
eps = 1e-07
if (prior == 'uniform'):
... |
def generateLine2(data):
global linenumber, tframe
if ((linenumber % 2) == 1):
bgcolor = '#e5e5e5'
else:
bgcolor = '#ffffff'
frame = Frame(tframe, bg=bgcolor)
assert (len(data) == 5)
Label(frame, text=data[0], font=(None, 10), bg=bgcolor, width=15, anchor=CENTER).grid(row=0, colu... |
def get_kenlm_processor(model_path, path_lm=None):
path_tokenizer = model_path
if Path(model_path).is_dir():
processor = AutoProcessor.from_pretrained(path_tokenizer)
model = AutoModelForCTC.from_pretrained(model_path)
else:
print(f'Error. Models were not found in {model_path}')
... |
def make_summary(tag, value):
return tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)]) |
class Data():
def __init__(self, data_dir='data/FB15k-237', reverse=False):
self.train_data = self.load_data(data_dir, 'train', reverse=reverse)
self.valid_data = self.load_data(data_dir, 'valid', reverse=reverse)
self.test_data = self.load_data(data_dir, 'test', reverse=reverse)
sel... |
def load_model_result(model, data_dir):
files = os.listdir(((data_dir + model) + '/result/'))
result = {}
for file in files:
city = file.split('_')[0].strip()
result[city] = load_city_result(city, model, data_dir)
return result |
def random_partial_box(random_state):
def generate():
x1 = random_state.uniform(0, 0.5)
(x2, y2) = random_state.uniform(0.5, 1, size=2)
side = (x2 - x1)
if (not (0.5 < side < y2)):
return None
return np.array([x1, (y2 - side), side, side])
while True:
... |
def is_compatible_episode(s, t, sim, near_dist, far_dist, geodesic_to_euclid_ratio):
euclid_dist = np.power(np.power((np.array(s) - np.array(t)), 2).sum(0), 0.5)
if (np.abs((s[1] - t[1])) > 0.5):
return (False, 0)
d_separation = sim.geodesic_distance(s, [t])
if (d_separation == np.inf):
... |
def main(args):
token_classification_model = args.input_model
path_to_files = args.input_files.rstrip().split(' ')
test_set_names = args.test_names.rstrip().split(' ')
output_folder = args.output_folder
assert (len(path_to_files) == len(test_set_names)), 'number of test files and their names differ'... |
class BlenderbotForConditionalGeneration(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class LogFileWriter(ContextDecorator, ContextMethodDecorator):
def __init__(self, experiment):
self.experiment = experiment
def log_writer_decorator(instance, original_method, original_args, original_kwargs):
result = original_method(instance, *original_args, **original_kwargs)
... |
class ResidualLayer(torch.nn.Module):
def __init__(self, units: int, nLayers: int=2, activation=None, name=None):
super().__init__()
self.dense_mlp = torch.nn.Sequential(*[Dense(units, units, activation=activation, bias=False) for i in range(nLayers)])
self.inv_sqrt_2 = (1 / (2.0 ** 0.5))
... |
def download_url(url, dst_file_path, chunk_size=8192, progress_hook=_progress_bar):
response = urlopen(url)
total_size = response.info().getheader('Content-Length').strip()
total_size = int(total_size)
bytes_so_far = 0
with open(dst_file_path, 'wb') as f:
while 1:
chunk = respons... |
def main(params):
for (k, v) in zip(params.keys(), params.values()):
assert (v is not None), f'Value for {k} is None'
metadata_schema = schema_from_dict(params)
base_directory = params['out_dir']
store = Store(base_directory)
def make_err_redirector(stream_name):
tee = Tee(os.path.jo... |
class MnliProcessor(DataProcessor):
def get_train_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'train.tsv')), 'train')
def get_dev_examples(self, data_dir):
return self._create_examples(self._read_tsv(os.path.join(data_dir, 'dev_matched.tsv')), 'de... |
def parse_args_and_arch(parser, input_args=None, parse_known=False):
(args, _) = parser.parse_known_args(input_args)
if hasattr(args, 'arch'):
model_specific_group = parser.add_argument_group('Model-specific configuration', argument_default=argparse.SUPPRESS)
ARCH_MODEL_REGISTRY[args.arch].add_a... |
def start(fn_name, use_stack=True):
global _running_timer
if use_stack:
if (_running_timer is not None):
stop(_running_timer, use_stack=False)
_timer_stack.append(_running_timer)
start(fn_name, use_stack=False)
_running_timer = fn_name
else:
_start_tim... |
def cifarnet(nfilters, avgpool=None, nclasses=10, nmasks=32, level=0.1, filter_size=3, first_filter_size=0, pool_type=None, input_size=None, scale_noise=1, act='relu', use_act=True, dropout=0.5, unique_masks=False, debug=False, noise_type='uniform', train_masks=False, mix_maps=None):
return CifarNet(nfilters=nfilte... |
class MYNET(Net):
def __init__(self, args, mode=None):
super().__init__(args, mode)
hdim = self.num_features
self.slf_attn = MultiHeadAttention(1, hdim, hdim, hdim, dropout=0.5)
def forward(self, input):
if (self.mode == 'encoder'):
input = self.encode(input)
... |
class DatasetPASCAL(Dataset):
def __init__(self, datapath, fold, transform, split, shot, use_original_imgsize):
self.split = ('val' if (split in ['val', 'test']) else 'trn')
self.fold = fold
self.nfolds = 4
self.nclass = 20
self.benchmark = 'pascal'
self.shot = shot
... |
def random_crop():
data = np.arange((3 * 5)).reshape(3, 5)
print(data)
m = RandomCrop(size=(3, 3), p=1.0)
print(m)
res = m(data)
print(res) |
def copy_parameter_from_resnet(model, resnet_dict):
cur_state_dict = model.state_dict()
for (name, param) in list(resnet_dict.items())[0:None]:
if (name not in cur_state_dict):
continue
if isinstance(param, Parameter):
param = param.data
try:
cur_state... |
def run(model, data_iter, data_iter2, data_iter3, data_iter4, train_mode):
(model.train() if train_mode else model.eval())
losses = []
losses_der1 = []
losses_der2 = []
losses_docking = []
losses_screening = []
if args.with_uncertainty:
losses_var = []
save_pred = {}
save_tru... |
def sol_norm(summary_pdf, name_string, abundances, cube, elements_to_trace, element_names, sol_table, number_of_models_overplotted, produce_mock_data, use_mock_data, error_inflation):
elements_to_trace = element_names
if ('C+N' in element_names):
new_array = np.log10((np.power(10, abundances['C']) + np.... |
_builder('vg_vqa')
class VGVQABuilder(BaseDatasetBuilder):
train_dataset_cls = VGVQADataset
DATASET_CONFIG_DICT = {'default': 'configs/datasets/vg/defaults_vqa.yaml'} |
def split_by_ratio(num_v: int, v_label: Union[(list, torch.Tensor, np.ndarray)], train_ratio: float, val_ratio: Optional[float]=None, test_ratio: Optional[float]=None):
if isinstance(v_label, list):
v_label = np.array(v_label)
if isinstance(v_label, torch.Tensor):
v_label = v_label.detach().cpu(... |
def _add_to_tfrecord(dataset_dir, name, tfrecord_writer):
(image_data, shape, bboxes, labels, labels_text, difficult, truncated) = _process_image(dataset_dir, name)
example = _convert_to_example(image_data, labels, labels_text, bboxes, shape, difficult, truncated)
tfrecord_writer.write(example.SerializeToSt... |
class TestCluster(unittest.TestCase):
def setUp(self):
node_lst = [Node('node1', 'localhost', 2, 4), Node('node2', 'localhost', 2, 4)]
self.cluster = Cluster(node_lst, db_path=db_path)
self.task = Task(task_id='1', arguments=['arg1', 'arg2'], workers=2, status='pending', script_url=' optimiz... |
def concat_hunks(file_patches: list[AvgFilePatch], delim: str='') -> str:
return delim.join((cast(str, hunk_patch.result.hunk) for file_patch in file_patches for hunk_patch in file_patch.hunks)) |
class SubPolicy(object):
def __init__(self, p1, operation1, magnitude_idx1, p2, operation2, magnitude_idx2, fillcolor=(128, 128, 128), magnitude_factor=1):
ranges = {'shearX': np.linspace(0, 0.3, 10), 'shearY': np.linspace(0, 0.3, 10), 'translateX': np.linspace(0, (150 / 331), 10), 'translateY': np.linspace... |
class ChatCompletionRequest(BaseModel):
model: str
messages: Union[(str, List[Dict[(str, str)]])]
temperature: Optional[float] = 0.7
top_p: Optional[float] = 1.0
n: Optional[int] = 1
max_tokens: Optional[int] = None
stop: Optional[Union[(str, List[str])]] = Field(default_factory=list)
st... |
def read_annotation_file(config, filename, doc):
items = []
if (len(glob.glob(filename)) == 1):
for line in open(filename):
fields = line.strip().split()
spans = get_spans(line.split('-')[0], doc, config)
labels = get_labels('-'.join(line.split('-')[1:]), config)
... |
class WebKB(InMemoryDataset):
url = '
def __init__(self, root, name, transform=None, pre_transform=None):
self.name = name.lower()
assert (self.name in ['cornell', 'texas', 'washington', 'wisconsin'])
super(WebKB, self).__init__(root, transform, pre_transform)
(self.data, self.sl... |
def get_filenames(dir, cifar_classnum):
assert ((cifar_classnum == 10) or (cifar_classnum == 100))
if (cifar_classnum == 10):
filenames = [os.path.join(dir, 'cifar-10-batches-py', ('data_batch_%d' % i)) for i in range(1, 6)]
filenames.append(os.path.join(dir, 'cifar-10-batches-py', 'test_batch')... |
_model
def regnety_160(pretrained=False, **kwargs):
return _regnet('regnety_160', pretrained, **kwargs) |
class LZ09_F6(LZ09):
def __init__(self, number_of_variables=10):
super(LZ09_F6, self).__init__(number_of_variables, dtype=1, ltype=32, ptype=31)
self.obj_directions = [self.MINIMIZE, self.MINIMIZE, self.MINIMIZE]
self.obj_labels = ['f(x)', 'f(y)', 'f(z)']
def number_of_objectives(self) -... |
def time_tensorflow_run(session, target, info_string):
num_steps_burn_in = 10
total_duration = 0.0
total_duration_squared = 0.0
for i in range((FLAGS.num_batches + num_steps_burn_in)):
start_time = time.time()
_ = session.run(target)
duration = (time.time() - start_time)
... |
def read_cameras_binary(path_to_model_file):
cameras = {}
with open(path_to_model_file, 'rb') as fid:
num_cameras = read_next_bytes(fid, 8, 'Q')[0]
for _ in range(num_cameras):
camera_properties = read_next_bytes(fid, num_bytes=24, format_char_sequence='iiQQ')
camera_id =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.