code stringlengths 101 5.91M |
|---|
def log_graph(graph, outdir, filename, identify_self=False, nodecolor='tag', fig_size=(4, 3), dpi=300, label_node_feat=True, edge_vmax=None, args=None, eps=1e-06):
if (len(graph.edges) == 0):
return
import matplotlib.pyplot as plt
plt.switch_backend('agg')
cmap = plt.get_cmap('tab20')
plt.sw... |
class DQNAgent():
def __init__(self, env, seed=None, lr=0.001, training_steps=20000, batch_size=32, replay_size=10000, final_epsilon=0.05, exploration_steps=10000, gamma=0.99, hidden_sizes=[64, 64], target_update_freq=1000, verbose=True, **kwargs):
assert env.flat_actions
self.verbose = verbose
... |
class Add(Layer):
def __init__(self, input_size, bigdl_type='float'):
super(Add, self).__init__(None, bigdl_type, input_size)
def set_init_method(self, weight_init_method=None, bias_init_method=None):
callBigDlFunc(self.bigdl_type, 'setInitMethod', self.value, weight_init_method, bias_init_metho... |
class ConcolicGen(BaseGen):
def __init__(self, opset, seed=None, init_fp=False, **kwargs):
super().__init__(opset, seed, **kwargs)
if (seed is not None):
set_z3_state(seed)
self.insert_init_ph_node(self.make_random_concrete_placeholder(self.random_rank(), dtype=(DType.float32 if ... |
class Server():
def __init__(self, client_models):
self.client_models = client_models
self.models = [client_model.get_params() for client_model in client_models]
self.num_groups = len(client_models)
self.selected_clients = []
self.updates = []
self.updates_group_infos... |
def train(args, model, device, train_loader, optimizer, epoch, logger):
model.train()
for (batch_idx, (data, target)) in enumerate(train_loader):
start = time()
(data, target) = (data.to(device), target.to(device))
model_fn = (lambda : model(data))
loss_fn = (lambda pred: F.cross... |
class MobileNetV2Config(PretrainedConfig):
model_type = 'mobilenet_v2'
def __init__(self, num_channels=3, image_size=224, depth_multiplier=1.0, depth_divisible_by=8, min_depth=8, expand_ratio=6, output_stride=32, first_layer_is_expansion=True, finegrained_output=True, hidden_act='relu6', tf_padding=True, classi... |
class AttModel(att_model.AttModel):
def make_model(self):
mask_params = {'mask_type': self.config.prune_type, 'mask_init_value': self.config.prune_supermask_init}
self.embed = nn.Sequential(MaskedEmbedding(self.vocab_size, self.input_encoding_size, **mask_params), nn.ReLU(), nn.Dropout(self.drop_pro... |
def splitEdgePunct(input):
input = EdgePunctLeft.sub('\\1\\2 \\3', input)
input = EdgePunctRight.sub('\\1 \\2\\3', input)
return input |
class SilverArrow(BaseBow):
def __init__(self):
super().__init__('silver arrow', weight=1, damage=D.Dice.from_str('d6'), material=M.Silver, hit=0) |
class Auxiliary_Rate(object):
def __init__(self, sentence_objs):
self.sentence_objs = sentence_objs
def handle(self):
(tot_num_advs, tot_num_words) = (0, 0)
for so in self.sentence_objs:
tot_num_advs += so.pos_tag_counter.get_pos_tag_count(AUXILIARY)
tot_num_words... |
def run_and_parse_first_match(run_lambda, command, regex):
(rc, out, _) = run_lambda(command)
if (rc != 0):
return None
match = re.search(regex, out)
if (match is None):
return None
return match.group(1) |
def min_max_scaler(X: torch.Tensor, ft_min: float, ft_max: float) -> torch.Tensor:
assert (ft_min < ft_max), 'The minimum value of the feature should be less than the maximum value.'
(X_min, X_max) = (X.min().item(), X.max().item())
X_range = (X_max - X_min)
scale_ = ((ft_max - ft_min) / X_range)
mi... |
class Case():
def __init__(self, url, raw_data):
self.url = url
self.raw_data = raw_data
self.data = None
def extract_data(self):
return self.to_standard(self.raw_data)
def get_data(self):
if (self.data is None):
self.data = self.extract_data()
ret... |
def printHelp():
print('{} [OPTIONS] inputJson outputImg'.format(os.path.basename(sys.argv[0])))
print('')
print(' Reads labels as polygons in JSON format and converts them to instance images,')
print(' where each pixel has an ID that represents the ground truth class and the')
print(' individual in... |
def test_nl_head():
head = NLHead(in_channels=8, channels=4, num_classes=19)
assert (len(head.convs) == 2)
assert hasattr(head, 'nl_block')
inputs = [torch.randn(1, 8, 23, 23)]
if torch.cuda.is_available():
(head, inputs) = to_cuda(head, inputs)
outputs = head(inputs)
assert (outputs... |
class Refiner(nn.Module):
def __init__(self, args):
super().__init__()
self.rlayer1 = torch.nn.Sequential(torch.nn.Conv3d(1, 32, kernel_size=4, padding=(2, 2, 2)), torch.nn.BatchNorm3d(32), torch.nn.LeakyReLU(0.2), torch.nn.MaxPool3d(kernel_size=2))
self.rlayer2 = torch.nn.Sequential(torch.n... |
class LTRTrainer(BaseTrainer):
def __init__(self, actor, loaders, optimizer, settings, lr_scheduler=None, use_amp=False):
super().__init__(actor, loaders, optimizer, settings, lr_scheduler)
self._set_default_settings()
self.stats = OrderedDict({loader.name: None for loader in self.loaders})
... |
def beit_forward_features(self, x):
resolution = x.shape[2:]
x = self.patch_embed(x)
x = torch.cat((self.cls_token.expand(x.shape[0], (- 1), (- 1)), x), dim=1)
if (self.pos_embed is not None):
x = (x + self.pos_embed)
x = self.pos_drop(x)
rel_pos_bias = (self.rel_pos_bias() if (self.rel_... |
class QueryNERProcessor(object):
def get_train_examples(self, data_dir):
data = read_mrc_ner_examples(os.path.join(data_dir, 'mrc-ner.train'))
return data
def get_dev_examples(self, data_dir):
return read_mrc_ner_examples(os.path.join(data_dir, 'mrc-ner.dev'))
def get_test_examples(s... |
def deterministic_cdf_oracle(observed_x, gamma):
w = torch.zeros(observed_x.shape[0], dtype=torch.float)
for i in range(observed_x.shape[0]):
w[i] = deterministic_one(observed_x[i], gamma)
return w |
def contLoss(y_true, y_pred):
loss = betweenLoss(y_true, y_pred)
loss += withinLoss(y_true, y_pred)
return loss |
class _ExpensivePotentials():
def __init__(self):
self._mcmillan17 = None
self._cautun20 = None
self._irrgang13i = None
self._irrgang13ii = None
self._irrgang13iii = None
self._dehnenbinney98i = None
self._dehnenbinney98ii = None
self._dehnenbinney98ii... |
class ConvEL():
def __init__(self, base_url='.', wiki_version='wiki_2019', ed_model=None, user_config=None, threshold=0, ner_model='bert_conv-td'):
self.threshold = threshold
self.wiki_version = wiki_version
self.base_url = base_url
self.file_pretrained = str((Path(base_url) / ner_mo... |
def resnet_main(flags_obj, model_function, input_function, dataset_name, shape=None):
print('RESNET MAIN')
model_helpers.apply_clean(flags.FLAGS)
if flags_obj.tf_gpu_thread_mode:
override_flags_and_set_envars_for_gpu_thread_pool(flags_obj)
session_config = tf.ConfigProto(allow_soft_placement=Tru... |
class DataSet(aicnn.DataSet):
def __init__(self, X, y, nb_classes, n_channels=3, scaling=True, test_size=0.2, random_state=0):
self.n_channels = n_channels
super().__init__(X, y, nb_classes, scaling=scaling, test_size=test_size, random_state=random_state)
def add_channels(self):
n_channe... |
def prepare_model(input_model, output_model):
batch_size = 1
model = torchvision.models.resnet50(pretrained=True)
x = torch.randn(batch_size, 3, 224, 224, requires_grad=True)
torch.onnx.export(model, x, output_model, export_params=True, opset_version=14, do_constant_folding=True, input_names=['input'], ... |
class Parameters(ParamaterNotValid):
from .system import includeSystem
from .experiment import includeExperiment
from .derived import computeDerived
def __init__(self, includeDerived=True, update=None):
self.includeSystem()
self.includeExperiment()
if (update is not None):
... |
class Discriminator(nn.Module):
def __init__(self, args, gan_type='GAN'):
super(Discriminator, self).__init__()
in_channels = 3
out_channels = 64
depth = 7
bn = True
act = nn.LeakyReLU(negative_slope=0.2, inplace=True)
m_features = [common.BasicBlock(args.n_co... |
def parse_tuning_log(line, url_dict):
result = line.split(';')
(OS, Platform, Framework, Version, Model, Strategy, Tune_time, Tuning_trials, URL, __) = result
file_name = f'{Framework}-{Model}-tune.log'
download_url = url_dict.get(f'{Framework}_{Model}')
download_url = f'{download_url}{file_name}'
... |
def pysptk_featurize(audiofile):
labels = list()
features = list()
(fs, x) = wavfile.read(audiofile)
f0_swipe = pysptk.swipe(x.astype(np.float64), fs=fs, hopsize=80, min=60, max=200, otype='f0')
features = (features + stats(f0_swipe))
labels = stats_labels('f0_swipe', labels)
f0_rapt = pyspt... |
def test_intree_extensions_package_dir(monkeypatch, tmpdir):
monkeypatch.syspath_prepend(MAIN_DIR)
from pybind11.setup_helpers import intree_extensions
monkeypatch.chdir(tmpdir)
root = (tmpdir / 'src')
root.ensure_dir()
subdir = (root / 'dir')
subdir.ensure_dir()
src = (subdir / 'ext.cpp... |
def test_sequence():
cstats = ConstructorStats.get(m.Sequence)
s = m.Sequence(5)
assert (cstats.values() == ['of size', '5'])
assert ('Sequence' in repr(s))
assert (len(s) == 5)
assert ((s[0] == 0) and (s[3] == 0))
assert (12.34 not in s)
(s[0], s[3]) = (12.34, 56.78)
assert (12.34 i... |
def test_funcall_kwarg_3():
run_cell('\n def f(x):\n return 2 * x + 8\n ')
run_cell('x = 7')
run_cell('y = f(x=x)')
run_cell('x = 8')
run_cell('logging.info(y)')
assert_detected('`y` depends on stale `x`') |
def is_protobuf_available():
if (importlib.util.find_spec('google') is None):
return False
return (importlib.util.find_spec('google.protobuf') is not None) |
def descnext(desc):
global next_description
if ((not default_verbosity) or (tqdm is None)):
return
next_description = desc |
def tolerance_infsolendgame_set(tol):
from phcpy.phcpy2c3 import py2c_set_value_of_continuation_parameter as set
return set(34, tol) |
def test_Gskew(white_noise):
a = FeatureSpace(featureList=['Gskew'])
a = a.calculateFeature(white_noise)
assert ((a.result(method='array') >= (- 0.2)) and (a.result(method='array') <= 0.2)) |
def build_single_model_ui(models):
notice_markdown = '\n<div class="title">\n<div style="\n color: #fff;\n">Large Language Model <p style="\n font-size: 0.8rem;\n">Future Gen Intel Xeon (codenamed Granite Rapids) with Intel AMX</p></div>\n</div>\n'
learn_more_markdown = '\n<div class="footer"><p>Powered b... |
class TaxiEnv(discrete.DiscreteEnv):
metadata = {'render.modes': ['human', 'ansi']}
def __init__(self):
self.desc = np.asarray(MAP, dtype='c')
self.locs = locs = [(0, 0), (0, 4), (4, 0), (4, 3)]
num_states = 500
num_rows = 5
num_columns = 5
max_row = (num_rows - 1... |
()
def sample_run():
exp = {'name': 'test_exp', 'sources': [], 'doc': '', 'base_dir': '/tmp'}
host = {'hostname': 'test_host', 'cpu_count': 1, 'python_version': '3.4'}
config = {'config': 'True', 'foo': 'bar', 'answer': 42}
command = 'run'
meta_info = {'comment': 'test run'}
return {'_id': 'FEDC... |
class EpisodeLoggerWrapper(AbstractTrainerWrapper):
def __init__(self, logging_period=10, validation_episodes=100, validation_period=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self._log_t = 0
self.logging_period = logging_period
self.validation_period = validation_peri... |
def _image_tensor_input_placeholder():
input_tensor = tf.placeholder(dtype=tf.uint8, shape=(None, None, None, 3), name='image_tensor')
return (input_tensor, input_tensor) |
def parse():
args = parser.parse_args()
parameters = params.Params(model=args.model, data=args.data, num_epochs=args.num_epochs, num_hops=args.num_hops, diffusion_threshold=args.diffusion_threshold, learning_rate=args.learning_rate, update_fn=args.optimizer, num_nodes=run.metadata[args.data]['num_nodes'], num_f... |
def load_model_and_checkpoint_files(folder, folds=None, mixed_precision=None, checkpoint_name='model_best'):
if isinstance(folds, str):
folds = [join(folder, 'all')]
assert isdir(folds[0]), ('no output folder for fold %s found' % folds)
elif isinstance(folds, (list, tuple)):
if ((len(fol... |
def dictionary_walk(dictionary):
for (key, value) in dictionary.items():
if isinstance(value, dict):
(yield from dictionary_walk(value))
else:
(yield (key, value)) |
def dynp(model, data, params):
ttf = []
for i in data.keys():
signal = StandardScaler().fit_transform(data[i].values)
algo = rpt.Dynp(model=model, params=params, jump=1).fit(signal)
my_bkps = algo.predict(n_bkps=1)
ttf.append((my_bkps[0] - 160))
return pd.DataFrame({((model +... |
class BaseDataset(object):
def get_imagedata_info(self, data):
(pids, cams) = ([], [])
for (_, pid, camid) in data:
pids += [pid]
cams += [camid]
pids = set(pids)
cams = set(cams)
num_pids = len(pids)
num_cams = len(cams)
num_imgs = len... |
def pad(pad_type, padding):
pad_type = pad_type.lower()
if (padding == 0):
return None
if (pad_type == 'reflect'):
layer = nn.ReflectionPad2d(padding)
elif (pad_type == 'replicate'):
layer = nn.ReplicationPad2d(padding)
else:
raise NotImplementedError('padding layer [... |
def get_best_trajectory_within_cluster(clustered_seqs, tracklets_info, time, norm_distance):
ends = []
covers = []
visual_similarity = []
for tracklet_seq in clustered_seqs:
total_gap = 0
distance = []
for (i, t_id) in enumerate(tracklet_seq):
total_gap += (tracklets_... |
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-data_train', type=str, default='')
parser.add_argument('-data_dev', required=True)
parser.add_argument('-data_test', type=str, default='')
parser.add_argument('-vocab', required=True)
parser.add_argument('-epoch', type=int, def... |
class AsymWeightLoss(nn.Module):
def __init__(self, underestimation_penalty=1, L1=False):
super().__init__()
invalidInputError((underestimation_penalty > 0), 'underestimation_penalty should be larger than 0')
self.L1 = L1
self.underestimation_penalty = underestimation_penalty
def... |
def get_game_envs():
_game_envs = defaultdict(set)
for env in gym.envs.registry.all():
try:
env_type = env.entry_point.split(':')[0].split('.')[(- 1)]
_game_envs[env_type].add(env.id)
except:
pass
return _game_envs |
class Res16UNetTemporalIN34(Res16UNetTemporal34):
NORM_TYPE = NormType.SPARSE_INSTANCE_NORM
BLOCK = BasicBlockIN |
class GraphGRUCell(HybridBlock):
def __init__(self, aggregator_args, aggregation_type='all', typ='rnn', prefix=None, params=None):
super(GraphGRUCell, self).__init__(prefix=prefix, params=params)
assert (len(aggregator_args) == 2)
self._aggregator_args = copy.deepcopy(aggregator_args)
... |
_module()
class NRTRModalityTransform(BaseModule):
def __init__(self, input_channels=3, init_cfg=[dict(type='Kaiming', layer='Conv2d'), dict(type='Uniform', layer='BatchNorm2d')]):
super().__init__(init_cfg=init_cfg)
self.conv_1 = nn.Conv2d(in_channels=input_channels, out_channels=32, kernel_size=3,... |
_module()
class LoveDADataset(CustomDataset):
CLASSES = ('background', 'building', 'road', 'water', 'barren', 'forest', 'agricultural')
PALETTE = [[255, 255, 255], [255, 0, 0], [255, 255, 0], [0, 0, 255], [159, 129, 183], [0, 255, 0], [255, 195, 128]]
def __init__(self, **kwargs):
super(LoveDADatase... |
_pipeline_test
class FeatureExtractionPipelineTests(unittest.TestCase):
model_mapping = MODEL_MAPPING
tf_model_mapping = TF_MODEL_MAPPING
_torch
def test_small_model_pt(self):
feature_extractor = pipeline(task='feature-extraction', model='hf-internal-testing/tiny-random-distilbert', framework='p... |
class MarianForCausalLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class TestPearlmutterHvp(TfGraphTestCase):
def test_pearl_mutter_hvp_1x1(self):
policy = HelperPolicy(n_vars=1)
x = policy.get_params()[0]
a_val = np.array([5.0])
a = tf.constant([0.0])
f = (a * (x ** 2))
expected_hessian = (2 * a_val)
vector = np.array([10.0]... |
def get_repeat_tasks(tasks, counts=5):
counts = (([counts] * len(tasks)) if isinstance(counts, int) else counts)
alltasks = []
isreptask = []
for (i, task) in enumerate(tasks):
for c in range(1, (counts[i] + 1)):
if (c == 1):
alltasks.append(task)
isre... |
def _get_sailvos_instances_meta():
SAILVOS_CATEGORIES_ = [c for c in SAILVOS_CATEGORIES if (c['id'] not in sailvos_ignore)]
thing_ids = [k['id'] for k in SAILVOS_CATEGORIES_]
thing_colors = [k['color'] for k in SAILVOS_CATEGORIES_]
assert (len(thing_ids) == 163), len(thing_ids)
thing_dataset_id_to_c... |
class SquadExample(object):
def __init__(self, qas_id, question_text, doc_tokens, orig_answer_text=None, start_position=None, end_position=None):
self.qas_id = qas_id
self.question_text = question_text
self.doc_tokens = doc_tokens
self.orig_answer_text = orig_answer_text
self... |
class ConvBNReLU(nn.Sequential):
def __init__(self, in_planes, out_planes, kernel_size=3, stride=1, groups=1, bn_aff=True):
padding = ((kernel_size - 1) // 2)
super(ConvBNReLU, self).__init__(nn.Conv2d(in_planes, out_planes, kernel_size, stride, padding, groups=groups, bias=False), nn.BatchNorm2d(ou... |
class PropPredictor(nn.Module):
def __init__(self, args, n_classes=1):
super(PropPredictor, self).__init__()
self.args = args
hidden_size = args.hidden_size
model = None
if (args.model_type == 'conv_net'):
model = MolConvNet(args, use_attn=False)
elif (arg... |
class TVMByteArray(ctypes.Structure):
_fields_ = [('data', ctypes.POINTER(ctypes.c_byte)), ('size', ctypes.c_size_t)] |
def hypergraph_Gnm(num_v: int, num_e: int, method: str='low_order_first', prob_k_list: Optional[List[float]]=None):
assert (num_v > 1), 'num_v must be greater than 1'
assert (num_e > 0), 'num_e must be greater than 0'
assert (method in ('uniform', 'low_order_first', 'high_order_first', 'custom')), "method m... |
def torch_mean(input, dim=None, keepdim=False, out=None):
global raw_torch_op, module_tensor_op
_stack = inspect.stack()
if (('forward' == _stack[1].function) and ('torch_mean_{}_1'.format(_stack[1].lineno) == module_tensor_op.get_module_name())):
input = module_tensor_op(input)
module_tenso... |
def split(t, split_size=None):
if (not exists(split_size)):
return t
if isinstance(t, torch.Tensor):
return t.split(split_size, dim=0)
if isinstance(t, Iterable):
return split_iterable(t, split_size)
return TypeError |
class AttentionPooling(nn.Module):
def __init__(self, in_features: int, keep_seq_dim: bool=False):
super().__init__()
self.norm = nn.LayerNorm(in_features)
self.query = nn.Parameter(torch.zeros(1, 1, in_features))
self.attn = nn.MultiheadAttention(in_features, 1, bias=False)
... |
class ConstantDice(Dice):
def __init__(self, constant):
super().__init__()
self.constant = self.max = constant
def roll(self):
return self.constant
def describe(self):
return repr(self.constant) |
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsample=None, dilation=1):
super(BasicBlock, self).__init__()
self.conv1 = conv3x3(inplanes, planes, stride=stride, dilation=dilation)
self.relu = nn.ReLU(inplace=True)
self.conv2 = conv3... |
class actionAngleHarmonic(actionAngle):
def __init__(self, *args, **kwargs):
actionAngle.__init__(self, ro=kwargs.get('ro', None), vo=kwargs.get('vo', None))
if (not ('omega' in kwargs)):
raise OSError('Must specify omega= for actionAngleHarmonic')
self._omega = conversion.parse_... |
def _update_registered_buffer(module, buffer_name, state_dict_key, state_dict, policy='resize_if_empty', dtype=torch.int):
new_size = state_dict[state_dict_key].size()
registered_buf = find_named_buffer(module, buffer_name)
if (policy in ('resize_if_empty', 'resize')):
if (registered_buf is None):
... |
def test_tuple_return_obj():
run_cell('\n x = 0\n y = 1\n a = x + 42\n b = y + 77\n def foo():\n return [a], [b]\n ')
run_cell('t = foo()[1][0]')
run_cell('x = 9')
run_cell('logging.info(t)')
assert_not_detected('`t` independent of updated `x`')
... |
def _upsample_flops_compute(input, size=None, scale_factor=None, mode='nearest', align_corners=None):
if (size is not None):
if isinstance(size, (tuple, list)):
return (int(_prod(size)), 0)
else:
return (int(size), 0)
assert (scale_factor is not None), 'either size or sca... |
def _get_lr_scheduler(lr, decay):
if (decay[0] == 'inverse time'):
lr_sch = paddle.optimizer.lr.InverseTimeDecay(lr, decay[1], verbose=False)
else:
raise NotImplementedError(f'{decay[0]} decay is not implemented in PaddlePaddle')
return lr_sch |
class ObservationGroupEncoder(Module):
def __init__(self, observation_group_shapes, feature_activation=nn.ReLU, encoder_kwargs=None):
super(ObservationGroupEncoder, self).__init__()
assert isinstance(observation_group_shapes, OrderedDict)
assert np.all([isinstance(observation_group_shapes[k]... |
def multi_topk_meter(ctx: Context, train_ctx: Context, k: int=1, init_num: int=1, end_num: int=0) -> dict:
def accuracy(output, target, k=1):
batch_size = target.size(0)
(_, pred) = output.topk(k, 1, True, True)
pred = pred.t()
correct = pred.eq(target.view(1, (- 1)).expand_as(pred))... |
class StandardAugInput(AugInput):
def __init__(self, image: np.ndarray, *, boxes: Optional[np.ndarray]=None, sem_seg: Optional[np.ndarray]=None):
_check_img_dtype(image)
self.image = image
self.boxes = boxes
self.sem_seg = sem_seg
def transform(self, tfm: Transform) -> None:
... |
class RobertaPreLayerNormForCausalLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def main(args):
img_mean = np.array([134., 102., 87.])
img_stddev = np.sqrt(np.array([3941., 2856., 2519.]))
vae_def = importlib.import_module(args.vae_def)
vae = vae_def.Vae(args.latent_var_size)
gen_image_size = vae.get_image_size()
subdir = datetime.strftime(datetime.now(), '%Y%m%d-%H%M%S')
... |
def load_ResNet101Model():
model = ResNet(Bottleneck, [3, 4, 23, 3])
copy_parameter_from_resnet(model, torchvision.models.resnet101(weights=models.ResNet101_Weights.DEFAULT).state_dict())
return model |
def UnpackVariable(var, num):
assert (len > 0)
if ((type(var) is list) and (len(var) == num)):
return var
else:
ret = []
if (type(var) is list):
assert (len(var) == 1)
for i in xrange(0, num):
ret.append(var[0])
else:
for i ... |
def check_predictions(clf, X, y):
n_samples = len(y)
classes = np.unique(y)
n_classes = classes.shape[0]
predicted = clf.fit(X, y).predict(X)
assert_array_equal(clf.classes_, classes)
assert (predicted.shape == (n_samples,))
assert_array_equal(predicted, y)
probabilities = clf.predict_pr... |
class QDQBertForMaskedLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class WriteError(Exception):
def __init__(self, filename, message):
self.filename = filename
self.message = message
def __str__(self):
return 'Error writing record to file {}: {}'.format(self.filename, self.message) |
def map_layers(weight):
return OrderedDict([((k.replace('z', 'w'), v) if ('z' in k) else (k, v)) for (k, v) in weight.items()]) |
class SummMetric():
metric_name: str = None
range: Tuple[(float, float)] = None
higher_is_better: bool = None
requires_heavy_compute: bool = None
def evaluate(self, inputs: List[str], targets: List[str], keys: List[str]) -> Dict[(str, float)]:
raise NotImplementedError("the base class for me... |
class BindSelfPaced(_BindOptions):
def bind(subparser):
subparser.add_argument('--begin_value', default=[1000], type=float, nargs='+', help='ProjectorParams.LossParams.begin_value')
subparser.add_argument('--end_value', default=[1000], type=float, nargs='+', help='ProjectorParams.LossParams.end_valu... |
def load_dataset(data_dir):
print(f'Loading dataset from {data_dir}')
if data_dir.endswith('.json'):
(src, tgt) = load_json(data_dir)
elif data_dir.endswith('.txt'):
with open(data_dir, 'r') as f:
data = [l.split('\t') for l in f.readlines()]
(src, tgt) = list(zip(*data))... |
class TinyImagenetDataModule(ImagenetDataModule):
def __init__(self, datadir: str, train: Optional[DictConfig]=None, val: Optional[DictConfig]=None, test: Optional[DictConfig]=None) -> None:
super().__init__(datadir=datadir, train=train, val=val, test=test)
def num_classes(self) -> int:
return 2... |
class SimulationRobotActor(AbstractActor):
def __init__(self, robot, *args, **kwargs):
super(SimulationRobotActor, self).__init__(*args, **kwargs)
self.robot = robot
self.getState = self.robot.getState |
class RiskEstimator():
def __init__(self, loss):
self.loss = maps.loss[loss]()
self.risks = np.array([[]])
def return_and_save(self, loss):
self.risks = np.append(self.risks, loss)
return loss |
class Trainer(object):
def __init__(self, para, config_path=None):
self.para = para
self.config_path = config_path
def run(self):
self.para.time = datetime.now()
logger = Logger(self.para, self.config_path)
logger.record_para()
if (not self.para.test_only):
... |
def sentence_bleu(hypothesis, reference):
bleu = _corpus_bleu(hypothesis, reference)
for i in range(1, 4):
bleu.counts[i] += 1
bleu.totals[i] += 1
bleu = compute_bleu(bleu.counts, bleu.totals, bleu.sys_len, bleu.ref_len, smooth_method='exp')
return bleu.score |
def image_transform(x, H, out_shape=None, interpolation='NEAREST'):
shape = x.get_shape().as_list()
if (out_shape is None):
if (len(shape) == 4):
out_shape = shape[1:3]
else:
out_shape = shape[:2]
return tf.contrib.image.transform(x, H, interpolation=interpolation, ou... |
class TaskType(Enum):
Classification = 'Classification'
Summarization = 'Summarization'
PairwiseClassification = 'PairwiseClassification' |
_cache()
def statcast_outfield_catch_prob(year: int, min_opp: Union[(int, str)]='q') -> pd.DataFrame:
url = f'
res = requests.get(url, timeout=None).content
data = pd.read_csv(io.StringIO(res.decode('utf-8')))
data = sanitize_statcast_columns(data)
return data |
def rename_state_dict_key(k, patterns):
for (tf_name, hf_name) in patterns:
k = k.replace(tf_name, hf_name)
return k |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.