code stringlengths 101 5.91M |
|---|
class TmpData(BaseDataset):
def __init__(self, n, **kwargs):
self.n = range(n)
super().__init__(**kwargs)
def __len__(self):
return len(self.n)
def load(self, item, x, y, meta):
x['item'] = self.n[item]
return (x, y, meta)
def augment(self, x, y, meta):
x[... |
class TestCutVideo(unittest.TestCase):
def setUp(self):
shutil.rmtree('./raw', ignore_errors=True)
os.mkdir('./raw')
def tearDown(self) -> None:
shutil.rmtree('./raw', ignore_errors=True)
((get_device_type() != 'cpu'), 'Only run this test on CPU')
def test_cut_video(self):
... |
class TFConvNextPreTrainedModel(TFPreTrainedModel):
config_class = ConvNextConfig
base_model_prefix = 'convnext'
main_input_name = 'pixel_values'
def dummy_inputs(self) -> Dict[(str, tf.Tensor)]:
VISION_DUMMY_INPUTS = tf.random.uniform(shape=(3, self.config.num_channels, self.config.image_size, ... |
def get_loss(seg_pred, seg):
per_instance_seg_loss = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=seg_pred, labels=seg), axis=1)
seg_loss = tf.reduce_mean(per_instance_seg_loss)
per_instance_seg_pred_res = tf.argmax(seg_pred, 2)
return (seg_loss, per_instance_seg_loss, per_instan... |
def get_super_module_by_name(model, module_name):
name_list = module_name.split('.')
for name in name_list[:(- 1)]:
if hasattr(model, name):
model = getattr(model, name)
else:
return None
if hasattr(model, name_list[(- 1)]):
return model
else:
retu... |
class FlaxDDIMScheduler(metaclass=DummyObject):
_backends = ['flax']
def __init__(self, *args, **kwargs):
requires_backends(self, ['flax'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['flax'])
def from_pretrained(cls, *args, **kwargs):
requires_backends(cls, ['... |
class TcmfValDataset(torch.utils.data.IterableDataset):
def __init__(self, config):
super(TcmfValDataset).__init__()
self.tcmf_data_loader = get_tcmf_data_loader(config)
def __iter__(self):
(inp, out, _, _) = self.tcmf_data_loader.supply_test()
(yield (inp, out)) |
def hn(tag):
if ((tag[0] == 'h') and (len(tag) == 2)):
try:
n = int(tag[1])
if (n in range(1, 10)):
return n
except ValueError:
return 0 |
def save_model(epoch, args, model, type_name=''):
model_to_save = (model.module.banzhafteacher if hasattr(model, 'module') else model.banzhafteacher)
output_model_file = join(args.output_dir, 'pytorch_model.bin.{}{}'.format(('' if (type_name == '') else (type_name + '.')), epoch))
torch.save(model_to_save.s... |
class CNNMnist(nn.Module):
def __init__(self, args):
super(CNNMnist, self).__init__()
self.conv1 = nn.Conv2d(args.num_channels, 16, 8, 2, padding=3)
self.conv2 = nn.Conv2d(16, 32, 4, 2)
self.fc1 = nn.Linear(((32 * 4) * 4), 32)
self.fc2 = nn.Linear(32, args.num_classes)
de... |
def train() -> None:
print(f'Starting training {config.name}...')
train_losses = []
t_start = time()
while True:
for input in train_loader:
config.step += 1
input = input.to(config.device)
loss = train_step(input)
train_losses.append(loss)
... |
def my_augment_pool():
augs = [(AutoContrast, None, None), (Brightness, 1.8, 0.1), (Color, 1.8, 0.1), (Contrast, 1.8, 0.1), (Cutout, 0.2, 0), (Equalize, None, None), (Invert, None, None), (Posterize, 4, 4), (Rotate, 30, 0), (Sharpness, 1.8, 0.1), (ShearX, 0.3, 0), (ShearY, 0.3, 0), (Solarize, 256, 0), (SolarizeAdd,... |
class ForwardBackward(Algorithm):
def __init__(self, parameters=None, **kargs):
Algorithm.__init__(self)
self.add_parameters(parameters, kargs)
self._default_keyword_parameters.update({'gradient': None, 'proximal': None, 'lipschitz_constant': None, 'lambda': 1, 'initialization': None, 'relat... |
class Pooler(nn.Module):
def __init__(self, output_size, scales, sampling_ratio):
super(Pooler, self).__init__()
poolers = []
for scale in scales:
poolers.append(ROIAlign(output_size, spatial_scale=scale, sampling_ratio=sampling_ratio))
self.poolers = nn.ModuleList(pooler... |
def _compute_corrected_ttest(differences: np.ndarray, n_train: int, n_test: int, df: Optional[int]=None, alternative: str='two-sided') -> Tuple[(float, float)]:
mean = differences.mean(axis=0)
if (df is None):
df = (len(differences) - 1)
std = _corrected_std(differences, n_train=n_train, n_test=n_te... |
def number_double_solutions(vrblvl=0):
if (vrblvl > 0):
print('in number_double_solutions ...')
phc = get_phcfun()
aaa = pointer(c_int32(0))
bbb = pointer(c_int32(0))
ccc = pointer(c_double(0.0))
vrb = c_int32(vrblvl)
if (vrblvl > 0):
print('-> number_double_solutions calls p... |
def get_ptb_format_from_diora_tree(parse, tokens, return_string=False, batched=False):
if batched:
return [get_ptb_format(p, t, return_string, batched=False) for (p, t) in zip(parse, tokens)]
def recursive_add_tokens(parse):
def helper(tr, pos):
if (not isinstance(tr, (tuple, list)))... |
def main():
node = rospy.init_node('map_collector')
controller = Controller(node)
controller.start()
navigator = Navigator(controller)
navigator = make_file_dataset(navigator)
navigator = visualize(navigator)
navigator.explore() |
def tensor_normalize(data):
d_min = data.min(dim=1)[0]
data += torch.abs(d_min).unsqueeze(1).repeat(1, data.shape[1])
d_min = data.min(dim=1)[0]
d_max = data.max(dim=1)[0]
dst = (d_max - d_min)
norm_data = (data - d_min.unsqueeze(1).repeat(1, data.shape[1])).true_divide(dst.unsqueeze(1).repeat(1... |
class OnlineEstimator():
def __init__(self, x_):
self.n = 1
self.mean = (x_ * 0.0)
self.m2 = (x_ * 0.0)
delta = (x_ - self.mean)
self.mean += (delta / self.n)
delta2 = (x_ - self.mean)
self.m2 += (delta * delta2)
def __call__(self, x_):
self.n += 1... |
class Gen_50(nn.Module):
def __init__(self):
super(Gen_50, self).__init__()
self.name = 'Gen_50'
self.lr = 3e-05
self.n_hosts = 50
self.n_hidden = 64
self.n = ((self.n_hosts * PROTO_DIM) + (self.n_hosts * self.n_hosts))
self.delta = nn.Sequential(nn.Linear(sel... |
def conv_block_Asym_Inception_WithIncreasedFeatMaps(in_dim, mid_dim, out_dim, kernel_size, padding, dilation=1):
model = nn.Sequential(nn.Conv2d(in_dim, mid_dim, kernel_size=[kernel_size, 1], padding=tuple([(padding * dilation), 0]), dilation=(dilation, 1)), nn.BatchNorm2d(mid_dim), nn.ReLU(), nn.Conv2d(mid_dim, ou... |
def output_seq_1():
class MockTokenizer():
def decode(self, i=None):
return ''
def convert_ids_to_tokens(self, i=None):
return ['']
output_1 = output.OutputSeq(**{'model_type': 'causal', 'tokenizer': MockTokenizer(), 'token_ids': [[352, 11, 352, 11, 362]], 'n_input_tokens... |
.script
def swish_jit_bwd(x, grad_output):
x_sigmoid = torch.sigmoid(x)
return (grad_output * (x_sigmoid * (1 + (x * (1 - x_sigmoid))))) |
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--depth_map', help='path to depth map', type=str, required=True)
parser.add_argument('-n', '--normal_map', help='path to normal map', type=str, required=True)
parser.add_argument('--min_depth_percentile', help='minimum visua... |
def aggregate_scores_for_experiment(score_file, labels=None, metrics=Evaluator.default_metrics, nanmean=True, json_output_file=None, json_name='', json_description='', json_author='Fabian', json_task=''):
scores = np.load(score_file)
scores_mean = scores.mean(0)
if (labels is None):
labels = list(ma... |
class RLAus_Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, downsample=None, rla_channel=32, SE=False, ECA_size=None, groups=1, base_width=64, dilation=1, norm_layer=None, reduction=16):
super(RLAus_Bottleneck, self).__init__()
if (norm_layer is None):
... |
def run_production(input_doc, default_claim=False):
try:
input_doc = filter_feats(input_doc, load=True)
input_doc = add_embeddings(input_doc)
spacy_var = True
except:
spacy_var = False
our_approach = True
if our_approach:
doc = input_doc
doc_sents = list(d... |
def parse_args():
parser = argparse.ArgumentParser(description='Print the whole config')
parser.add_argument('config', help='config file path')
parser.add_argument('--options', nargs='+', action=DictAction, help='arguments in dict')
args = parser.parse_args()
return args |
def edge_matrix(labels, connectivity=1):
conn = ndi.generate_binary_structure(labels.ndim, connectivity)
eroded = ndi.grey_erosion(labels, footprint=conn).ravel()
dilated = ndi.grey_dilation(labels, footprint=conn).ravel()
labels = labels.ravel()
boundaries0 = np.flatnonzero((eroded != labels))
... |
def __init__2__cinit__(lines, no_optimization):
new_lines = []
in_cclass = False
for line in lines:
if ((len(line) > 13) and (line[:14] == '')):
in_cclass = True
elif ((line[0] not in ' \n') and (not ((len(line) > 4) and (line[:5] == 'class')))):
in_cclass = False
... |
def main(args):
trs_parser = Trs2Stm(args.trs, args.audio)
trs_parser.print_segments()
return 0 |
class TestKraus(ChannelTestCase):
def test_init(self):
chan = Kraus(self.UI)
self.assertAllClose(chan.data, [self.UI])
self.assertEqual(chan.dim, (2, 2))
chan = Kraus(self.depol_kraus(0.5))
self.assertAllClose(chan.data, self.depol_kraus(0.5))
self.assertEqual(chan.di... |
def test_chunk_text_preprocessor_one_go():
df = pd.read_csv(os.path.join(data_folder, fname))
text_processor = TextPreprocessor(text_col=text_col, n_cpus=1, maxlen=10, max_vocab=50)
X_text = text_processor.fit_transform(df)
chunk_text_processor = ChunkTextPreprocessor(text_col=text_col, n_chunks=1, n_cp... |
def make_plot(list_of_csv):
colors = px.colors.qualitative.Dark24
n_colors = len(colors)
fig = go.Figure()
hovertemplate_prediction = '<b>%{meta}</b><br>x=%{x}<br>y=%{y}<extra></extra>'
for (index, path) in enumerate(list_of_csv):
df_temporary = pd.read_csv(path)
fig.add_trace(go.Sca... |
class CUDA_build_ext(build_ext):
def build_extensions(self):
self.compiler.src_extensions.append('.cu')
self.compiler.set_executable('compiler_so', 'nvcc')
self.compiler.set_executable('linker_so', 'nvcc --shared')
if hasattr(self.compiler, '_c_extensions'):
self.compiler... |
def SGD(model_param, lr=0.0001, momentum=0.9, dampening=0, weight_decay=0, nesterov=False):
optimizer = torch.optim.SGD(model_param, lr=lr, momentum=momentum, dampening=dampening, weight_decay=weight_decay, nesterov=False)
return optimizer |
def active_session(delay=DELAY, interval=INTERVAL):
token = requests.request('GET', TOKEN_URL, headers=TOKEN_HEADERS).text
headers = {'Authorization': ('STAR ' + token)}
delay = max(delay, MIN_DELAY)
interval = max(interval, MIN_INTERVAL)
original_handler = signal.getsignal(signal.SIGALRM)
try:
... |
def listdir_nohidden(path, sort=False):
items = [f for f in os.listdir(path) if (not f.startswith('.'))]
if sort:
items.sort()
return items |
class Flip(Base):
def __init__(self, axis=0):
self.axis = axis
def tf(self, img, k=0):
return np.flip(img, self.axis)
def __str__(self):
return 'Flip(axis={})'.format(self.axis) |
class VAE_GST(nn.Module):
def __init__(self, hparams):
super().__init__()
self.ref_encoder = ReferenceEncoder(hparams)
self.fc1 = nn.Linear(hparams.ref_enc_gru_size, hparams.z_latent_dim)
self.fc2 = nn.Linear(hparams.ref_enc_gru_size, hparams.z_latent_dim)
self.fc3 = nn.Linea... |
def download_czang16(download_to, username=None):
wgets = [f'wget --user={username} --password=czeng -P {download_to} for i in range(10)]
cmds = []
for (i, cmd) in enumerate(wgets):
filename = f'{download_to}/data-plaintext-format.{i}.tar'
if os.path.exists(filename):
print(f'{f... |
def append_test(file, suites):
for suite in suites:
for test in suite['tests']:
text = (('\\item ' + tex_escape(test['fullTitle'])) + '\n')
file.write(text)
append_test(file, suite['suites']) |
def codex(prompt, top_p=1, temperature=0.0, n=1):
response = None
received = False
while (not received):
try:
openai.api_key = key_generator.get_key()
response = openai.Completion.create(engine=engine, prompt=prompt, max_tokens=128, logprobs=1, top_p=top_p, n=n, temperature=t... |
def kaiming_uniform_in_(tensor, a=0, mode='fan_in', scale=1.0, nonlinearity='leaky_relu'):
fan_in = nn.init._calculate_correct_fan(tensor, mode)
fan_in *= scale
gain = nn.init.calculate_gain(nonlinearity, a)
std = (gain / math.sqrt(fan_in))
bound = (math.sqrt(3.0) * std)
with torch.no_grad():
... |
def _calculate_fan_in(tensor):
dimension = tensor.ndimension()
if (dimension < 2):
raise ValueError('Fan in can not be computed for tensor with less than 2 dimensions')
fan_in = tensor.size(1)
if ((dimension > 2) and (tensor.dim() > 2)):
fan_in *= tensor[0][0].numel()
return fan_in |
class ReliabilityMetricsPowerOutage(PowerOutage):
def __init__(self, saifi: float=None, caidi: float=None, start_time_steps: List[int]=None, **kwargs):
super().__init__(**kwargs)
self.saifi = saifi
self.caidi = caidi
self.start_time_steps = start_time_steps
def saifi(self) -> flo... |
def _dump_entity_embeddings(predictor: BertPredictor):
for start in range(0, len(entity_dict), SHARD_SIZE):
end = (start + SHARD_SIZE)
shard_id = (start // SHARD_SIZE)
shard_path = _get_shard_path(shard_id=shard_id)
if os.path.exists(shard_path):
logger.info('{} already e... |
class FurthestPointSamplingWithDist(Function):
def forward(ctx, points_dist: torch.Tensor, num_points: int) -> torch.Tensor:
assert points_dist.is_contiguous()
(B, N, _) = points_dist.size()
output = points_dist.new_zeros([B, num_points], dtype=torch.int32)
temp = points_dist.new_zer... |
def write_html(filename, iterations, image_save_iterations, image_directory, all_size=1536):
html_file = open(filename, 'w')
html_file.write(('\n <!DOCTYPE html>\n <html>\n <head>\n <title>Experiment name = %s</title>\n <meta content="30">\n </head>\n <body>\n ' % os.path.basena... |
class CrossEn(nn.Module):
def __init__(self):
super(CrossEn, self).__init__()
def forward(self, sim_matrix, target):
logpt = F.log_softmax(sim_matrix, dim=(- 1))
logpt = torch.index_select(logpt, (- 1), target)
loss = (- logpt)
sim_loss = loss.mean()
return sim_lo... |
def get_network(weights):
if (weights in WEIGHTS_URLS.keys()):
arch_params = WEIGHTS_URLS[weights]['arch_params']
url = WEIGHTS_URLS[weights]['url']
name = WEIGHTS_URLS[weights]['name']
else:
raise ValueError('Available RDN network weights: {}'.format(list(WEIGHTS_URLS.keys())))
... |
class ImgNormalize(nn.Conv2d):
def __init__(self, pixel_range, img_mean, img_std, sign=(- 1)):
assert (len(img_mean) == len(img_std))
num_channels = len(img_mean)
super().__init__(num_channels, num_channels, kernel_size=1)
std = torch.Tensor(img_std)
self.weight.data = torch.... |
def image_clean(cleaning_set, imagefile, basedir):
if (cleaning_set == 'clean_greyscale'):
clean_greyscale.clean_greyscale(imagefile)
elif (cleaning_set == 'clean_extractfaces'):
clean_extractfaces.clean_extractfaces(imagefile, basedir)
elif (cleaning_set == 'clean_jpg2png'):
clean_j... |
def ae_pointnet(args, num_points=2048, global_feat=True, data=None):
model = AE_pointnet(args, num_points, global_feat)
if (data is not None):
model.encoder.load_state_dict(data['state_dict_encoder'])
model.decoder.load_state_dict(data['state_dict_decoder'])
return model |
def write_checkpoints_json(model_name_or_path, local_rank, checkpoints_json, token=None):
checkpoint_files = get_checkpoint_files(model_name_or_path, local_rank, token)
if ((local_rank == 0) and (len(checkpoint_files) != 0)):
data = {'type': 'ds_model', 'checkpoints': checkpoint_files, 'version': 1.0}
... |
def main():
parser = argparse.ArgumentParser(description='NoBox')
parser.add_argument('--gp_coeff', type=float, default=0.0, help='coeff for the gradient penalty')
parser.add_argument('--latent_dim', type=int, default=20, metavar='N', help='Latent dim for VAE')
parser.add_argument('--lr', type=float, de... |
class JitDataLoader():
def __init__(self, module_name, file_name, batch_size, is_train, device, log, vocab=None):
self.module_name = module_name
split_chars = (lambda x: list(x))
source = Field(tokenize=split_chars, init_token='<sos>', eos_token='<eos>', batch_first=True)
target = Fi... |
class HyperGCN(nn.Module):
def __init__(self, V, E, X, num_features, num_layers, num_classses, args):
super(HyperGCN, self).__init__()
(d, l, c) = (num_features, num_layers, num_classses)
cuda = args.cuda
h = [d]
for i in range((l - 1)):
power = ((l - i) + 2)
... |
class LoopExecutor():
def run(self, target, *args_iter, verbose=False):
tasks = list(zip(*args_iter))
n_tasks = len(tasks)
for (i, task) in enumerate(tasks):
target(*task)
if verbose:
print(('task %i of %i' % ((n_tasks - len(tasks)), n_tasks))) |
def DataParallel(module, device_ids=None, output_device=None, dim=0, chunk_sizes=None):
if (chunk_sizes is None):
return torch.nn.DataParallel(module, device_ids, output_device, dim)
standard_size = True
for i in range(1, len(chunk_sizes)):
if (chunk_sizes[i] != chunk_sizes[0]):
... |
def worker(gpu, solver, ngpus_per_node, args):
args.sys_params.rank = ((args.sys_params.rank * ngpus_per_node) + gpu)
dist.init_process_group(backend='nccl', world_size=args.sys_params.world_size, init_method='env://', rank=args.sys_params.rank)
args.gpu = gpu
args.ngpus_per_node = ngpus_per_node
so... |
class AutoModelForSeq2SeqLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
class pos_model(base):
_init_pytorch
def __init__(self, vocab_size, embed_dim, embed_init, max_nsent, max_npara, max_nlv, doc_title_vocab_size, sec_title_vocab_size, experiment, *args, **kwargs):
super(pos_model, self).__init__(vocab_size, embed_dim, embed_init, experiment)
if (self.expe.config.... |
def train():
encoder = Encoder(encoder_params[0], encoder_params[1]).cuda()
decoder = Decoder(decoder_params[0], decoder_params[1]).cuda()
net = ED(encoder, decoder)
run_dir = ('./runs/' + TIMESTAMP)
if (not os.path.isdir(run_dir)):
os.makedirs(run_dir)
tb = SummaryWriter(run_dir)
ea... |
def batch_clamp(float_or_vector, tensor):
if isinstance(float_or_vector, torch.Tensor):
assert (len(float_or_vector) == len(tensor))
tensor = _batch_clamp_tensor_by_vector(float_or_vector, tensor)
return tensor
elif isinstance(float_or_vector, float):
tensor = clamp(tensor, (- fl... |
def components_from_array(ion, *, z, b, logN):
pars = Parameters()
for (num, vals) in enumerate(zip(z, b, logN)):
z_name = ('z%i_%s' % (num, ion))
b_name = ('b%i_%s' % (num, ion))
N_name = ('logN%i_%s' % (num, ion))
pars.add(z_name, value=vals[0])
pars.add(b_name, value=v... |
def sample_dirichlet(prior):
n = len(prior)
dist = np.zeros(n)
for i in range(n):
dist[i] = np.random.gamma(prior[i])
dist = (dist / sum(dist))
return dist |
class AgentOutputStatus(str, Enum):
NORMAL = 'normal'
CANCELLED = 'cancelled'
AGENT_CONTEXT_LIMIT = 'agent context limit' |
class Trainer(object):
def __init__(self, args):
self.args = args
self.saver = Saver(args)
self.saver.save_experiment_config()
self.summary = TensorboardSummary(self.saver.experiment_dir)
self.writer = self.summary.create_summary()
kwargs = {'num_workers': args.worker... |
def get_confirm_token(response):
for (key, value) in response.cookies.items():
if key.startswith('download_warning'):
return value
return None |
def vgg11_bn(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> VGG:
return VGG(torchvision.models.vgg11_bn(pretrained, progress, **kwargs)) |
def get_string_from_layer_name(all_layers, current_layer, full_layer_name):
(layer_name, auxiliary_output) = split_layer_name(full_layer_name)
for layer in all_layers:
if (layer is current_layer):
break
if (layer.get_name() == full_layer_name):
return layer.output_name()
... |
def ycrank(pt0, y):
from math import cos, sin, acos, pi
(yp0, yp1) = ((y[0] + pt0[0]), (y[1] + pt0[1]))
crklen = sqrt((((yp0 - 1) ** 2) + (yp1 ** 2)))
crkagl = acos(((yp0 - 1) / crklen))
if (yp1 < 0):
dlt = (pi - crkagl)
crkagl = (pi + dlt)
cx = (1 + (crklen * cos(crkagl)))
c... |
def main():
tf.set_random_seed(1)
(height, width) = (224, 224)
inputs = tf.Variable(tf.random_uniform((2, height, width, 3)), name='input')
inputs = tf.identity(inputs, 'input_node')
(net, end_points) = resnet_v1.resnet_v1_101(inputs, 1000, is_training=True)
print('nodes in the graph')
for n... |
def _load_from_remote(model_name_or_path: str, ckpt_file: str='best.ckpt', cfg_file: str='config.yaml', **kwargs) -> TranslatorHubInterface:
download_dir = _download_and_extract(model_name_or_path, **kwargs)
(config, test_data, model) = _from_pretrained(model_name_or_path=download_dir, ckpt_file=ckpt_file, cfg_... |
def get_video_codec_bitrate(width, height, framerate, divisor, factor):
return int(((((width * height) * (framerate / divisor)) * 12) * factor)) |
class SharedStorage(object):
def __init__(self):
self._networks = {}
def latest_network(self) -> Network:
if self._networks:
return self._networks[max(self._networks.keys())]
else:
return make_uniform_network()
def old_network(self) -> Network:
if self... |
def pointnet_fp_module(xyz1, xyz2, points1, points2, mlp, is_training, bn_decay, scope, bn=True):
with tf.variable_scope(scope) as sc:
(dist, idx) = three_nn(xyz1, xyz2)
dist = tf.maximum(dist, 1e-10)
norm = tf.reduce_sum((1.0 / dist), axis=2, keepdims=True)
norm = tf.tile(norm, [1, ... |
class RNNEncoder(nn.Module):
def __init__(self, n_vocab, d_word_vec, d_model, n_layer, brnn, rnn, feat_vocab, d_feat_vec, slf_attn, dropout):
self.name = 'rnn'
self.n_layer = n_layer
self.num_directions = (2 if brnn else 1)
assert ((d_model % self.num_directions) == 0), 'd_model = hi... |
def train_wsam(train_loader, model, criterion, optimizer, scheduler, args):
starttime = time.time()
train_loss = 0.0
total_num = 0
model.train()
for (batch_idx, (data, target)) in enumerate(train_loader):
if args.use_gpu:
(data, target) = (data.cuda(non_blocking=args.pin_memory),... |
class Distribution():
def __init__(self):
with resource_stream(__name__, 'resources/partition_spline.npz') as spline_file:
with np.load(spline_file, allow_pickle=False) as f:
self._spline_x_scale = torch.tensor(f['x_scale'])
self._spline_values = torch.tensor(f['v... |
class ResNet_Strategy(nn.Module):
def __init__(self, block, num_blocks, args):
self.args = args
super(ResNet_Strategy, self).__init__()
self.in_planes = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(64)
self... |
def build_mxnet_kl():
fake_yaml = '\n model:\n name: imagenet\n framework: mxnet\n\n quantization:\n model_wise:\n activation:\n algorithm: kl\n\n tuning:\n accuracy_criterion:\n relative: 0.01\n exit_policy:\n timeout: 0\n ... |
class AutoModelForSequenceClassification(nn.Module):
def __init__(self, args, Model, config, num_labels=2):
super(AutoModelForSequenceClassification, self).__init__()
self.num_labels = num_labels
self.encoder = Model
self.config = config
self.dropout = nn.Dropout(args.drop_ra... |
class CrystalPlateMail(BaseSuit):
def __init__(self):
super().__init__('crystal plate mail', weight=450, armour_class=7, material=M.Glass) |
def generate_scenario(num_hosts, num_services, **params):
generator = ScenarioGenerator()
return generator.generate(num_hosts, num_services, **params) |
def test_sim_trajectory():
with open('test/data/habitat-sim_trajectory_data.json', 'r') as f:
test_trajectory = json.load(f)
with init_sim() as sim:
sim.reset()
sim.set_agent_state(position=test_trajectory['positions'][0], rotation=test_trajectory['rotations'][0])
for (i, action)... |
class RawVideoExtractorCV2():
def __init__(self, centercrop=False, size=224, framerate=(- 1)):
self.centercrop = centercrop
self.size = size
self.framerate = framerate
self.transform = self._transform(self.size)
def _transform(self, n_px):
return Compose([Resize(n_px, int... |
def setup_density_and_loaders(config, device):
(train_loader, valid_loader, test_loader) = get_loaders(dataset=config['dataset'], device=device, data_root=config['data_root'], make_valid_loader=config['early_stopping'], train_batch_size=config['train_batch_size'], valid_batch_size=config['valid_batch_size'], test_b... |
def imagenet_wide_resnet50_2_pretrained(output_dim):
return _replace_fc(torchvision.models.wide_resnet50_2(pretrained=True), output_dim) |
def get_num_channels(input_shape_or_channels):
if hasattr(input_shape_or_channels, '__iter__'):
return input_shape_or_channels[0]
else:
return input_shape_or_channels |
class CustomLVISResults(LVISResults):
def __init__(self, lvis_gt, results, max_dets=300, max_dets_per_class=(- 1)):
if isinstance(lvis_gt, LVIS):
self.dataset = deepcopy(lvis_gt.dataset)
elif isinstance(lvis_gt, str):
self.dataset = self._load_json(lvis_gt)
else:
... |
def extract_davis(epochs):
results = dict()
print('\t \tJ&F-Mean,J-Mean,J-Recall,J-Decay,F-Mean,F-Recall,F-Decay')
JFm = []
Jm = []
Jr = []
Jd = []
Fm = []
Fr = []
Fd = []
for e in epochs:
results[e] = dict()
full_path = join('result', args.dataset, e, 'global_res... |
class RecDataSetTest(tf.test.TestCase):
def testRecDataSet(self):
dir_path = os.path.dirname(os.path.abspath(__file__))
data_dir = os.path.join(dir_path, 'testdata')
rec_data_set = rec_dataset.RecDataset(os.path.join(data_dir, 'batch.txt'), '', os.path.join(data_dir, 'feature_dict.txt'), 0, ... |
def get_pydot_graph(caffe_net, rankdir, label_edges=True, phase=None):
pydot_graph = pydot.Dot((caffe_net.name if caffe_net.name else 'Net'), graph_type='digraph', rankdir=rankdir)
pydot_nodes = {}
pydot_edges = []
for layer in caffe_net.layer:
if (phase is not None):
included = Fals... |
def get_action_for_move(agent_position: Tuple[(int, int)], agent_direction: Grid4TransitionsEnum, next_agent_position: Tuple[(int, int)], next_agent_direction: int, rail: GridTransitionMap) -> Optional[RailEnvActions]:
possible_transitions = rail.get_transitions(*agent_position, agent_direction)
num_transitions... |
def test_batch_all_triplet_loss():
num_data = 10
feat_dim = 6
margin = 0.2
num_classes = 5
embeddings = np.random.rand(num_data, feat_dim).astype(np.float32)
labels = np.random.randint(0, num_classes, size=num_data).astype(np.float32)
for squared in [True, False]:
pdist_matrix = pair... |
def prepare_environment(seed):
random.seed(seed)
np.random.seed(seed)
tf.set_random_seed(seed) |
def transliteration_cleaners(text):
text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.