code stringlengths 101 5.91M |
|---|
class EncoderConv(nn.Module):
def __init__(self, in_ch, out_ch):
super(EncoderConv, self).__init__()
self.conv = nn.Conv2d(in_ch, out_ch, 3, padding=1)
self.gn = nn.GroupNorm((out_ch // 4), out_ch)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
x = self.conv(x)
... |
class XGBoostModelBuilder(ModelBuilder):
def __init__(self, model_type='regressor', cpus_per_trial=1, **xgb_configs):
self.model_type = model_type
self.model_config = xgb_configs.copy()
if (('n_jobs' in xgb_configs) and (xgb_configs['n_jobs'] != cpus_per_trial)):
logger.warning(f... |
def test_torch_Accuracy():
from bigdl.orca.learn.pytorch.pytorch_metrics import Accuracy
pred = torch.tensor([0, 2, 3, 4])
target = torch.tensor([1, 2, 3, 4])
acc = Accuracy()
acc(pred, target)
assert (acc.compute() == 0.75)
pred = torch.tensor([0, 2, 3, 4])
target = torch.tensor([1, 1, ... |
def extract_comments(directory):
for (parent, dir_names, file_names) in os.walk(directory):
for file_name in file_names:
if ((os.path.splitext(file_name)[1] == '.py') and (file_name != '__init__.py')):
doc = get_comments_str(os.path.join(parent, file_name))
direct... |
def get_class_name():
import platform
if (platform.system() == 'Windows'):
return WindowsJob
elif (platform.system() == 'Linux'):
return LinuxJob
else:
return None |
def miliseconds_to_frame_index(miliseconds: int, fps: int) -> int:
return int((fps * (miliseconds / 1000))) |
def mlperf_log_epoch_start(iteration, iters_per_epoch):
if (iteration == 0):
log_start(key=constants.BLOCK_START, metadata={'first_epoch_num': 1, 'epoch_count': 1})
log_start(key=constants.EPOCH_START, metadata={'epoch_num': 1})
return
if ((iteration % iters_per_epoch) == 0):
epo... |
class TestSparseWeightedAverage(unittest.TestCase):
def device(self):
return 'cuda'
def setUpClass(cls):
if (not torch.cuda.is_available()):
raise unittest.SkipTest('No CUDA capable device detected')
def _zero_grad(self, Q, K):
for x in [Q, K]:
if (x.grad is n... |
def build_model(base_model_cfg='vgg'):
if (base_model_cfg == 'vgg'):
return TUN_bone(base_model_cfg, *extra_layer(base_model_cfg, vgg16()))
elif (base_model_cfg == 'resnet'):
return TUN_bone(base_model_cfg, *extra_layer(base_model_cfg, resnet50())) |
def make_layers(cfg, batch_norm=False):
layers = []
in_channels = 3
for v in cfg:
if (v == 'M'):
layers += [nn.MaxPool2d(kernel_size=2, stride=2)]
else:
print('Reflection Padding')
conv2d = nn.Conv2d(in_channels, v, kernel_size=3)
if batch_norm... |
def graph_mean_and_std(categories, means, stds, ymin=0, ymax=500, xaxis='', filename=''):
plt.errorbar(categories, means, stds, linestyle='None', marker='^')
plt.ylim(ymin, ymax)
plt.xlabel(xaxis, fontsize=12)
plt.ylabel('Mean Difference in Stopping Epoch', fontsize=12)
fname = (('graph_images/' + f... |
def get_scheduler(optimizer, policy, nepoch_fix=None, nepoch=None, decay_step=None):
if (policy == 'lambda'):
def lambda_rule(epoch):
lr_l = (1.0 - (max(0, (epoch - nepoch_fix)) / float(((nepoch - nepoch_fix) + 1))))
return lr_l
scheduler = lr_scheduler.LambdaLR(optimizer, lr... |
def create_cpp_version_headers(dir_path, license_c):
version_lines = ['\n', '// Automatic generated header with version information.', '#ifndef VERSION_H_', '#define VERSION_H_', '#define L2A_VERSION_GIT_SHA_HEAD_ "{}"'.format(get_git_sha()), '#endif', '']
with open(os.path.join(dir_path, 'version.h'), 'w') as ... |
def test_mobilenet_v2():
for s in [224, 192, 160, 128]:
for wm in [1.0, 0.75, 0.5, 0.25]:
cfg.merge_from_file('configs/cifar/mbv2_cifar100_224_e100.yaml')
cfg.MODEL.COMPRESSION.WIDTH_MULTIPLIER = wm
round_nearest = cfg.MODEL.COMPRESSION.ROUND_NEAREST
feature_d... |
class StableDiffusionDiffEditPipeline(metaclass=DummyObject):
_backends = ['torch', 'transformers']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch', 'transformers'])
def from_config(cls, *args, **kwargs):
requires_backends(cls, ['torch', 'transformers'])
def from_pr... |
class PermutationProblem(Problem[PermutationSolution], ABC):
def __init__(self):
super(PermutationProblem, self).__init__() |
def MakeInterAll(Info, InteractionType):
L = Info['L']
InterAllArray = []
if (Info['model'] == '"Fermion Hubbard"'):
if (InteractionType == 'Normal'):
for x in range(0, L):
lattice_origin = x
lattice_forward = ((x + 1) % L)
InterAllArray.ap... |
def quaternion_linear(input, r_weight, i_weight, j_weight, k_weight, bias=True):
cat_kernels_4_r = torch.cat([r_weight, (- i_weight), (- j_weight), (- k_weight)], dim=0)
cat_kernels_4_i = torch.cat([i_weight, r_weight, (- k_weight), j_weight], dim=0)
cat_kernels_4_j = torch.cat([j_weight, k_weight, r_weight... |
def normalized(a, axis=(- 1), order=2):
l2 = np.atleast_1d(np.linalg.norm(a, order, axis))
l2[(l2 == 0)] = 1
return (a / np.expand_dims(l2, axis)) |
def predict_cases_fastest(model, list_of_lists, output_filenames, folds, num_threads_preprocessing, num_threads_nifti_save, segs_from_prev_stage=None, do_tta=True, mixed_precision=True, overwrite_existing=False, all_in_gpu=True, step_size=0.5, checkpoint_name='model_final_checkpoint'):
assert (len(list_of_lists) ==... |
class Stage(Enum):
COMPILATION = 'compilation'
EXECUTION = 'execution'
VERIFICATION = 'verification' |
def validation(df, valDir, inPklCoarse, network, trainMode):
strideNet = 16
minSize = 480
precAllAlign = np.zeros(8)
totalAlign = 0
pixelGrid = np.around(np.logspace(0, np.log10(36), 8).reshape((- 1), 8))
for key in list(network.keys()):
network[key].eval()
with torch.no_grad():
... |
def test_pred_files() -> None:
assert (len(PRED_FILES) >= 6)
assert all((path.endswith(('.csv', '.csv.gz', '.json', '.json.gz')) for path in PRED_FILES.values()))
for (model, path) in PRED_FILES.items():
msg = f'Missing preds file for model={model!r}, expected at path={path!r}'
assert os.pat... |
class FasterRCNN(object):
__category__ = 'architecture'
__inject__ = ['backbone', 'rpn_head', 'bbox_assigner', 'roi_extractor', 'bbox_head', 'fpn']
def __init__(self, backbone, rpn_head, roi_extractor, bbox_head='BBoxHead', bbox_assigner='BBoxAssigner', rpn_only=False, fpn=None):
super(FasterRCNN, s... |
class Mask(object):
def __init__(self, gamma=0.7):
self.gamma = gamma
def __call__(self, sequence):
copied_sequence = copy.deepcopy(sequence)
mask_nums = int((self.gamma * len(copied_sequence)))
mask = [0 for i in range(mask_nums)]
mask_idx = random.sample([i for i in ran... |
_module()
class PANet(TextDetectorMixin, SingleStageTextDetector):
def __init__(self, backbone, neck, bbox_head, train_cfg=None, test_cfg=None, pretrained=None, show_score=False, init_cfg=None):
SingleStageTextDetector.__init__(self, backbone, neck, bbox_head, train_cfg, test_cfg, pretrained, init_cfg)
... |
def test_caffe2xavierinit():
model = nn.Sequential(nn.Conv2d(3, 1, 3), nn.ReLU(), nn.Linear(1, 2))
func = Caffe2XavierInit(bias=0.1, layer='Conv2d')
func(model)
assert torch.equal(model[0].bias, torch.full(model[0].bias.shape, 0.1))
assert (not torch.equal(model[2].bias, torch.full(model[2].bias.sha... |
def decide_function(path, label, sl, xs):
img = Image.open(path)
attack_image = add_watermark_to_image(img, xs, watermark, sl)
attack_image = attack_image.convert('RGB')
predict = label_model(model, attack_image).cpu().detach().numpy()
if (np.argmax(predict) != int(label)):
return True
e... |
def generate_model(input_shape_tra_cdr3, input_shape_tra_vgene, input_shape_tra_jgene, input_shape_trb_cdr3, input_shape_trb_vgene, input_shape_trb_jgene, num_outputs):
kmer_size = 4
features_tra_cdr3 = Input(shape=input_shape_tra_cdr3)
features_tra_vgene = Input(shape=input_shape_tra_vgene)
features_tr... |
class CNNModel(Model):
def __init__(self, filters, strides, padding, name=None, hidden_nonlinearity=tf.nn.relu, hidden_w_init=tf.initializers.glorot_uniform(seed=deterministic.get_tf_seed_stream()), hidden_b_init=tf.zeros_initializer()):
super().__init__(name)
self._filters = filters
self._s... |
_module()
class PascalVOCDataset(CustomDataset):
CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus', 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse', 'motorbike', 'person', 'pottedplant', 'sheep', 'sofa', 'train', 'tvmonitor')
PALETTE = [[0, 0, 0], [128, 0, 0], [0, 128,... |
.filterwarnings('ignore::DeprecationWarning')
def test_log() -> None:
configure_logging()
logger.info('Testing') |
def read_png(filename):
string = tf.read_file(filename)
image = tf.image.decode_image(string, channels=3)
image.set_shape([None, None, 3])
image = tf.cast(image, tf.float32)
image /= 255
return image |
def resnet_v1(inputs, blocks, num_classes=None, is_training=True, global_pool=True, output_stride=None, include_root_block=True, spatial_squeeze=True, reuse=None, scope=None):
with tf.variable_scope(scope, 'resnet_v1', [inputs], reuse=reuse) as sc:
end_points_collection = (sc.original_name_scope + '_end_poi... |
def main(model_args, data_args, training_args):
last_checkpoint = None
if (not model_args.hyper_param_search):
if (os.path.isdir(training_args.output_dir) and training_args.do_train and (not training_args.overwrite_output_dir)):
last_checkpoint = get_last_checkpoint(training_args.output_dir)... |
class Adapter(nn.Module):
def __init__(self, cfg, red_fac=2):
super(Adapter, self).__init__()
self.cfg = cfg
self.embed_dim = cfg.encoder_embed_dim
self.quant_noise = getattr(cfg, 'quant_noise_pq', 0)
self.quant_noise_block_size = (getattr(cfg, 'quant_noise_pq_block_size', 8)... |
def resnet101(pretrained: bool=False, progress: bool=True, **kwargs: Any) -> ResNet:
return ResNet(torchvision.models.resnet101(pretrained, progress, **kwargs)) |
class FGSM(object):
def attack(model, epsilon, x, target):
xn = Point(x.data)
xn.requires_grad_()
model.optimizer.zero_grad()
loss = model.stdLoss(xn, None, target).sum()
loss.backward()
r = (x + Point((epsilon * torch.sign(xn.grad.data))))
model.optimizer.zer... |
class Data(object):
def get_size(self):
raise NotImplementedError()
def get_by_idxs(self, idxs):
data = defaultdict(list)
for idx in idxs:
each_data = self.get_one(idx)
for (key, val) in each_data.items():
data[key].append(val)
return data
... |
class TFFlaubertForMultipleChoice():
def __init__(self, *args, **kwargs):
requires_tf(self)
def from_pretrained(self, *args, **kwargs):
requires_tf(self) |
class Optimizers(object):
def __init__(self):
self.optimizers = []
self.lrs = []
def add(self, optimizer, lr):
self.optimizers.append(optimizer)
self.lrs.append(lr)
def step(self):
for optimizer in self.optimizers:
optimizer.step()
def zero_grad(self):... |
class BartForConditionalGeneration():
def __init__(self, *args, **kwargs):
requires_pytorch(self)
def from_pretrained(self, *args, **kwargs):
requires_pytorch(self) |
class LL2XYProjector():
def __init__(self, lat_origin, lon_origin):
self.lat_origin = lat_origin
self.lon_origin = lon_origin
self.zone = (math.floor(((lon_origin + 180.0) / 6)) + 1)
self.p = pyproj.Proj(proj='utm', ellps='WGS84', zone=self.zone, datum='WGS84')
[self.x_origin... |
class Lipophilicity(MoleculeCSVDataset):
def __init__(self, smiles_to_graph=smiles_2_dgl, load=False, log_every=1000, cache_file_path='./lipophilicity_dglgraph.bin', n_jobs=1):
self._url = 'dataset/lipophilicity.zip'
data_path = (get_download_dir() + '/lipophilicity.zip')
dir_path = (get_dow... |
class BasicModule(Module):
def __init__(self):
super(BasicModule, self).__init__()
self.model_name = self.__class__.__name__
def save(self, name=None):
prefix = (('checkpoints/' + self.model_name) + '_')
if (name is None):
name = time.strftime((prefix + '%Y%m%d_%H%M%S... |
class GNActDWConv2d(nn.Module):
def __init__(self, indim, gn_groups=32):
super().__init__()
self.gn = nn.GroupNorm(gn_groups, indim)
self.conv = nn.Conv2d(indim, indim, 5, dilation=1, padding=2, groups=indim, bias=False)
def forward(self, x, size_2d):
(h, w) = size_2d
(_,... |
def prototype_twitter_GaussOnly_VHRED_NormOp_ClusterExp1():
state = prototype_state()
state['train_dialogues'] = '../TwitterDataBPE/Train.dialogues.pkl'
state['test_dialogues'] = '../TwitterDataBPE/Test.dialogues.pkl'
state['valid_dialogues'] = '../TwitterDataBPE/Valid.dialogues.pkl'
state['dictiona... |
def checkpoint(nets, history, cfg, epoch):
print('Saving checkpoints...')
(net_encoder, net_decoder, crit) = nets
dict_encoder = net_encoder.state_dict()
dict_decoder = net_decoder.state_dict()
torch.save(history, '{}/history_epoch_{}.pth'.format(cfg.DIR, epoch))
torch.save(dict_encoder, '{}/enc... |
class ClusteredSparseDotProduct(torch.autograd.Function):
dot = {'cpu': clustered_sparse_dot_product_cpu, 'cuda': clustered_sparse_dot_product_cuda}
dot_backward = {'cpu': clustered_sparse_dot_backward_cpu, 'cuda': clustered_sparse_dot_backward_cuda}
def forward(ctx, Q, K, topk, groups, counts, lengths):
... |
def load_from_splits(paths, original_test_filename, model_predicted_filename):
sentence_potential_mistake_count = defaultdict(int)
for path in paths:
original_test = os.path.join(path, original_test_filename)
model_predicted = os.path.join(path, model_predicted_filename)
assert os.path.e... |
class BridgeTowerForMaskedLM(metaclass=DummyObject):
_backends = ['torch']
def __init__(self, *args, **kwargs):
requires_backends(self, ['torch']) |
def test_diaghom(precision='d'):
from phcpy.sets import witness_set_of_hypersurface
hyp1 = 'x1*x2;'
hyp2 = 'x1 - x2;'
(w1sys, w1sols) = witness_set_of_hypersurface(2, hyp1, precision)
print('the witness sets for', hyp1)
for pol in w1sys:
print(pol)
for sol in w1sols:
print(so... |
def _create_dummy_line_str_file(ann_file):
ann_info1 = 'sample1.jpg hello'
ann_info2 = 'sample2.jpg world'
with open(ann_file, 'w') as fw:
for ann_info in [ann_info1, ann_info2]:
fw.write((ann_info + '\n')) |
class DukeMTMCreID(BaseImageDataset):
dataset_dir = 'dukemtmcreid'
def __init__(self, root='', verbose=True, pid_begin=0, **kwargs):
super(DukeMTMCreID, self).__init__()
self.dataset_dir = osp.join(root, self.dataset_dir)
self.dataset_url = '
self.train_dir = osp.join(self.datase... |
class LRASPP(nn.Module):
def __init__(self, backbone, low_channels, high_channels, num_classes, inter_channels=128):
super().__init__()
self.backbone = backbone
self.classifier = LRASPPHead(low_channels, high_channels, num_classes, inter_channels)
def forward(self, input):
featur... |
def _unbroadcast(x, shape):
extra_dims = (x.ndim - len(shape))
assert (extra_dims >= 0)
dim = [i for i in range(x.ndim) if ((x.shape[i] > 1) and ((i < extra_dims) or (shape[(i - extra_dims)] == 1)))]
if len(dim):
x = x.sum(dim=dim, keepdim=True)
if extra_dims:
x = x.reshape((- 1), *x... |
def ssd_print(key, value=None, stack_offset=1, deferred=False, extra_print=True, prefix=''):
return _mlperf_print(key=key, value=value, benchmark=SSD, stack_offset=stack_offset, tag_set=SSD_TAG_SET, deferred=deferred, extra_print=extra_print, root_dir=ROOT_DIR_SSD, prefix=prefix) |
def _unescape_token(token):
def match(m):
.\n\n If m.group(1) exists, then use the integer in m.group(1) to return a\n unicode character.\n\n Args:\n m: match object\n\n Returns:\n String to replace matched object with.\n '
if (m.group(1) is None):
return (u'_' i... |
def combine(video_name_split_path, video_duration_path, save_path):
video_name_split = load_json(video_name_split_path)
video_duration_dict = load_json(video_duration_path)
combined_dict = {}
for (split_name, split_video_names) in video_name_split.items():
combined_dict[split_name] = {vid_name: ... |
class ContextGuidedBlock(nn.Module):
def __init__(self, in_channels, out_channels, dilation=2, reduction=16, down=False, residual=True, norm_layer=nn.BatchNorm2d):
super(ContextGuidedBlock, self).__init__()
inter_channels = ((out_channels // 2) if (not down) else out_channels)
if down:
... |
def count_conv2d(m, x, y):
x = x[0]
cin = m.in_channels
cout = m.out_channels
(kh, kw) = m.kernel_size
batch_size = x.size()[0]
out_h = y.size(2)
out_w = y.size(3)
kernel_ops = ((multiply_adds * kh) * kw)
bias_ops = (1 if (m.bias is not None) else 0)
ops_per_element = (kernel_ops... |
class CollectTestLoss(MultipleRunBase):
MultipleRun_params = luigi.DictParameter()
score_name = luigi.Parameter(default='Test loss')
def obj_task(self, **kwargs):
return PerformanceEvaluation(**kwargs) |
def _write_config(config, config_path):
config_text = text_format.MessageToString(config)
with tf.gfile.Open(config_path, 'wb') as f:
f.write(config_text) |
class DiscreteActionSpace(ActionSpace):
def __init__(self, num):
super(DiscreteActionSpace, self).__init__()
self.num = num
def sample(self):
return self.rng.randint(self.num)
def num_actions(self):
return self.num
def __repr__(self):
return 'DiscreteActionSpace({... |
def atom_features(atom):
return torch.Tensor((((onek_encoding_unk(atom.GetSymbol(), ELEM_LIST) + onek_encoding_unk(atom.GetDegree(), [0, 1, 2, 3, 4, 5])) + onek_encoding_unk(atom.GetFormalCharge(), [(- 1), (- 2), 1, 2, 0])) + [atom.GetIsAromatic()])) |
def main():
list_mod = ['Nsite', 'Lanczos_max', 'NumAve', 'ExpecInterval']
dict_mod = func_mod('modpara.def', list_mod)
max_set = int(dict_mod['NumAve'])
max_eigen = int(dict_mod['Lanczos_max'])
Ref_ave_Temp = np.zeros([max_eigen], dtype=np.float64)
Ref_err_Temp = np.zeros([max_eigen], dtype=np.... |
_experiment
def dqn_cartpole(ctxt=None, seed=1):
set_seed(seed)
with LocalTFRunner(ctxt) as runner:
n_epochs = 10
steps_per_epoch = 10
sampler_batch_size = 500
num_timesteps = ((n_epochs * steps_per_epoch) * sampler_batch_size)
env = GarageEnv(gym.make('CartPole-v0'))
... |
def test_octree_OctreeNodeInfo():
origin = [0, 0, 0]
size = 2.0
depth = 5
child_index = 7
node_info = o3d.geometry.OctreeNodeInfo(origin, size, depth, child_index)
np.testing.assert_equal(node_info.origin, origin)
np.testing.assert_equal(node_info.size, size)
np.testing.assert_equal(node... |
def sparsenet161(**kwargs):
return get_sparsenet(num_layers=161, model_name='sparsenet161', **kwargs) |
.mujoco
.no_cover
.timeout(60)
def test_mtppo_metaworld_ml1_push():
assert (subprocess.run([str((EXAMPLES_ROOT_DIR / 'torch/mtppo_metaworld_ml1_push.py')), '--epochs', '1', '--batch_size', '1'], check=False).returncode == 0) |
def test_sql_observer_failed_event_updates_run(sql_obs, sample_run, session):
sql_obs.started_event(**sample_run)
fail_trace = ['lots of errors and', 'so', 'on...']
sql_obs.failed_event(fail_time=T2, fail_trace=fail_trace)
assert (session.query(Run).count() == 1)
db_run = session.query(Run).first()
... |
def readme():
with open('README_mmdet.md', encoding='utf-8') as f:
content = f.read()
return content |
class PathwayTypes(object):
NORM = 0
SUBS = 1
FC = 2
def pTypes(self):
return [self.NORM, self.SUBS, self.FC] |
def mixing_noise(batch, latent_dim, prob, device):
if ((prob > 0) and (random.random() < prob)):
return make_noise(batch, latent_dim, 2, device)
else:
return [make_noise(batch, latent_dim, 1, device)] |
def create_datasets(data_dir: str, dest_dir: str):
try:
assert os.path.exists(data_dir)
except AssertionError:
raise Exception(f'[create_datasets] ERROR: DATA_DIR {data_dir} MUST EXIST')
if (not os.path.exists(dest_dir)):
os.makedirs(dest_dir)
dataset_creators = [ProofStepClassif... |
class HuffmanCodeBuilder():
def __init__(self):
self.symbols = Counter()
def add_symbols(self, *syms) -> None:
self.symbols.update(syms)
def increment(self, symbol: str, cnt: int) -> None:
self.symbols[symbol] += cnt
def from_file(cls, filename):
c = cls()
with op... |
class SentencePieceUnigramTokenizer(BaseTokenizer):
def __init__(self, replacement: str='', add_prefix_space: bool=True, unk_token: Union[(str, AddedToken)]='<unk>', eos_token: Union[(str, AddedToken)]='</s>', pad_token: Union[(str, AddedToken)]='<pad>'):
self.special_tokens = {'pad': {'id': 0, 'token': pad... |
def make_atari(env_id, max_episode_steps=None):
env = gym.make(env_id)
assert ('NoFrameskip' in env.spec.id)
env = NoopResetEnv(env, noop_max=30)
env = MaxAndSkipEnv(env, skip=4)
if (max_episode_steps is not None):
env = TimeLimit(env, max_episode_steps=max_episode_steps)
return env |
def _f_lcs(llcs, m, n):
r_lcs = (llcs / m)
p_lcs = (llcs / n)
beta = (p_lcs / (r_lcs + 1e-12))
num = (((1 + (beta ** 2)) * r_lcs) * p_lcs)
denom = (r_lcs + ((beta ** 2) * p_lcs))
f_lcs = (num / (denom + 1e-12))
return f_lcs |
def train_transform():
transform_list = [transforms.Resize(size=(512, 512)), transforms.RandomCrop(256), transforms.ToTensor()]
return transforms.Compose(transform_list) |
def plot_augmentations(y, sr, time_shift=3000, pitch_shift=12, time_stretch=1.3):
augmentations = {'Original': y, 'Timeshift left': y[time_shift:], 'Timeshift right': numpy.concatenate([numpy.zeros(time_shift), y[:(- time_shift)]]), 'Timestretch faster': librosa.effects.time_stretch(y, time_stretch), 'Timestretch s... |
def save_model_card(repo_id: str, image_logs=None, base_model=str, repo_folder=None):
img_str = ''
if (image_logs is not None):
for (i, log) in enumerate(image_logs):
images = log['images']
validation_prompt = log['validation_prompt']
validation_image = log['validatio... |
class TestPointAssigner(unittest.TestCase):
def test_point_assigner(self):
assigner = PointAssigner()
pred_instances = InstanceData()
pred_instances.priors = torch.FloatTensor([[0, 0, 1], [10, 10, 1], [5, 5, 1], [32, 32, 1]])
gt_instances = InstanceData()
gt_instances.bboxes ... |
def conv3x3(in_channels, out_channels, module_name, postfix, stride=1, groups=1, kernel_size=3, padding=1):
return [(f'{module_name}_{postfix}/conv', nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding, groups=groups, bias=False)), (f'{module_name}_{postfix}/norm', get_norm(... |
def create_feedforward_V_function(observation_shape, *args, observation_preprocessor=None, name='feedforward_V', **kwargs):
input_shapes = (observation_shape,)
preprocessors = (observation_preprocessor, None)
return feedforward_model(input_shapes, *args, output_size=1, preprocessors=preprocessors, **kwargs) |
def get_tasks(task_names):
task_names = task_names.split(',')
if ('all' in task_names):
tasks = TASKS
else:
tasks = []
for task_name in task_names:
assert (task_name in TASKS), ('Task %s not found!' % task_name)
tasks.append(task_name)
return tasks |
class ProbModel(torch.nn.Module):
def __init__(self, model):
super(ProbModel, self).__init__()
self.model = model
def forward(self, x):
x = self.model(x)
x = torch.softmax(x, 1)
return x |
def remove_small_elements(segmentation_mask: np.ndarray, min_size: int=1000) -> np.ndarray:
pred_mask = (segmentation_mask > 0)
mask = remove_small_objects(pred_mask, min_size=min_size)
clean_segmentation = (segmentation_mask * mask)
return clean_segmentation |
def conv_layer(ni, nf, ks=3, stride=1, zero_bn=False, act=True):
bn = nn.BatchNorm2d(nf)
nn.init.constant_(bn.weight, (0.0 if zero_bn else 1.0))
layers = [conv(ni, nf, ks, stride=stride), bn]
if act:
layers.append(act_fn)
return nn.Sequential(*layers) |
class DynamicMTGATPruneModel(nn.Module):
def __init__(self, config, concat=True, num_gat_layers=1, use_pe=False):
super(DynamicMTGATPruneModel, self).__init__()
self.config = config
self.use_pe = use_pe
if concat:
gat_out_channel = int((self.config['graph_conv_out_dim'] /... |
def create_dummy_func(func, dependency, message=''):
err = "Cannot import '{}', therefore '{}' is not available.".format(dependency, func)
if message:
err = ((err + ' ') + message)
if isinstance(dependency, (list, tuple)):
dependency = ','.join(dependency)
def _dummy(*args, **kwargs):
... |
def load_data(folder, domain):
from scipy import io
data = io.loadmat(os.path.join(folder, (domain + '_fc6.mat')))
return (data['fts'], data['labels']) |
def f2_score_multi(y_true, y_pred, average):
return fbeta_score(y_true, y_pred, average=average, beta=2) |
class GaussianDropout(Layer):
def __init__(self, rate, bigdl_type='float'):
super(GaussianDropout, self).__init__(None, bigdl_type, rate) |
class _StemBlock(nn.Module):
def __init__(self, num_input_channels, num_init_features):
super(_StemBlock, self).__init__()
num_stem_features = int((num_init_features / 2))
self.stem1 = BasicConv2d(num_input_channels, num_init_features, kernel_size=3, stride=2, padding=1)
self.stem2a ... |
def test(cfg_file, ckpt: str, output_path: str=None, datasets: dict=None, save_attention: bool=False, save_scores: bool=False) -> None:
cfg = load_config(Path(cfg_file))
(model_dir, load_model, device, n_gpu, num_workers, normalization, fp16) = parse_train_args(cfg['training'], mode='prediction')
if (len(lo... |
class UmapKmeans():
def __init__(self, n_clusters, umap_dim=2, umap_neighbors=10, umap_min_distance=float(0), umap_metric='euclidean', random_state=0):
self.n_clusters = n_clusters
self.manifold_in_embedding = umap.UMAP(random_state=random_state, metric=umap_metric, n_components=umap_dim, n_neighbor... |
def _graph_network(graph_tuple):
update_node_fn = (lambda n, se, re, g: n)
update_edge_fn = (lambda e, sn, rn, g: e)
update_global_fn = (lambda gn, ge, g: g)
net = nn.GraphNetwork(update_edge_fn, update_node_fn, update_global_fn)
return net(graph_tuple) |
class Attacker():
def __init__(self, clip_max=1.0, clip_min=0.0):
self.clip_max = clip_max
self.clip_min = clip_min
def perturb(self, model, x, y):
pass |
def _master_is_failing_stamp(branch, commit):
return '<!-- commit {}{} -->'.format(commit, branch) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.