code stringlengths 17 6.64M |
|---|
def GetChemSpider12(a):
TreatedAtoms = np.array([1, 6, 7, 8], dtype=np.uint8)
PARAMS['NetNameSuffix'] = 'act_sigmoid100'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 21
PARAMS['batch_size'] = 50
PARAMS['test_freq'] = 1
PARAMS['tf_prec'] = 'tf.float64'... |
def Xmas():
'\n\tShoot a tree with a ball.\n\t'
tree = Mol()
tree.FromXYZString(treeXYZ)
tree.coords -= tree.Center()
ball = Mol()
ball.FromXYZString(ballXYZ)
ball.coords -= ball.Center()
ball.coords -= np.array([15.0, 0.0, 0.0])
ntree = tree.NAtoms()
toshoot = Mol(np.concatena... |
def Train():
if 1:
a = MSet('water_mini')
a.Load()
random.shuffle(a.mols)
TreatedAtoms = a.AtomTypes()
PARAMS['NetNameSuffix'] = 'training_sample'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 15
PARAMS['batc... |
def Eval():
if 1:
a = MSet('H2O_trimer_move', center_=False)
a.ReadXYZ('H2O_trimer_move')
TreatedAtoms = a.AtomTypes()
PARAMS['NetNameSuffix'] = 'training_sample'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 15
PARA... |
class GroundTruthDatasetFactory(Dataset):
'\n Factory to create projection datasets from any 2D image-data.\n\n This is essentially a simple version of dival[1] without any noise contribution.\n\n References:\n [1] Johannes Leuschner, Maximilian Schmidt, Daniel Otero Baguer, and Peter Maaß.\n ... |
class SResFourierCoefficientDataset(Dataset):
def __init__(self, ds, amp_min, amp_max):
self.ds = ds
if ((amp_min == None) and (amp_max == None)):
tmp_imgs = []
for i in np.random.permutation(len(self.ds))[:200]:
img = self.ds[i]
tmp_imgs.ap... |
class TRecFourierCoefficientDataset(Dataset):
def __init__(self, ds, angles, mag_min, mag_max, img_shape=42, inner_circle=True):
self.ds = ds
self.img_shape = img_shape
self.inner_circle = inner_circle
self.angles = angles
if ((mag_min == None) and (mag_max == None)):
... |
def _fc_prod_loss(pred_fc, target_fc, amp_min, amp_max):
pred_amp = denormalize_amp(pred_fc[(..., 0)], amp_min=amp_min, amp_max=amp_max)
target_amp = denormalize_amp(target_fc[(..., 0)], amp_min=amp_min, amp_max=amp_max)
pred_phi = denormalize_phi(pred_fc[(..., 1)])
target_phi = denormalize_phi(target... |
def _fc_sum_loss(pred_fc, target_fc, amp_min, amp_max):
pred_amp = denormalize_amp(pred_fc[(..., 0)], amp_min=amp_min, amp_max=amp_max)
target_amp = denormalize_amp(target_fc[(..., 0)], amp_min=amp_min, amp_max=amp_max)
pred_phi = denormalize_phi(pred_fc[(..., 1)])
target_phi = denormalize_phi(target_... |
class SResTransformerTrain(torch.nn.Module):
def __init__(self, d_model, coords, flatten_order, attention_type='linear', n_layers=4, n_heads=4, d_query=32, dropout=0.1, attention_dropout=0.1):
super(SResTransformerTrain, self).__init__()
self.fourier_coefficient_embedding = torch.nn.Linear(2, (d_... |
class SResTransformerPredict(torch.nn.Module):
def __init__(self, d_model, coords, flatten_order, attention_type='full', n_layers=4, n_heads=4, d_query=32, dropout=0.1, attention_dropout=0.1):
super(SResTransformerPredict, self).__init__()
self.fourier_coefficient_embedding = torch.nn.Linear(2, (... |
class RAdam(Optimizer):
def __init__(self, params, lr=0.001, max_grad_norm=1.0, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, degenerated_to_sgd=True):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('... |
class PlainRAdam(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, degenerated_to_sgd=True):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilo... |
class AdamW(Optimizer):
def __init__(self, params, lr=0.001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, warmup=0):
if (not (0.0 <= lr)):
raise ValueError('Invalid learning rate: {}'.format(lr))
if (not (0.0 <= eps)):
raise ValueError('Invalid epsilon value: {}'.format(... |
class TestTomoUtils(unittest.TestCase):
def setUp(self) -> None:
self.img_shape = 27
self.angles = np.array([0, (np.pi / 2), np.pi])
def test_cartesian_rfft_2D(self):
(x, y, flatten_indices, order) = get_cartesian_rfft_coords_2D(self.img_shape)
x_ordered = torch.zeros_like(x)... |
class TestUtils(unittest.TestCase):
def test_cart2pol2cart(self):
x = torch.arange(1, 6, dtype=torch.float32)
y = torch.arange((- 2), 3, dtype=torch.float32)
(r, phi) = cart2pol(x, y)
(x_, y_) = pol2cart(r, phi)
self.assertTrue((torch.allclose(x, x_) and torch.allclose(y, ... |
def get_data(params, dataset_name, subset=None):
load_test = (('train_all' in params) and params['train_all'])
test_dataset = None
transform = transforms.Compose([transforms.ToTensor()])
if (dataset_name == 'mnist'):
dataset = datasets.mnist.MNIST(root=config.DATASETS_DIR, download=True, trans... |
def attach_handlers(run, model, optimizer, learning_rule, trainer, evaluator, train_loader, val_loader, params):
UnitConvergence(model[0], learning_rule.norm).attach(trainer.engine, 'unit_conv')
pbar = ProgressBar(persist=True, bar_format=config.IGNITE_BAR_FORMAT)
pbar.attach(trainer.engine, metric_names=... |
def main(args: Namespace, params: dict, dataset_name, run_postfix=''):
identifier = time.strftime('%Y%m%d-%H%M%S')
run = '{}/heb/{}'.format(dataset_name, identifier)
if run_postfix:
run += ('-' + run_postfix)
print("Starting run '{}'".format(run))
model = models.create_conv1_model(28, 1, n... |
def main():
model = models.create_fc1_model([(28 ** 2), 2000])
transform = transforms.Compose([transforms.ToTensor()])
dataset = datasets.mnist.MNIST(root=config.DATASETS_DIR, download=True, transform=transform)
train_loader = DataLoader(dataset, batch_size=1024, shuffle=True)
learning_rule = Krot... |
def create_fc1_model(hu: List, n: float=1.0, batch_norm=False):
modules = [('flatten', Flatten()), ('linear1', nn.Linear(hu[0], hu[1], bias=False))]
if batch_norm:
modules.append(('batch_norm', nn.BatchNorm1d(num_features=hu[1])))
modules.append(('repu', RePU(n)))
linear2 = nn.Linear(hu[1], 10... |
def create_fc2_model(hu: List, n: float=1.0, batch_norm=False):
modules = [('flatten', Flatten()), ('linear1', nn.Linear(hu[0], hu[1], bias=False))]
if batch_norm:
modules.append(('batch_norm', nn.BatchNorm1d(num_features=hu[1])))
modules.append(('repu1', RePU(n)))
modules.append(('linear2', n... |
def create_conv1_model(input_dim, input_channels=1, num_kernels=8, kernel_size=5, pool_size=2, n=1, batch_norm=False, dropout=None):
modules = [('conv1', nn.Conv2d(input_channels, num_kernels, kernel_size, bias=False))]
if batch_norm:
modules.append(('batch_norm', nn.BatchNorm2d(num_features=num_kerne... |
def create_conv2_model(input_dim, input_channels=1, num_kernels=None, kernel_size=4, pool_size=2, n=1):
if (num_kernels is None):
num_kernels = [8, 16]
modules = [('conv1', nn.Conv2d(input_channels, num_kernels[0], kernel_size, bias=False)), ('repu1', RePU(n)), ('pool1', nn.MaxPool2d(pool_size)), ('co... |
def attach_handlers(run, model, optimizer, trainer, train_evaluator, evaluator, train_loader, val_loader, params):
pbar = ProgressBar(persist=True, bar_format=config.IGNITE_BAR_FORMAT)
pbar.attach(trainer.engine, metric_names='all')
tqdm_logger = TqdmLogger(pbar=pbar)
tqdm_logger.attach_output_handler... |
def main(params, dataset_name, transfer_learning=False):
identifier = time.strftime('%Y%m%d-%H%M%S')
run = '{}/sup/{}'.format(dataset_name, identifier)
if transfer_learning:
run += '-tl'
if (('train_all' in params) and params['train_all']):
run += '-test'
print("Starting run '{}'".... |
def main(params):
model = models.create_fc1_model([(28 ** 2), 2000], n=1, batch_norm=True)
weights_path = '../output/models/heb-mnist-fashion-20200426-101420_m_500_acc=0.852.pth'
state_dict_path = os.path.join(PATH, weights_path)
model = load_weights(model, state_dict_path)
run = os.path.splitext(... |
class SimpleEngine(Engine):
'Custom engine with custom run function.\n\n This engine has only metrics in its state and only fires 2 events.\n '
def __init__(self, run_function: Callable):
super().__init__(process_function=(lambda x, y: None))
self._allowed_events = [Events.STARTED, Even... |
class Evaluator(ABC):
def __init__(self):
self.engine = None
self.logger = logging.getLogger(((__name__ + '.') + self.__class__.__name__))
def attach(self, engine, event_name, *args, **kwargs):
if (event_name not in State.event_to_attr):
raise RuntimeError("Unknown event ... |
class HebbianEvaluator(Evaluator):
def __init__(self, model: torch.nn.Module, score_name: str, score_function: Callable, init_function: Callable[([torch.nn.Module], tuple)]=None, epochs: int=100, supervised_from: int=None):
super().__init__()
self.model = model
self.score_name = score_nam... |
class SupervisedEvaluator(Evaluator):
def __init__(self, model, criterion, metrics=None, device=None):
super().__init__()
self.device = utils.get_device(device)
if (metrics is None):
metrics = {'accuracy': Accuracy(), 'loss': Loss(criterion)}
self.engine = create_super... |
class OutputHandler(BaseOutputHandler):
'Helper handler to log engine\'s output and/or metrics.\n\n Args:\n tag (str): common title for all produced plots. For example, \'training\'\n metric_names (list of str, optional): list of metric names to plot or a string "all" to plot all available\n ... |
class TqdmLogger(BaseLogger):
'Tqdm logger to log messages using the progress bar.'
def __init__(self, pbar):
self.pbar = pbar
def close(self):
if self.pbar:
self.pbar.close()
self.pbar = None
def _create_output_handler(self, *args, **kwargs):
return Outp... |
class HebbsRule(LearningRule):
def __init__(self, c=0.1):
super().__init__()
self.c = c
def update(self, inputs, w):
d_ws = torch.zeros(inputs.size(0))
for (idx, x) in enumerate(inputs):
y = torch.dot(w, x)
d_w = torch.zeros(w.shape)
for i ... |
class KrotovsRule(LearningRule):
'Krotov-Hopfield Hebbian learning rule fast implementation.\n\n Original source: https://github.com/DimaKrotov/Biological_Learning\n\n Args:\n precision: Numerical precision of the weight updates.\n delta: Anti-hebbian learning strength.\n norm: Lebesgue... |
class LearningRule(ABC):
def __init__(self):
self.logger = logging.getLogger(((__name__ + '.') + self.__class__.__name__))
def init_layers(self, model):
pass
@abstractmethod
def update(self, x, w):
pass
|
class OjasRule(LearningRule):
def __init__(self, c=0.1):
super().__init__()
self.c = c
def update(self, inputs, w):
d_ws = torch.zeros(inputs.size(0), *w.shape)
for (idx, x) in enumerate(inputs):
y = torch.mm(w, x.unsqueeze(1))
d_w = torch.zeros(w.shap... |
class UnitConvergence(Metric):
def __init__(self, layer: torch.nn.Module, norm: int, tolerance: int=0.1, output_transform=(lambda x: x), device=None):
self.layer = layer
self.norm = norm
self.tolerance = tolerance
super(UnitConvergence, self).__init__(output_transform=output_trans... |
class Flatten(nn.Module):
def forward(self, x: torch.Tensor):
return x.view(x.size(0), (- 1))
|
class RePU(nn.ReLU):
def __init__(self, n):
super(RePU, self).__init__()
self.n = n
def forward(self, x: torch.Tensor):
return (torch.relu(x) ** self.n)
|
class SPELoss(Module):
def __init__(self, m=1, beta=0.1):
super(SPELoss, self).__init__()
self.m = m
self.beta = beta
def forward(self, output, target):
output = torch.tanh((self.beta * output))
target = ((torch.nn.functional.one_hot(target, num_classes=output.shape[1... |
class Local(Optimizer):
def __init__(self, named_params, lr=required):
(self.param_names, params) = zip(*named_params)
if ((lr is not required) and (lr < 0.0)):
raise ValueError('Invalid learning rate: {}'.format(lr))
defaults = dict(lr=lr)
super(Local, self).__init__(... |
class Trainer(ABC):
'Abstract base trainer class.\n\n Supports (optional) evaluating and visualizing by default.\n '
def __init__(self, engine, model: torch.nn.Module, device: Optional[Union[(str, torch.device)]]=None):
self.engine = engine
self.model = model
self.device = utils... |
class SupervisedTrainer(Trainer):
'Trains a model using classical supervised backpropagation.\n\n Args:\n model: The model to be trained.\n optimizer: The optimizer used to train the model.\n criterion: The criterion used for calculating the loss.\n device: The device to be used.\n ... |
class HebbianTrainer(Trainer):
'Trains a model using unsupervised local learning rules also known as Hebbian learning.\n\n The specified learning rule is used to perform local weight updates after each batch of data. Per batch all\n trainable layers are updated in sequence.\n\n Args:\n model (torc... |
def plot_to_img(fig):
'Takes a matplotlib figure handle and converts it using canvas and string-casts to a numpy array that can be\n visualized in TensorBoard using the add_image function\n '
fig.canvas.draw()
img = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
img = img.resha... |
def extract_image_patches(x, kernel_size, stride=(1, 1), dilation=1, padding=0):
(b, c, h, w) = x.shape
patches = x.unfold(2, kernel_size[0], stride[0]).unfold(3, kernel_size[1], stride[1])
patches = patches.permute(0, 4, 5, 1, 2, 3).contiguous()
return patches.view((- 1), kernel_size[0], kernel_size[... |
def split_dataset(dataset, val_split):
val_size = int((val_split * len(dataset)))
train_size = (len(dataset) - val_size)
(train_dataset, val_dataset) = random_split(dataset, [train_size, val_size])
return (train_dataset, val_dataset)
|
def prepare_batch(batch, device=None, non_blocking=False):
'Prepare batch for training: pass to a device with options.'
(x, y) = batch
return (convert_tensor(x, device=device, non_blocking=non_blocking), convert_tensor(y, device=device, non_blocking=non_blocking))
|
def load_weights(model: torch.nn.Module, state_dict_path, layer_names: List=None, freeze=False):
'Load model weights from a stored state dict. Optionally only load weights for the specified layer.\n\n Args:\n model: The model acquiring the weights.\n state_dict_path: The path of the source state ... |
def extract_layers_from_state_dict(state_dict: dict, layer_names: List[str]):
'Extract layers from a state dict.'
new_state_dict = {}
for layer_name in layer_names:
if (type(layer_name) == tuple):
old_layer_name = layer_name[0]
new_layer_name = layer_name[1]
else:
... |
def get_device(device=None):
if (device is None):
if torch.cuda.is_available():
device = 'cuda'
torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
device = 'cpu'
elif (device == 'cuda'):
if torch.cuda.is_available():
device = '... |
def has_file_allowed_extension(filename: str, extensions: Tuple[(str, ...)]) -> bool:
return filename.lower().endswith(extensions)
|
def make_subsampled_dataset(directory, class_to_idx, extensions=None, is_valid_file=None, sampling_ratio=1.0, nb_classes=None):
instances = []
directory = os.path.expanduser(directory)
both_none = ((extensions is None) and (is_valid_file is None))
both_something = ((extensions is not None) and (is_val... |
class INatDataset(ImageFolder):
def __init__(self, root, train=True, year=2018, transform=None, target_transform=None, category='name', loader=default_loader):
self.transform = transform
self.loader = loader
self.target_transform = target_transform
self.year = year
path_js... |
class SubsampledDatasetFolder(DatasetFolder):
def __init__(self, root, loader, extensions=None, transform=None, target_transform=None, is_valid_file=None, sampling_ratio=1.0, nb_classes=None):
super(DatasetFolder, self).__init__(root, transform=transform, target_transform=target_transform)
(class... |
class ImageNetDataset(SubsampledDatasetFolder):
def __init__(self, root, loader=default_loader, is_valid_file=None, **kwargs):
super(ImageNetDataset, self).__init__(root, loader, (IMG_EXTENSIONS if (is_valid_file is None) else None), is_valid_file=is_valid_file, **kwargs)
self.imgs = self.samples... |
def build_dataset(is_train, args):
transform = build_transform(is_train, args)
if (args.data_set == 'CIFAR10'):
dataset = datasets.CIFAR10(args.data_path, train=is_train, transform=transform, download=True)
nb_classes = 10
if (args.data_set == 'CIFAR100'):
dataset = datasets.CIFAR1... |
def build_transform(is_train, args):
resize_im = (args.input_size > 32)
if is_train:
transform = create_transform(input_size=args.input_size, is_training=True, color_jitter=args.color_jitter, auto_augment=args.aa, interpolation=args.train_interpolation, re_prob=args.reprob, re_mode=args.remode, re_cou... |
def train_one_epoch(model: torch.nn.Module, criterion: torch.nn.Module, data_loader: Iterable, optimizer: torch.optim.Optimizer, device: torch.device, epoch: int, loss_scaler, max_norm: float=0, model_ema: Optional[ModelEma]=None, mixup_fn: Optional[Mixup]=None):
model.train()
criterion.train()
metric_log... |
@torch.no_grad()
def evaluate(data_loader, model, device):
criterion = torch.nn.CrossEntropyLoss()
metric_logger = utils.MetricLogger(delimiter=' ')
header = 'Test:'
model.eval()
for (images, target) in metric_logger.log_every(data_loader, 10, header):
images = images.to(device, non_block... |
def get_args_parser():
parser = argparse.ArgumentParser('PerViT training and evaluation script', add_help=False)
parser.add_argument('--batch-size', default=256, type=int)
parser.add_argument('--epochs', default=300, type=int)
parser.add_argument('--model', default='pervit_tiny', type=str, metavar='MO... |
def main(args):
utils.init_distributed_mode(args)
if utils.is_main_process():
tbd_writer = SummaryWriter(os.path.join(args.output_dir, 'tbd/runs'))
print(args)
device = torch.device(args.device)
seed = (args.seed + utils.get_rank())
print('seed: ', seed)
np.random.seed(seed)
to... |
@register_model
def pervit_tiny(pretrained=False, **kwargs):
num_heads = 4
kwargs['emb_dims'] = [128, 192, 224, 280]
kwargs['convstem_dims'] = [3, 48, 64, 96, 128]
model = VisionTransformer(num_heads=num_heads, norm_layer=partial(nn.LayerNorm, eps=1e-06), **kwargs)
model.default_cfg = _cfg()
r... |
@register_model
def pervit_small(pretrained=False, **kwargs):
num_heads = 8
kwargs['emb_dims'] = [272, 320, 368, 464]
kwargs['convstem_dims'] = [3, 64, 128, 192, 272]
model = VisionTransformer(num_heads=num_heads, norm_layer=partial(nn.LayerNorm, eps=1e-06), **kwargs)
model.default_cfg = _cfg()
... |
@register_model
def pervit_medium(pretrained=False, **kwargs):
num_heads = 12
kwargs['emb_dims'] = [312, 468, 540, 684]
kwargs['convstem_dims'] = [3, 64, 192, 256, 312]
model = VisionTransformer(num_heads=num_heads, norm_layer=partial(nn.LayerNorm, eps=1e-06), **kwargs)
model.default_cfg = _cfg()
... |
class OffsetGenerator():
@classmethod
def initialize(cls, n_patch_side, pad_size):
grid_1d = torch.linspace((- 1), 1, n_patch_side).to('cuda')
if (pad_size > 0):
pad_dist = torch.cumsum((grid_1d[(- 1)] - grid_1d[(- 2)]).repeat(pad_size), dim=0)
grid_1d = torch.cat([((-... |
class RASampler(torch.utils.data.Sampler):
'Sampler that restricts data loading to a subset of the dataset for distributed,\n with repeated augmentation.\n It ensures that different each augmented version of a sample will be visible to a\n different process (GPU)\n Heavily based on torch.utils.data.Di... |
class SmoothedValue(object):
'Track a series of values and provide access to smoothed values over a\n window or the global series average.\n '
def __init__(self, window_size=20, fmt=None):
if (fmt is None):
fmt = '{median:.4f} ({global_avg:.4f})'
self.deque = deque(maxlen=wi... |
class MetricLogger(object):
def __init__(self, delimiter='\t'):
self.meters = defaultdict(SmoothedValue)
self.delimiter = delimiter
def update(self, **kwargs):
for (k, v) in kwargs.items():
if isinstance(v, torch.Tensor):
v = v.item()
assert is... |
def _load_checkpoint_for_ema(model_ema, checkpoint):
'\n Workaround for ModelEma._load_checkpoint to accept an already-loaded object\n '
mem_file = io.BytesIO()
torch.save(checkpoint, mem_file)
mem_file.seek(0)
model_ema._load_checkpoint(mem_file)
|
def setup_for_distributed(is_master):
'\n This function disables printing when not in master process\n '
import builtins as __builtin__
builtin_print = __builtin__.print
def print(*args, **kwargs):
force = kwargs.pop('force', False)
if (is_master or force):
builtin_p... |
def is_dist_avail_and_initialized():
if (not dist.is_available()):
return False
if (not dist.is_initialized()):
return False
return True
|
def get_world_size():
if (not is_dist_avail_and_initialized()):
return 1
return dist.get_world_size()
|
def get_rank():
if (not is_dist_avail_and_initialized()):
return 0
return dist.get_rank()
|
def is_main_process():
return (get_rank() == 0)
|
def save_on_master(*args, **kwargs):
if is_main_process():
torch.save(*args, **kwargs)
|
def init_distributed_mode(args):
if (('RANK' in os.environ) and ('WORLD_SIZE' in os.environ)):
args.rank = int(os.environ['RANK'])
args.world_size = int(os.environ['WORLD_SIZE'])
args.gpu = int(os.environ['LOCAL_RANK'])
elif ('SLURM_PROCID' in os.environ):
args.rank = int(os.en... |
@torch.no_grad()
def compute_throughput(model, batch_size=128, resolution=224):
torch.cuda.empty_cache()
warmup_iters = 3
num_iters = 30
model.eval()
model.to('cuda')
timing = []
inputs = torch.randn(batch_size, 3, resolution, resolution, device='cuda')
for _ in range(warmup_iters):
... |
def download_from_google_drive(file_id, output_dir):
url = ('https://drive.google.com/uc?id=%s' % file_id)
output = os.path.join(output_dir, 'tmp.tar.gz')
gdown.download(url, output, quiet=False)
file = tarfile.open(output, 'r:gz')
file.extractall(output_dir)
file.close()
os.remove(output)... |
def align_and_split(files):
for f in tqdm(files):
get_ipython().system('/notebooks/MotionCor2_1.3.0-Cuda101 -InMrc {f} -OutMrc tmp/aligned.mrc -Patch 5 5 5 -OutStack 1 >> motioncor2.log')
aligned_stack = mrcfile.open(glob('tmp/*_Stk.mrc')[0], permissive=True)
save_mrc(join(data_path, 'even... |
def copy_etomo_files(src, name, target):
if exists(join(src, (name + 'local.xf'))):
cp(join(src, (name + 'local.xf')), target)
cp(join(src, (name + '.xf')), target)
cp(join(src, 'eraser.com'), target)
cp(join(src, 'ctfcorrection.com'), target)
cp(join(src, 'tilt.com'), target)
cp(join(... |
def augment(x, y):
rot_k = np.random.randint(0, 4, x.shape[0])
X = x.copy()
Y = y.copy()
for i in range(X.shape[0]):
if (np.random.rand() < 0.5):
X[i] = np.rot90(x[i], k=rot_k[i], axes=(0, 2))
Y[i] = np.rot90(y[i], k=rot_k[i], axes=(0, 2))
else:
X[i]... |
class CryoDataWrapper(Sequence):
def __init__(self, X, Y, batch_size):
(self.X, self.Y) = (X, Y)
self.batch_size = batch_size
self.perm = np.random.permutation(len(self.X))
def __len__(self):
return int(np.ceil((len(self.X) / float(self.batch_size))))
def on_epoch_end(se... |
class CryoCARE(CARE):
def train(self, X, Y, validation_data, epochs=None, steps_per_epoch=None):
'Train the neural network with the given data.\n Parameters\n ----------\n X : :class:`numpy.ndarray`\n Array of source images.\n Y : :class:`numpy.ndarray`\n ... |
@contextmanager
def cd(newdir):
'Context manager to temporarily change the working directory'
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
(yield)
finally:
os.chdir(prevdir)
|
def save_mrc(path, data, pixel_spacing):
'\n Save data in a mrc-file and set the pixel spacing with the `alterheader` command from IMOD.\n\n Parameters\n ----------\n path : str\n Path of the new file.\n data : array(float)\n The data to save.\n pixel_spacing : float\n The p... |
def remove_files(dir, extension='.mrc'):
"\n Removes all files in a directory with the given extension.\n\n Parameters\n ----------\n dir : str\n The directory to clean.\n extension : str\n The file extension. Default: ``'.mrc'``\n "
files = glob(join(dir, ('*' + extension)))
... |
def modify_newst(path, bin_factor):
'\n Modifies the bin-factor of a given newst.com file.\n\n Note: This will overwrite the file!\n\n Parameters\n ----------\n path : str\n Path to the newst.com file.\n bin_factor : int\n The new bin-factor.\n '
f = open(path, 'r')
cont... |
def modify_ctfcorrection(path, bin_factor, pixel_spacing):
'\n Modifies the bin-factor of a given ctfcorrection.com file.\n\n Note: This will overwrite the file!\n\n Parameters\n ----------\n path : str\n Path to the ctfcorrection.com file.\n bin_factor : int\n The new bin-factor.\... |
def modify_tilt(path, bin_factor, exclude_angles=[]):
'\n Modifies the bin-factor and exclude-angles of a given tilt.com file.\n\n Note: This will overwrite the file!\n\n Parameters\n ----------\n path : str\n Path to the tilt.com file.\n bin_factor : int\n The new bin-factor.\n ... |
def modify_com_scripts(path, bin_factor, pixel_spacing, exclude_angles=[]):
'\n Modifies the bin-factor and exclude-angles of the newst.com, ctfcorrection.com and tilt.com scripts.\n\n Note: This will overwrite the files!\n\n Parameters\n ----------\n path : str\n Path to the parent director... |
def reconstruct_tomo(path, name, dfix, init, volt=300, rotate_X=True):
'\n Reconstruct a tomogram with IMOD-com scripts. This also applies mtffilter after ctfcorrection.\n\n A reconstruction log will be placed in the reconstruction-directory.\n\n Parameters\n ----------\n path : str\n Path t... |
def get_datasets():
return [ousidhoum2019.Ousidhoum2019(), mulki2019.Mulki2019(), mubarak2017twitter.Mubarak2017twitter(), mubarak2017aljazeera.Mubarak2017aljazeera(), davidson2017.Davidson2017(), gibert2018.Gibert2018(), gao2018.Gao2018(), chung2019.Chung2019(), qian2019.Qian2019(), waseem2016.Waseem2016(), jha2... |
def get_dataset_by_name(name):
all_datasets = get_datasets()
return next(filter((lambda dataset: (dataset.name == name)), all_datasets), None)
|
class Albadi2018(dataset.Dataset):
name = 'albadi2018'
url = 'https://github.com/nuhaalbadi/Arabic_hatespeech/archive/refs/heads/master.zip'
hash = '7f7d87384b4b715655ec0e2d329bc234bbc965ad116290f2e2d0b11e26e272b3'
files = [{'name': 'albadi2018ar_train.csv', 'language': 'ar', 'type': 'training', 'plat... |
class Alfina2017(dataset.Dataset):
name = 'alfina2017'
url = 'https://github.com/ialfina/id-hatespeech-detection/raw/master/IDHSD_RIO_unbalanced_713_2017.txt'
hash = '4ee1d9cc1f1fdd27fb4298207fabb717f4e09281bd68fa5dcbcf720d75f1d4ed'
files = [{'name': 'alfina2017id.csv', 'language': 'id', 'type': 'trai... |
class Basile2019(dataset.Dataset):
name = 'basile2019'
url = 'https://github.com/cicl2018/HateEvalTeam/raw/master/Data%20Files/Data%20Files/%232%20Development-English-A/train_dev_en_merged.tsv'
hash = 'fdd34bf56f0afa744ee7484774d259d83a756033cd8049ded81bd55d2fcb1272'
files = [{'name': 'basile2019en.cs... |
class Bretschneider2016lol(dataset.Dataset):
name = 'bretschneider2016lol'
url = 'http://ub-web.de/research/resources/lol_anonymized.zip'
hash = '901e0d51428f34b94bf6b3f59b0e9cf71dabe94fc74fd81fd1e9be199d2902bc'
files = [{'name': 'bretschneider2016en_lol.csv', 'language': 'en', 'type': 'training', 'pl... |
class Bretschneider2016wow(dataset.Dataset):
name = 'bretschneider2016wow'
url = 'http://www.ub-web.de/research/resources/wow_anonymized.zip'
hash = '0f5d67879306cd67154c31583b6e8750b9290f54c0065cc8cdf11ab6a8d1a26d'
files = [{'name': 'bretschneider2016en_wow.csv', 'language': 'en', 'type': 'training',... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.