repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
PT-MAP-sf
PT-MAP-sf-master/methods/baselinetrain.py
import backbone import utils import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import torch.nn.functional as F class BaselineTrain(nn.Module): def __init__(self, model_func, num_class, loss_type = 'softmax'): super(BaselineTrain, self).__init__() self.featur...
1,927
33.428571
124
py
PT-MAP-sf
PT-MAP-sf-master/methods/baselinefinetune.py
import backbone import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import torch.nn.functional as F from methods.meta_template import MetaTemplate class BaselineFinetune(MetaTemplate): def __init__(self, model_func, n_way, n_support, loss_type = "dist"): super(Baselin...
4,407
41.796117
124
py
PT-MAP-sf
PT-MAP-sf-master/methods/matchingnet.py
# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate import backbone import torch import torch.nn as nn from torch.autograd import Variable import numpy as np import torch.nn.functional as F from methods.meta_template import MetaTemplate import utils import copy class MatchingN...
3,735
35.627451
199
py
PT-MAP-sf
PT-MAP-sf-master/methods/models/utils.py
import torch.nn as nn import torch import numpy as np def constant_init(module, val, bias=0): nn.init.constant_(module.weight, val) if hasattr(module, 'bias') and module.bias is not None: nn.init.constant_(module.bias, bias) def xavier_init(module, gain=1, bias=0, distribution='normal'): assert d...
2,292
30.847222
73
py
PT-MAP-sf
PT-MAP-sf-master/methods/models/imagenet/resnet.py
import torch.nn as nn # from .utils import load_state_dict_from_url try: from torch.hub import load_state_dict_from_url except ImportError: from torch.utils.model_zoo import load_url as load_state_dict_from_url import torch import numpy as np from models.utils import * __all__ = ['ResNet', 'resnet18', 'resnet3...
19,341
38.880412
117
py
PT-MAP-sf
PT-MAP-sf-master/methods/models/imagenet/mobilenetv2.py
""" Creates a MobileNetV2 Model as defined in: Mark Sandler, Andrew Howard, Menglong Zhu, Andrey Zhmoginov, Liang-Chieh Chen. (2018). MobileNetV2: Inverted Residuals and Linear Bottlenecks arXiv preprint arXiv:1801.04381. import from https://github.com/tonylins/pytorch-mobilenet-v2 """ import math from models.utils i...
34,822
36.892274
130
py
PT-MAP-sf
PT-MAP-sf-master/datasets/cvtransforms.py
from __future__ import division import torch import math import random import cv2 import numpy as np import numbers import types import collections import matplotlib.pyplot as plt from sklearn.preprocessing import minmax_scale import time from turbojpeg import TurboJPEG from jpeg2dct.numpy import load, loads import d...
57,509
36.490222
150
py
PT-MAP-sf
PT-MAP-sf-master/datasets/cvfunctional.py
from __future__ import division import torch import math import random from PIL import Image import cv2 import numpy as np import numbers import types import collections import warnings import matplotlib.pyplot as plt from torchvision.transforms import functional from numpy import r_ from jpeg2dct.numpy import load, lo...
36,212
36.448811
125
py
PT-MAP-sf
PT-MAP-sf-master/datasets/dataloader_imagenet_dct2.py
import os import time import torch from datasets.dataset_imagenet_dct import ImageFolderDCT import datasets.cvtransforms as transforms from datasets import train_y_mean, train_y_std, train_cb_mean, train_cb_std, \ train_cr_mean, train_cr_std from datasets import train_y_mean_upscaled, train_y_std_upscaled, train_cb...
2,237
36.3
114
py
PT-MAP-sf
PT-MAP-sf-master/datasets/dataset_imagenet_dct2.py
# Optimized for DCT # Upsampling in the compressed domain import os import sys import random from datasets.vision import VisionDataset from PIL import Image import cv2 import os.path import numpy as np import torch from turbojpeg import TurboJPEG from datasets import train_y_mean_resized, train_y_std_resized, train_cb_...
12,008
39.16388
112
py
PT-MAP-sf
PT-MAP-sf-master/datasets/vision.py
import os import torch import torch.utils.data as data class VisionDataset(data.Dataset): _repr_indent = 4 def __init__(self, root, transforms=None, transform=None, target_transform=None): if isinstance(root, torch._six.string_classes): root = os.path.expanduser(root) self.root = ...
2,950
35.432099
86
py
PT-MAP-sf
PT-MAP-sf-master/data/additional_transforms.py
# Copyright 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from PIL import ImageEnhance transformtypedict=dict(Brightness=ImageEnhance.Brightness, Contrast=ImageEnhance.Contrast...
850
24.787879
150
py
PT-MAP-sf
PT-MAP-sf-master/data/feature_loader.py
import torch import numpy as np import h5py class SimpleHDF5Dataset: def __init__(self, file_handle = None): if file_handle == None: self.f = '' self.all_feats_dset = [] self.all_labels = [] self.total = 0 else: self.f = file_handle ...
1,293
27.755556
78
py
PT-MAP-sf
PT-MAP-sf-master/data/dataset.py
# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate import torch from PIL import Image import cv2 import json import numpy as np import torchvision.transforms as transforms import os # Optimized for DCT # Upsampling in the compressed domain import sys import random from dataset...
7,665
33.223214
116
py
PT-MAP-sf
PT-MAP-sf-master/data/datamgr.py
# This code is modified from https://github.com/facebookresearch/low-shot-shrink-hallucinate import torch from PIL import Image import numpy as np import torchvision.transforms as transforms import datasets.cvtransforms as transforms_dct import data.additional_transforms as add_transforms from data.dataset import Simp...
8,113
46.729412
152
py
SirenMRI
SirenMRI-main/siren.py
# Based on https://github.com/lucidrains/siren-pytorch import torch from torch import nn from math import sqrt class Sine(nn.Module): """Sine activation with scaling. Args: w0 (float): Omega_0 parameter from SIREN paper. """ def __init__(self, w0=1.): super().__init__() self.w...
4,675
31.472222
128
py
SirenMRI
SirenMRI-main/sirenMRI_2D.py
import argparse import getpass import os import random import sys import torch import util import numpy as np import nibabel as nib from siren import Siren from siren import MLP from training import Trainer from sklearn.preprocessing import MinMaxScaler import pickle import py7zr parser = argparse.ArgumentParser() pa...
8,342
42.453125
137
py
SirenMRI
SirenMRI-main/psnr_3d_slicewise.py
import torch import numpy as np import nibabel as nib from sklearn.preprocessing import MinMaxScaler import pickle import argparse import util parser = argparse.ArgumentParser() parser.add_argument("-p", "--predicted", help="Predicted volume") parser.add_argument("-g", "--ground_truth", help="Ground truth") parser.add...
1,852
31.508772
87
py
SirenMRI
SirenMRI-main/training.py
import torch import tqdm from collections import OrderedDict from util import get_clamped_psnr class Trainer(): def __init__(self, representation, lr=1e-3, print_freq=1): """Model to learn a representation of a single datapoint. Args: representation (siren.Siren): Neural net represent...
2,858
41.671642
115
py
SirenMRI
SirenMRI-main/util.py
import numpy as np import torch from torch._C import dtype from typing import Dict DTYPE_BIT_SIZE: Dict[dtype, int] = { torch.float32: 32, torch.float: 32, torch.float64: 64, torch.double: 64, torch.float16: 16, torch.half: 16, torch.bfloat16: 16, torch.complex32: 32, torch.complex...
4,832
29.980769
99
py
SirenMRI
SirenMRI-main/sirenMRI_3D.py
import scipy.io import argparse import getpass import os import random import torch import util import numpy as np import nibabel as nib from siren import Siren from training import Trainer from sklearn.preprocessing import MinMaxScaler import pickle parser = argparse.ArgumentParser() parser.add_argument("-ld", "--lo...
4,867
34.532847
122
py
pyehr
pyehr-main/test_twostage.py
""" step 1: find the best config combination (outcome/los) of the same model step 2: get the prediction results step 3: calculate the metric """ import pandas as pd import numpy as np import lightning as L import torch from datasets.loader.datamodule import EhrDataModule from datasets.loader.load_los_info import get_...
5,913
44.145038
196
py
pyehr
pyehr-main/ml_tune.py
import hydra import lightning as L from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint from lightning.pytorch.loggers import CSVLogger, WandbLogger from omegaconf import DictConfig, OmegaConf import wandb from datasets.loader.datamodule import EhrDataModule from datasets.loader.load_los_info import ...
2,482
36.621212
134
py
pyehr
pyehr-main/dl_tune.py
import hydra import lightning as L from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint from lightning.pytorch.loggers import CSVLogger, WandbLogger from omegaconf import DictConfig, OmegaConf import wandb from datasets.loader.datamodule import EhrDataModule from datasets.loader.load_los_info import ...
3,058
39.786667
163
py
pyehr
pyehr-main/train.py
import lightning as L from lightning.pytorch.callbacks import EarlyStopping, ModelCheckpoint from lightning.pytorch.loggers import CSVLogger from configs.dl import dl_best_hparams from configs.experiments import experiments_configs from configs.ml import ml_best_hparams from datasets.loader.datamodule import EhrDataMo...
3,519
43.556962
157
py
pyehr
pyehr-main/models/stagenet.py
from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.utils.rnn as rnn_utils from models.utils import get_last_visit class StageNetLayer(nn.Module): """StageNet layer. Paper: Stagenet: Stage-aware neural networks for health risk pr...
10,710
36.714789
207
py
pyehr
pyehr-main/models/xgboost.py
from xgboost import XGBClassifier, XGBRegressor class XGBoost(): def __init__(self, **params): """params is a dict seed: int, random seed n_estimators: int, number of trees learning_rate: float, learning rate max_depth: int, depth of trees """ task = params[...
1,584
39.641026
195
py
pyehr
pyehr-main/models/lstm.py
from torch import nn class LSTM(nn.Module): def __init__(self, input_dim, hidden_dim, act_layer=nn.GELU, drop=0.0, **kwargs): super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.proj = nn.Linear(input_dim, hidden_dim) self.act = act_layer() ...
503
30.5
105
py
pyehr
pyehr-main/models/adacare.py
from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils from models.utils import get_last_visit class Sparsemax(nn.Module): """Sparsemax function.""" def __init__(self, dim=None): super(Sparsemax, self).__init__() self.dim = ...
10,099
33.827586
148
py
pyehr
pyehr-main/models/mcgru.py
import torch from torch import nn class MCGRU(nn.Module): def __init__(self, lab_dim, demo_dim, hidden_dim: int=32, feat_dim: int=8, act_layer=nn.GELU, drop=0.0, **kwargs): super().__init__() self.lab_dim = lab_dim self.demo_dim = demo_dim self.hidden_dim = hidden_dim self.f...
1,488
38.184211
118
py
pyehr
pyehr-main/models/gru.py
from torch import nn class GRU(nn.Module): def __init__(self, input_dim, hidden_dim, act_layer=nn.GELU, drop=0.0, **kwargs): super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.proj = nn.Linear(input_dim, hidden_dim) self.act = act_layer() ...
499
30.25
103
py
pyehr
pyehr-main/models/mlp.py
from torch import nn class MLP(nn.Module): def __init__(self, input_dim, hidden_dim, act_layer=nn.GELU, drop=0.0, **kwargs): super().__init__() self.input_dim = input_dim self.hidden_dim = hidden_dim self.proj = nn.Linear(input_dim, hidden_dim) self.act = act_layer() ...
585
26.904762
85
py
pyehr
pyehr-main/models/utils.py
import torch def generate_mask(seq_lens): """Generates a mask for the sequence. Args: seq_lens: [batch size] (max_len: int) Returns: mask: [batch size, max_len] """ max_len = torch.max(seq_lens).to(seq_lens.device) mask = torch.arange(max_len).expand(len(seq_lens), ma...
1,490
28.82
91
py
pyehr
pyehr-main/models/heads.py
import torch from torch import nn class MultitaskHead(nn.Module): def __init__(self, hidden_dim, output_dim, act_layer=nn.GELU, drop=0.0): super(MultitaskHead, self).__init__() self.hidden_dim = (hidden_dim,) self.output_dim = (output_dim,) self.act = act_layer() self.outco...
772
29.92
76
py
pyehr
pyehr-main/models/transformer.py
import math from typing import Dict, List, Optional, Tuple import torch from torch import nn class Attention(nn.Module): def forward(self, query, key, value, mask=None, dropout=None): scores = torch.matmul(query, key.transpose(-2, -1)) / math.sqrt(query.size(-1)) if mask is not None: ...
6,829
34.759162
92
py
pyehr
pyehr-main/models/agent.py
from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn from models.utils import get_last_visit class AgentLayer(nn.Module): """Dr. Agent layer. Paper: Junyi Gao et al. Dr. Agent: Clinical predictive model via mimicked second opinions. JAMIA. This layer is used in the Dr. Age...
11,163
35.603279
130
py
pyehr
pyehr-main/models/retain.py
from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils class RETAINLayer(nn.Module): """RETAIN layer. Paper: Edward Choi et al. RETAIN: An Interpretable Predictive Model for Healthcare using Reverse Time Attention Mechanism. NIPS 2016. ...
4,165
34.305085
88
py
pyehr
pyehr-main/models/__init__.py
from .adacare import AdaCare from .agent import Agent from .catboost import CatBoost # ML model from .concare import ConCare from .dt import DT # ML model from .gbdt import GBDT # ML model from .grasp import GRASP from .gru import GRU from .heads import MultitaskHead from .lstm import LSTM from .mlp import MLP from ...
549
26.5
42
py
pyehr
pyehr-main/models/concare.py
import math from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn from models.utils import generate_mask, get_last_visit class FinalAttentionQKV(nn.Module): def __init__( self, attention_input_dim: int, attention_hidden_dim: int, attention_type: str = ...
24,095
33.720461
157
py
pyehr
pyehr-main/models/rnn.py
from typing import Dict, List, Optional, Tuple import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils class RNNLayer(nn.Module): def __init__( self, input_size: int, hidden_size: int, rnn_type: str = "GRU", num_layers: int = 1, dropout: float = 0...
3,584
35.958763
103
py
pyehr
pyehr-main/models/grasp.py
import copy import math import random from typing import Dict, List, Optional, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils from sklearn.neighbors import kneighbors_graph from models.concare import ConCareLayer from models.rnn import RNNLayer from models.utils imp...
10,664
35.030405
162
py
pyehr
pyehr-main/models/tcn.py
from typing import Dict, List, Optional, Tuple import numpy as np import torch import torch.nn as nn import torch.nn.utils.rnn as rnn_utils from torch.nn.utils import weight_norm from models.utils import get_last_visit # From TCN original paper https://github.com/locuslab/TCN class Chomp1d(nn.Module): def __ini...
6,513
31.733668
154
py
pyehr
pyehr-main/metrics/__init__.py
import torch from .binary_classification_metrics import get_binary_metrics from .es import es_score from .osmae import osmae_score from .regression_metrics import get_regression_metrics from .utils import check_metric_is_better def reverse_los(y, los_info): return y * los_info["los_std"] + los_info["los_mean"] ...
2,072
45.066667
255
py
pyehr
pyehr-main/metrics/regression_metrics.py
from torchmetrics.regression import MeanAbsoluteError, MeanSquaredError, R2Score # get regression metrics: mse, mae, rmse, r2 def get_regression_metrics(preds, labels): mse = MeanSquaredError(squared=True) rmse = MeanSquaredError(squared=False) mae = MeanAbsoluteError() r2 = R2Score() mse(preds, ...
590
25.863636
80
py
pyehr
pyehr-main/metrics/binary_classification_metrics.py
import torch from torchmetrics import AUROC, Accuracy, AveragePrecision threshold = 0.5 def get_binary_metrics(preds, labels): accuracy = Accuracy(task="binary", threshold=threshold) auroc = AUROC(task="binary", threshold=threshold) auprc = AveragePrecision(task="binary", threshold=threshold) # conv...
631
26.478261
64
py
pyehr
pyehr-main/datasets/loader/datamodule.py
import os import lightning as L import pandas as pd import torch import torch.utils.data as data class EhrDataset(data.Dataset): def __init__(self, data_path, mode='train'): super().__init__() self.data = pd.read_pickle(os.path.join(data_path,f'{mode}_x.pkl')) self.label = pd.read_pickle(...
2,074
38.150943
137
py
pyehr
pyehr-main/datasets/loader/unpad.py
import torch from torch.nn.utils.rnn import unpad_sequence def unpad_y(y_pred, y_true, lens): raw_device = y_pred.device device = torch.device("cpu") y_pred, y_true, lens = y_pred.to(device), y_true.to(device), lens.to(device) y_pred_unpad = unpad_sequence(y_pred, batch_first=True, lengths=lens) y...
967
41.086957
80
py
pyehr
pyehr-main/pipelines/dl_pipeline.py
import os import lightning as L import torch import torch.nn as nn import models from datasets.loader.unpad import unpad_y from losses import get_loss from metrics import get_all_metrics, check_metric_is_better from models.utils import generate_mask, get_last_visit class DlPipeline(L.LightningModule): def __ini...
6,197
44.573529
113
py
pyehr
pyehr-main/losses/multitask_loss.py
import torch from torch import nn class MultitaskLoss(nn.Module): def __init__(self, task_num=2): super(MultitaskLoss, self).__init__() self.task_num = task_num self.alpha = nn.Parameter(torch.ones((task_num))) self.mse = nn.MSELoss() self.bce = nn.BCELoss() def forwar...
667
32.4
61
py
pyehr
pyehr-main/losses/time_aware_loss.py
import torch from torch import nn class TimeAwareLoss(nn.Module): def __init__(self, decay_rate=0.1, reward_factor=0.1): super(TimeAwareLoss, self).__init__() self.bce = nn.BCELoss(reduction='none') self.decay_rate = decay_rate self.reward_factor = reward_factor def forward(se...
1,133
36.8
102
py
pyehr
pyehr-main/losses/__init__.py
import torch import torch.nn.functional as F from .multitask_loss import get_multitask_loss from .time_aware_loss import get_time_aware_loss def get_loss(y_pred, y_true, task, time_aware=False): if task == "outcome": loss = F.binary_cross_entropy(y_pred, y_true[:, 0]) elif task == "los": loss...
632
29.142857
85
py
CSSL
CSSL-master/backbone/ResNet18.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional a...
7,191
36.264249
112
py
CSSL
CSSL-master/models/ccic.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from torch.optim import Adam from utils.ring_buffer import Ring...
12,414
42.409091
157
py
CSSL
CSSL-master/models/lwf.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from datasets import get_dataset from torch.optim ...
4,297
41.137255
120
py
CSSL
CSSL-master/models/ewc_on.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn import torch.nn.functional a...
3,277
34.247312
112
py
CSSL
CSSL-master/models/der.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from utils.buffer import Buffer from torch.nn import functional...
1,865
34.884615
112
py
CSSL
CSSL-master/models/joint.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from torch.optim import SGD from utils.args import * from mode...
4,217
39.171429
112
py
CSSL
CSSL-master/models/gdumb.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from utils.args import * from models.utils.continual_model impo...
1,915
34.481481
112
py
CSSL
CSSL-master/models/pseudoer.py
import torch from utils.buffer import Buffer from utils.args import * from models.utils.continual_model import ContinualModel from datasets import get_dataset def get_parser() -> ArgumentParser: parser = ArgumentParser(description='Continual learning via' ' Experience Replay...
1,849
33.90566
111
py
CSSL
CSSL-master/models/si.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import torch.nn as nn from utils.args import * fro...
2,544
35.357143
113
py
CSSL
CSSL-master/models/er.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from utils.buffer import Buffer from utils.args im...
1,791
33.461538
112
py
CSSL
CSSL-master/models/icarl.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from copy import deepcopy import torch import torch.nn.function...
8,773
36.982684
112
py
CSSL
CSSL-master/models/utils/continual_model.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch.nn as nn from torch.optim import SGD import torch ...
5,508
36.993103
113
py
CSSL
CSSL-master/datasets/seq_cifar10.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from torchvision.datasets import CIFAR10 import torchvision.tra...
5,250
37.610294
112
py
CSSL
CSSL-master/datasets/utils/continual_dataset.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. from abc import abstractmethod from argparse import Namespace f...
6,677
36.1
112
py
CSSL
CSSL-master/datasets/utils/validation.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from PIL import Image import numpy as np import os...
2,809
35.973684
112
py
CSSL
CSSL-master/utils/main.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import importlib from models import get_all_models from argpars...
1,572
33.195652
112
py
CSSL
CSSL-master/utils/training.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from utils.status import ProgressBar from utils.lo...
5,448
36.840278
112
py
CSSL
CSSL-master/utils/mixup.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch from torch.distributions.beta import Beta def mix...
915
34.230769
112
py
CSSL
CSSL-master/utils/buffer.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import numpy as np from typing import Tuple from t...
5,755
39.535211
112
py
CSSL
CSSL-master/utils/ring_buffer.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch import numpy as np from typing import Tuple from t...
4,989
38.603175
112
py
CSSL
CSSL-master/utils/triplet.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import torch def negative_only_triplet_loss(labels, embedding...
4,282
36.570175
112
py
CSSL
CSSL-master/utils/conf.py
# Copyright 2021-present, Lorenzo Bonicelli, Pietro Buzzega, Matteo Boschini, Angelo Porrello, Simone Calderara. # All rights reserved. # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import random import torch import numpy as np def get_device(...
860
24.323529
112
py
mixture-of-experts
mixture-of-experts-master/setup.py
from setuptools import setup, find_packages setup( name = 'mixture-of-experts', packages = find_packages(), version = '0.2.1', license='MIT', description = 'Sparsely-Gated Mixture of Experts for Pytorch', author = 'Phil Wang', author_email = 'lucidrains@gmail.com', url = 'https://github.com/lucidrains/...
745
30.083333
96
py
mixture-of-experts
mixture-of-experts-master/mixture_of_experts/mixture_of_experts.py
import torch from torch import nn import torch.nn.functional as F import math from inspect import isfunction # constants MIN_EXPERT_CAPACITY = 4 # helper functions def default(val, default_val): default_val = default_val() if isfunction(default_val) else default_val return val if val is not None else defau...
12,926
38.898148
302
py
ExplicitLatentVariables
ExplicitLatentVariables-main/MNIST/mnist_noencode.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pickle from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms import matplotlib.pyplot as plt import os # Custom datasets for train and test sets, used to extract the index with the actua...
8,959
30.660777
156
py
ExplicitLatentVariables
ExplicitLatentVariables-main/MNIST/mnist_vae.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pickle from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms import matplotlib.pyplot as plt import os # Custom datasets for train and test sets, used to extract the index with the actua...
6,465
29.074419
156
py
ExplicitLatentVariables
ExplicitLatentVariables-main/MNIST/mnist_vae_shifted.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pickle from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms import matplotlib.pyplot as plt import os # Custom datasets for train and test sets, used to extract the index with the actua...
7,751
29.761905
156
py
ExplicitLatentVariables
ExplicitLatentVariables-main/MNIST/mnist_noencode_huge.py
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import pickle from torch.utils.data import Dataset, DataLoader from torchvision import datasets, transforms import matplotlib.pyplot as plt import os # Custom datasets for train and test sets, used to extract the index with the actua...
9,119
30.777003
156
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/setup.py
#!/usr/bin/env python from setuptools import setup, find_packages import os,sys sys.path.insert(0, f'{os.path.dirname(__file__)}/cryodrgn') import cryodrgn version = cryodrgn.__version__ setup(name='cryodrgn', version=version, description='cryoDRGN heterogeneous reconstruction', author='Ellen Zhong...
899
23.324324
59
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/testing/test_entropy.py
import numpy as np import sys, os import argparse import pickle from datetime import datetime as dt import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable from torch.distributions import Normal #sys.path.insert(0,os.path.abspath(os.path.dirname(__file__))+'/lib-python')...
1,128
23.021277
79
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/testing/test_translate.py
''' ''' import numpy as np import sys, os import argparse import pickle import matplotlib.pyplot as plt import torch import torch.nn as nn sys.path.insert(0,'../lib-python') import fft import models import mrc from lattice import Lattice imgs,_ = mrc.parse_mrc('data/hand.mrcs') img = imgs[0] D = img.shape[0] ht = f...
791
17.857143
53
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/losses.py
"""Equivariance loss for Encoder""" import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class EquivarianceLoss(nn.Module): """Equivariance loss for SO(2) subgroup.""" def __init__(self, model, D): super().__init__() self.model = model self.D = D ...
1,081
30.823529
85
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/lattice.py
'''Lattice object''' import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from . import utils log = utils.log class Lattice: def __init__(self, D, extent=0.5, ignore_DC=True, device=None): assert D % 2 == 1, "Lattice size must be odd" x0, x1 = np.meshgrid(np.lins...
6,786
38.005747
109
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/dataset.py
import numpy as np import torch from torch.utils import data import os import multiprocessing as mp from multiprocessing import Pool from . import fft from . import mrc from . import utils from . import starfile log = utils.log def load_particles(mrcs_txt_star, lazy=False, datadir=None): ''' Load particle st...
10,068
37.876448
157
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/pose.py
import torch import torch.nn as nn import numpy as np import pickle from . import lie_tools from . import utils log = utils.log class PoseTracker(nn.Module): def __init__(self, rots_np, trans_np=None, D=None, emb_type=None, device=None): super(PoseTracker, self).__init__() rots = torch.tensor(rots...
4,665
39.224138
123
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/ctf.py
import numpy as np import torch from . import utils log = utils.log def compute_ctf(freqs, dfu, dfv, dfang, volt, cs, w, phase_shift=0, bfactor=None): ''' Compute the 2D CTF Input: freqs (np.ndarray) Nx2 or BxNx2 tensor of 2D spatial frequencies dfu (float or Bx1 tensor): DefocusU (Ang...
3,928
34.718182
116
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/lie_tools.py
''' Tools for dealing with SO(3) group and algebra Adapted from https://github.com/pimdh/lie-vae All functions are pytorch-ified ''' import torch from torch.distributions import Normal import numpy as np def map_to_lie_algebra(v): """Map a point in R^N to the tangent space at the identity, i.e. to the Lie Alg...
7,476
33.939252
115
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/models.py
'''Pytorch models''' import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from . import fft from . import lie_tools from . import utils from . import lattice log = utils.log class HetOnlyVAE(nn.Module): # No pose inference def __init__(self, lattice, # Lattice object ...
34,008
40.934649
123
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/z_train.py
import torch import torch.nn as nn import numpy as np import pickle class ZTracker(nn.Module): def __init__(self, zmu, zvar): super(ZTracker, self).__init__() self.zmu = zmu self.zvar = zvar # zvals shape: N x Zdim for each zmu_embed = nn.Embedding(zmu.shap...
1,016
28.911765
76
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/graph_traversal.py
''' Find shortest path along nearest neighbor graph ''' import torch import argparse import pickle import numpy as np import os from heapq import heappush, heappop def add_args(parser): parser.add_argument('data', help='Input z.pkl embeddings') parser.add_argument('--anchors', type=int, nargs='+', required=Tr...
5,822
34.078313
136
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/parse_pose_csparc.py
'''Parse image poses from a cryoSPARC .cs metafile''' import argparse import numpy as np import sys, os import pickle import torch from cryodrgn import lie_tools from cryodrgn import utils log = utils.log def add_args(parser): parser.add_argument('input', help='Cryosparc .cs file') parser.add_argument('--ab...
2,097
30.313433
154
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/train_vae.py
''' Train a VAE for heterogeneous reconstruction with known pose ''' import numpy as np import sys, os import argparse import pickle from datetime import datetime as dt from copy import deepcopy import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader try: import a...
32,280
47.180597
236
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/backproject_voxel.py
''' Backproject cryo-EM images ''' import argparse import numpy as np import sys, os import time import pickle import torch from cryodrgn import utils from cryodrgn import mrc from cryodrgn import fft from cryodrgn import dataset from cryodrgn import ctf from cryodrgn.pose import PoseTracker from cryodrgn.lattice i...
5,925
37.232258
146
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/eval_images.py
''' Evaluate cryoDRGN z and loss for a stack of images ''' import numpy as np import sys, os import argparse import pickle from datetime import datetime as dt import pprint import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from cryodrgn import mrc from cryodrgn...
9,661
46.831683
206
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/z_train.py
import torch import torch.nn as nn import numpy as np import pickle class ZTracker(nn.Module): def __init__(self, z_vals): super(ZTracker, self).__init__() self.zvals = z_vals def get_z_val(self, ind): zval = self.zvals[:, ind, :] return zval def save(self, out_pkl...
414
23.411765
49
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/eval_vol.py
''' Evaluate the decoder at specified values of z ''' import numpy as np import sys, os import argparse import pickle from datetime import datetime as dt import matplotlib.pyplot as plt import pprint import torch from cryodrgn import mrc from cryodrgn import utils from cryodrgn import fft from cryodrgn import lie_to...
6,706
43.125
152
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/build/lib/cryodrgn/commands/train_nn.py
''' Train a NN to model a 3D density map given 2D images with pose assignments ''' import numpy as np import sys, os import argparse import pickle from datetime import datetime as dt import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader try: import apex.amp as a...
15,346
46.221538
207
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/cryodrgn/losses.py
"""Equivariance loss for Encoder""" import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class EquivarianceLoss(nn.Module): """Equivariance loss for SO(2) subgroup.""" def __init__(self, model, D): super().__init__() self.model = model self.D = D ...
1,081
30.823529
85
py
ExplicitLatentVariables
ExplicitLatentVariables-main/CryoDRGNVLT/cryodrgn/cryodrgn/lattice.py
'''Lattice object''' import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from . import utils log = utils.log class Lattice: def __init__(self, D, extent=0.5, ignore_DC=True, device=None): assert D % 2 == 1, "Lattice size must be odd" x0, x1 = np.meshgrid(np.lins...
6,786
38.005747
109
py