code
stringlengths
17
6.64M
def test_sorted_slice_sampler(): batch_size = 16 max_length = (16000 * 5) lengths = [random.randint((16000 * 3), (16000 * 8)) for index in range(1000)] sampler = SortedSliceSampler(lengths, batch_size=batch_size, max_length=max_length) for epoch in range(5): sampler.set_epoch(epoch) ...
def test_sorted_bucketing_sampler(): batch_size = 16 max_length = (16000 * 5) lengths = [random.randint((16000 * 3), (16000 * 8)) for index in range(1000)] sampler = SortedBucketingSampler(lengths, batch_size=batch_size, max_length=max_length, shuffle=False) for epoch in range(5): sampler....
def test_sox_effect(): effects = [['channels', '1'], ['rate', '16000'], ['gain', '-3.0']] with tempfile.NamedTemporaryFile() as file: tensor = torch.randn(1, (16000 * 10)) filename = f'{file.name}.wav' torchaudio.save(filename, tensor, SAMPLE_RATE) (wav1, sr1) = torchaudio.sox_...
def test_specaug_model(): model = FrameLevelLinear(input_size=13, output_size=25, hidden_size=32) model = ModelWithSpecaug(model) assert (model.specaug.apply_time_mask == True) assert (model.specaug.apply_freq_mask == True)
def _class_counter(data_dict): counter = Counter() for (data_id, data) in data_dict.items(): counter.update([data['class_name']]) return counter
@pytest.mark.corpus def test_speech_commands(): env = dotenv_values() corpus = SpeechCommandsV1(env['GSC1'], env['GSC1_TEST']) all_data = corpus.all_data classes = set([value['class_name'] for (key, value) in all_data.items()]) assert (len(classes) == 12), f'{classes}' (train, valid, test) = c...
def test_tokenizer(): char_tokenizer = CharacterTokenizer() phone_tokenizer = default_phoneme_tokenizer() char_text = 'HELLO WORLD' char_text_enc = char_tokenizer.encode(char_text) char_text_dec = char_tokenizer.decode(char_text_enc) assert isinstance(char_text_enc, list) assert (char_text...
def test_version(): s3prl.__version__
def is_same_vocab(vocabs_1, vocabs_2): if (len(vocabs_1) != len(vocabs_2)): return False for (v1, v2) in zip(vocabs_1, vocabs_2): if (v1 != v2): return False return True
@pytest.mark.corpus def test_vocabulary(): config = dotenv_values() corpus = LibriSpeech(config['LibriSpeech']) text_list = corpus.data_dict['train-clean-100']['text_list'] with tempfile.TemporaryDirectory() as directory: logging.info(directory) text_file = os.path.join(directory, 'tex...
@pytest.mark.corpus @pytest.mark.parametrize('use_cache', [False, True]) def test_voxceleb1sid(use_cache): config = dotenv_values() voxceleb1 = Path(config['VoxCeleb1']) if voxceleb1.is_dir(): (train_data, valid_data, test_data) = VoxCeleb1SID(voxceleb1).data_split else: raise ValueErr...
def extract_single_name(name: str, ckpt: str, legacy: bool, output_dir: str, device: str, refresh: bool=False): output_dir: Path = Path(output_dir) output_dir.mkdir(exist_ok=True, parents=True) output_path = str((output_dir / f'{name}.pt').resolve()) if (Path(output_path).is_file() and (not refresh)):...
class Airfoil(BaseDataset): __doc__ = f''' The NASA data set comprises different size NACA 0012 airfoils at various wind tunnel speeds and angles of attack. The span of the airfoil and the observer position were the same in all of the experiments. {BASE_DATASET_DESCRIPTION} Features: ...
class BikeSharingDaily(BaseDataset): __doc__ = f''' Bike sharing systems are new generation of traditional bike rentals where whole process from membership, rental and return back has become automatic. Through these systems, user is able to easily rent a bike from a particular position and return ...
class BikeSharingHourly(BaseDataset): __doc__ = f''' Bike sharing systems are new generation of traditional bike rentals where whole process from membership, rental and return back has become automatic. Through these systems, user is able to easily rent a bike from a particular position and return ...
class Blog(BaseDataset): __doc__ = f''' This data originates from blog posts. The raw HTML-documents of the blog posts were crawled and processed. The prediction task associated with the data is the prediction of the number of comments in the upcoming 24 hours. In order to simulate this situation,...
class Concrete(BaseDataset): __doc__ = f''' Concrete is the most important material in civil engineering. The concrete compressive strength is a highly nonlinear function of age and ingredients. {BASE_DATASET_DESCRIPTION} Features: Cement (float): Kg of cement in an m3 mixtur...
class CPU(BaseDataset): __doc__ = f''' Relative CPU Performance Data, described in terms of its cycle time, memory size, etc. {BASE_DATASET_DESCRIPTION} Features: vendor_name (string): Name of the vendor, 30 unique values model_name (string): Name of the m...
class FacebookComments(BaseDataset): __doc__ = f''' Instances in this dataset contain features extracted from Facebook posts. The task associated with the data is to predict how many comments the post will receive. {BASE_DATASET_DESCRIPTION} Features: page_popularity (int): D...
class FacebookMetrics(BaseDataset): __doc__ = f''' The data is related to posts' published during the year of 2014 on the Facebook's page of a renowned cosmetics brand. {BASE_DATASET_DESCRIPTION} Features: page_likes(int): The total number of likes of the Facebook page at the...
class FishBioconcentration(BaseDataset): __doc__ = f''' This dataset contains manually-curated experimental bioconcentration factor (BCF) for 1058 molecules (continuous values). Each row contains a molecule, identified by a CAS number, a name (if available), and a SMILES string. Additionally, the KOW ...
class FishToxicity(BaseDataset): __doc__ = f''' This dataset was used to develop quantitative regression QSAR models to predict acute aquatic toxicity towards the fish Pimephales promelas (fathead minnow) on a set of 908 chemicals. LC50 data, which is the concentration that causes death in 50% of ...
class ForestFire(BaseDataset): __doc__ = f''' This is a difficult regression task, where the aim is to predict the burned area of forest fires, in the northeast region of Portugal, by using meteorological and other data. {BASE_DATASET_DESCRIPTION} Features: X (float): The...
class GasTurbine(BaseDataset): __doc__ = f''' Data have been generated from a sophisticated simulator of a Gas Turbines (GT), mounted on a Frigate characterized by a COmbined Diesel eLectric And Gas (CODLAG) propulsion plant type. The experiments have been carried out by means of a numerical simu...
class Nanotube(BaseDataset): __doc__ = f''' CASTEP can simulate a wide range of properties of materials proprieties using density functional theory (DFT). DFT is the most successful method calculates atomic coordinates faster than other mathematical approaches, and it also reaches more accurate re...
class Parkinsons(BaseDataset): __doc__ = f''' This dataset is composed of a range of biomedical voice measurements from 42 people with early-stage Parkinson's disease recruited to a six-month trial of a telemonitoring device for remote symptom progression monitoring. The recordings were automatica...
class PowerPlant(BaseDataset): __doc__ = f''' The dataset contains 9568 data points collected from a Combined Cycle Power Plant over 6 years (2006-2011), when the power plant was set to work with full load. Features consist of hourly average ambient variables Temperature (T), Ambient Pressure (AP)...
class Protein(BaseDataset): __doc__ = f''' This is a data set of Physicochemical Properties of Protein Tertiary Structure. The data set is taken from CASP 5-9. There are 45730 decoys and size varying from 0 to 21 armstrong. {BASE_DATASET_DESCRIPTION} Features: F1 (float): ...
class Servo(BaseDataset): __doc__ = f''' Data was from a simulation of a servo system. Ross Quinlan: This data was given to me by Karl Ulrich at MIT in 1986. I didn't record his description at the time, but here's his subsequent (1992) recollection: "I seem to remember that the data was fro...
class SolarFlare(BaseDataset): __doc__ = f''' Each class attribute counts the number of solar flares of a certain class that occur in a 24 hour period. The database contains 3 potential classes, one for the number of times a certain type of solar flare occured in a 24 hour period. Each insta...
class SpaceShuttle(BaseDataset): __doc__ = f''' The motivation for collecting this database was the explosion of the USA Space Shuttle Challenger on 28 January, 1986. An investigation ensued into the reliability of the shuttle's propulsion system. The explosion was eventually traced to the failure...
class Stocks(BaseDataset): __doc__ = f''' There are three disadvantages of weighted scoring stock selection models. First, they cannot identify the relations between weights of stock-picking concepts and performances of portfolios. Second, they cannot systematically discover the optimal combinatio...
class Superconductivity(BaseDataset): __doc__ = f''' This dataset contains data on 21,263 superconductors and their relevant features. The goal here is to predict the critical temperature based on the features extracted. {BASE_DATASET_DESCRIPTION} Features: - number_of_elements (int)...
class TehranHousing(BaseDataset): __doc__ = f''' Data set includes construction cost, sale prices, project variables, and economic variables corresponding to real estate single-family residential apartments in Tehran, Iran. {BASE_DATASET_DESCRIPTION} Features: start_year (int): ...
class Yacht(BaseDataset): __doc__ = f''' Prediction of residuary resistance of sailing yachts at the initial design stage is of a great value for evaluating the ship's performance and for estimating the required propulsive power. Essential inputs include the basic hull dimensions and the boat velo...
def quantile_loss(predictions: np.ndarray, targets: np.ndarray, quantile: float) -> float: 'Quantile loss function.\n\n Args:\n predictions (sequence of floats):\n Model predictions, of shape [n_samples,].\n targets (sequence of floats):\n Target values, of shape [n_samples,...
def smooth_quantile_loss(predictions: np.ndarray, targets: np.ndarray, quantile: float, alpha: float=0.4) -> float: 'The smooth quantile loss function from [1].\n\n Args:\n predictions (sequence of floats):\n Model predictions, of shape [n_samples,].\n targets (sequence of floats):\n ...
class Model(Protocol): def __init__(self, *args, **kwargs): ... def predict(self, X: np.ndarray, **kwargs) -> Tuple[(Union[(float, np.ndarray)], np.ndarray)]: ... def fit(self, X: np.ndarray, y: np.ndarray, **kwargs): ... def __call__(self, X: np.ndarray, **kwargs) -> Tuple...
class BaseTreeQuantileRegressor(BaseDecisionTree): def predict(self, X: np.ndarray, uncertainty: Optional[float]=None, quantiles: Optional[np.ndarray]=None, check_input: bool=True) -> Union[(np.ndarray, Tuple[(np.ndarray, np.ndarray)])]: "Predict regression value for X.\n\n Args:\n X (a...
class QuantileRegressionTree(DecisionTreeRegressor, BaseTreeQuantileRegressor): "A decision tree regressor that provides quantile estimates.\n\n Args:\n criterion (string, optional):\n The function to measure the quality of a split. Supported criteria are\n 'squared_error' for the ...
def weighted_percentile(arr: np.ndarray, quantile: float, weights: Optional[np.ndarray]=None, sorter: Optional[np.ndarray]=None): 'Returns the weighted percentile of an array.\n\n See [1] for an explanation of this concept.\n\n Args:\n arr (array-like):\n Samples at which the quantile shou...
def fix_dot_env_file(): 'Ensures that the .env file exists and contains all desired variables.' env_file_path = Path('.env') env_file_path.touch(exist_ok=True) env_file_lines = env_file_path.read_text().splitlines(keepends=False) env_vars = [line.split('=')[0] for line in env_file_lines] env_v...
def bump_major(): 'Add one to the major version.' (major, _, _) = get_current_version() set_new_version((major + 1), 0, 0)
def bump_minor(): 'Add one to the minor version.' (major, minor, _) = get_current_version() set_new_version(major, (minor + 1), 0)
def bump_patch(): 'Add one to the patch version.' (major, minor, patch) = get_current_version() set_new_version(major, minor, (patch + 1))
def set_new_version(major: int, minor: int, patch: int): 'Sets a new version.\n\n Args:\n major (int):\n The major version. This only changes when the code stops being backwards\n compatible.\n minor (int):\n The minor version. This changes when a backwards compat...
def get_current_version() -> Tuple[(int, int, int)]: 'Fetch the current version of the package.\n\n Returns:\n triple of ints:\n The current version, separated into major, minor and patch versions.\n\n Raises:\n RuntimeError:\n If the version could not be determined.\n ...
def fetch(category: str, all_cats: list, max_results: int=5, start: int=0): ' Fetch papers from the ArXiv.\n\n INPUT\n category: str\n The name of the ArXiv category. Leave blank to search among all\n categories\n all_cats: list\n A list of all the categories\n ...
def scrape(db_name: str='arxiv_data', data_dir: str='.data', batch_size: int=1000, patience: int=20, overwrite: bool=False, start_from: str=None, log_path: str=None): " Scrape papers from the ArXiv.\n\n INPUT\n db_name: str = 'arxiv_data'\n Name of the SQLite databse where the data will be st...
class BatchWrapper(): ' Wrap a torchtext data iterator. ' def __init__(self, data_iter, vectors: str, cats: list): self.data_iter = data_iter self.batch_size = data_iter.batch_size self.vectors = vectors self.cats = cats def __iter__(self): for batch in self.data_...
def preprocess_data(tsv_fname: str='arxiv_data', txt_fname: str='preprocessed_docs.txt', data_dir: str='.data', batch_size: int=1000): " \n Preprocess text data. This merges titles and abstracts and separates \n tokens by spaces. It saves this into a text file and also saves a\n dataframe with all the ca...
def load_data(tsv_fname: str='arxiv_data_pp', data_dir: str='.data', batch_size: int=32, split_ratio: float=0.95, random_seed: int=42, vectors: str='fasttext') -> tuple: " \n Loads the preprocessed data, tokenises it, builds a vocabulary,\n splits into a training- and validation set, numeralises the texts,\...
class ArXivDatabase(): " A SQLite databse for storing ArXiv papers. \n \n INPUT\n name: str = 'arxiv_data.db'\n Name of the database\n data_dir: str = '.data'\n Folder which contains the database\n " def __init__(self, name: str='arxiv_data.db', data_dir: str='.da...
def end2end(mcat_ratio: float, epochs: int, dim: int, nlayers: int, fname: str, gpu: bool, name: str, lr: float, batch_size: int, split_ratio: float, vectors: str, data_dir: str, pbar_width: int, wandb: bool, boom_dim: int, dropout: float, ema: float, overwrite_model: bool) -> str: ' Loads the data, preprocesses ...
def predict(model, title: str, abstract: str): ' Get the predicted categories from a model, a title and an abstract.\n\n INPUT\n model: torch.nn.Module\n A trained model\n title: str\n The title of a research paper\n abstract: str\n The abstract of a resear...
def evaluate(model, val_dl, output_dict: bool=False): ' Evaluate a model on a validation dataset.\n\n INPUT\n model: torch.nn.Module\n A trained model\n val_dl: torch.utils.data.DataLoader\n A data loader containing a validation dataset\n output_dict: bool = False\n ...
def train_fasttext(txt_fname: str='preprocessed_docs.txt', model_fname: str='fasttext.bin', vec_fname: str='fasttext', data_dir: str='.data', lr: float=0.05, emb_dim: int=100, window: int=5, epochs: int=5, min_count: int=5, min_char_ngram: int=3, max_char_ngram: int=6, neg_samples: int=5, max_word_ngram: int=1): ...
class NestedBCELoss(nn.Module): " A nested form of binary cross entropy.\n\n From the category predictions it pulls out the master category\n predictions, using the utils.cats2mcats function, which enables\n a positive master category prediction even though all individual\n category predictions within...
def train_model(model, train_dl, val_dl, epochs: int=10, lr: float=0.0003, name: str='no_name', mcat_ratio: float=0.1, ema: float=0.99, pbar_width: int=None, use_wandb: bool=True, overwrite_model: bool=True): " Train a given model. \n \n INPUT\n model: torch.nn.Module\n The model we would ...
@app.route('/') def index(): return redirect('/scholarly')
@app.route('/scholarly', methods=['POST', 'GET']) def result(): import json from scholarly.modules import load_model data_dict = (request.form if (request.method == 'POST') else request.args) if (not data_dict): return render_template('scholarly.html') model_path = next(Path('.data').glob(...
def upgrade_config(cfg: CN, to_version: Optional[int]=None) -> CN: '\n Upgrade a config from its current version to a newer version.\n\n Args:\n cfg (CfgNode):\n to_version (int): defaults to the latest version.\n ' cfg = cfg.clone() if (to_version is None): to_version = _C....
def downgrade_config(cfg: CN, to_version: int) -> CN: '\n Downgrade a config from its current version to an older version.\n\n Args:\n cfg (CfgNode):\n to_version (int):\n\n Note:\n A general downgrade of arbitrary configs is not always possible due to the\n different function...
def guess_version(cfg: CN, filename: str) -> int: '\n Guess the version of a partial config where the VERSION field is not specified.\n Returns the version, or the latest if cannot make a guess.\n\n This makes it easier for users to migrate.\n ' logger = logging.getLogger(__name__) def _has(n...
def _rename(cfg: CN, old: str, new: str) -> None: old_keys = old.split('.') new_keys = new.split('.') def _set(key_seq: List[str], val: str) -> None: cur = cfg for k in key_seq[:(- 1)]: if (k not in cur): cur[k] = CN() cur = cur[k] cur[key_s...
class _RenameConverter(): '\n A converter that handles simple rename.\n ' RENAME: List[Tuple[(str, str)]] = [] @classmethod def upgrade(cls, cfg: CN) -> None: for (old, new) in cls.RENAME: _rename(cfg, old, new) @classmethod def downgrade(cls, cfg: CN) -> None: ...
class ConverterV1(_RenameConverter): RENAME = [('MODEL.RPN_HEAD.NAME', 'MODEL.RPN.HEAD_NAME')]
class ConverterV2(_RenameConverter): '\n A large bulk of rename, before public release.\n ' RENAME = [('MODEL.WEIGHT', 'MODEL.WEIGHTS'), ('MODEL.PANOPTIC_FPN.SEMANTIC_LOSS_SCALE', 'MODEL.SEM_SEG_HEAD.LOSS_WEIGHT'), ('MODEL.PANOPTIC_FPN.RPN_LOSS_SCALE', 'MODEL.RPN.LOSS_WEIGHT'), ('MODEL.PANOPTIC_FPN.INST...
class CfgNode(_CfgNode): '\n The same as `fvcore.common.config.CfgNode`, but different in:\n\n 1. Use unsafe yaml loading by default.\n Note that this may lead to arbitrary code execution: you must not\n load a config file from untrusted sources before manually inspecting\n the content of ...
def get_cfg() -> CfgNode: '\n Get a copy of the default config.\n\n Returns:\n a detectron2 CfgNode instance.\n ' from .defaults import _C return _C.clone()
def set_global_cfg(cfg: CfgNode) -> None: '\n Let the global config point to the given cfg.\n\n Assume that the given "cfg" has the key "KEY", after calling\n `set_global_cfg(cfg)`, the key can be accessed by:\n\n .. code-block:: python\n\n from detectron2.config import global_cfg\n prin...
def configurable(init_func): '\n Decorate a class\'s __init__ method so that it can be called with a CfgNode\n object using the class\'s from_config classmethod.\n\n Examples:\n\n .. code-block:: python\n\n class A:\n @configurable\n def __init__(self, a, b=2, c=3):\n ...
def _get_args_from_config(from_config_func, *args, **kwargs): '\n Use `from_config` to obtain explicit arguments.\n\n Returns:\n dict: arguments to be used for cls.__init__\n ' signature = inspect.signature(from_config_func) if (list(signature.parameters.keys())[0] != 'cfg'): raise...
def _called_with_cfg(*args, **kwargs): '\n Returns:\n bool: whether the arguments contain CfgNode and should be considered\n forwarded to from_config.\n ' if (len(args) and isinstance(args[0], _CfgNode)): return True if isinstance(kwargs.pop('cfg', None), _CfgNode): ...
def list_to_dict(list): '\n\n :param list: input list\n :return: converted dictionary\n ' result_dict = {str(i): val for (i, val) in enumerate(list)} return result_dict
class BaseDataset(Dataset): def __init__(self, root, mode='train', resize_mode=None, resize_shape=None): self.resize_mode = ResizeMode(resize_mode) self.resize_shape = resize_shape self.mode = mode self.root = root self.samples = [] self.create_sample_list() d...
class VideoDataset(BaseDataset): def __init__(self, root, mode='train', resize_mode=None, resize_shape=None, tw=8, max_temporal_gap=8, num_classes=2): self.tw = tw self.max_temporal_gap = max_temporal_gap self.num_classes = num_classes self.videos = [] self.num_frames = {}...
class Davis(VideoDataset): def __init__(self, root, mode='train', resize_mode=None, resize_shape=None, tw=8, max_temporal_gap=8, num_classes=2, imset=None): self.imset = imset self.videos = [] self.num_frames = {} self.num_objects = {} self.shape = {} self.raw_samp...
class FBMSDataset(Davis): def __init__(self, root, mode='train', resize_mode=None, resize_shape=None, tw=8, max_temporal_gap=8, num_classes=2): self.index_length = {} self.gt_frames = {} self.video_frames = {} super(FBMSDataset, self).__init__(root, mode, resize_mode, resize_shape...
def load_augmentors(args, pascal_voc_path): if (args is None): return augmentors = [] if ('occ' in args): augmentors += {'occluders': load_occluders(pascal_voc_path)} return augmentors
def augment(augmentors, aug_classes, tensors): tensors = tensors.copy() if ('occ' in augmentors): assert ('occluders' in aug_classes) tensors = do_occ_aug(aug_classes['occluders'], tensors) return tensors
def do_occ_aug(occluders, tensors, p=0.2): occluded_tensors = tensors.copy() if np.random.choice([True, False], 1, p=[p, (1 - p)]): occluded_tensors = occlude_with_objects(occluded_tensors, occluders) return occluded_tensors
def import_submodules(package_name): package = sys.modules[package_name] for (importer, name, is_package) in pkgutil.walk_packages(package.__path__): if (not importer.path.startswith(package.__path__[0])): continue name_with_package = ((package_name + '.') + name) importlib...
def generate_clip_from_image(raw_frame, raw_mask, temporal_window, **kwargs): '\n\n :param raw_frame: The frame to be augmented: h x w x 3\n :param raw_mask: h x w x 1\n :param temporal_window: Number of frames in the output clip\n :return: clip_frames - list of frames with values 0-255\n clip_masks...
class VisalDataset(Davis): def __init__(self, root, mode='train', resize_mode=None, resize_shape=None, tw=8, max_temporal_gap=8, num_classes=2, imset=None): self.gt_frames = {} self.video_frames = {} super(VisalDataset, self).__init__(root, mode, resize_mode, resize_shape, tw, max_tempora...
class YoutubeVOS(VideoDataset): def __init__(self, root, mode='train', resize_mode=None, resize_shape=None, tw=8, max_temporal_gap=8, num_classes=2): self.videos = [] self.num_frames = {} self.num_objects = {} self.shape = {} self.raw_samples = [] self.video_frames...
def get_inference_engine(cfg): engines = all_subclasses(BaseInferenceEngine) try: class_index = [cls.__name__ for cls in engines].index(cfg.INFERENCE.ENGINE) except: raise ValueError('Inference engine {} not found.'.format(cfg.INFERENCE.ENGINE)) engine = list(engines)[class_index] ...
class Trainer(): def __init__(self, args, port): cfg = get_cfg() cfg.merge_from_file(args.config) self.cfg = cfg self.port = port assert os.path.exists('saved_models'), 'Create a path to save the trained models: <default: ./saved_models> ' self.model_dir = os.path....
def register_interrupt_signals(trainer): signal.signal(signal.SIGHUP, trainer.backup_session) signal.signal(signal.SIGINT, trainer.backup_session) signal.signal(signal.SIGQUIT, trainer.backup_session) signal.signal(signal.SIGILL, trainer.backup_session) signal.signal(signal.SIGTRAP, trainer.backup...
class DecoderWithEmbedding(Decoder3d): def __init__(self, n_classes=2, e_dim=64, add_spatial_coord=True): super(DecoderWithEmbedding, self).__init__(n_classes) self.embedding_head = NonlocalOffsetEmbeddingHead(256, 128, e_dim, downsampling_factor=2, add_spatial_coord=add_spatial_coord) def f...
class DecoderSegmentEmbedding(DecoderWithEmbedding): def __init__(self, n_classes=2, e_dim=64): super(DecoderSegmentEmbedding, self).__init__(n_classes=n_classes, e_dim=e_dim) self.con1x1 = nn.Conv3d(e_dim, 256, kernel_size=1, padding=1) def forward(self, r5, r4, r3, r2, support): x ...
class DecoderEmbedding(Decoder3d): def __init__(self, n_classes=2, e_dim=3, add_spatial_coord=True, scale=0.5): super(DecoderEmbedding, self).__init__(n_classes=n_classes) self.RF4 = Refine3dConvTranspose(1024, 256) self.RF3 = Refine3dConvTranspose(512, 256) self.RF2 = Refine3dCon...
class DecoderLight(Decoder3d): def __init__(self, n_classes=2, conv_t=False): super(DecoderLight, self).__init__(n_classes=n_classes) self.RF4 = Refine3dLight(1024, 256, conv_t=conv_t) self.RF3 = Refine3dLight(512, 256, conv_t=conv_t) self.RF2 = Refine3dLight(256, 256, conv_t=conv...
class DecoderMultiClass(Decoder3d): def __init__(self, n_classes=2, conv_t=False): super(DecoderMultiClass, self).__init__(n_classes=n_classes) self.pred_fg = nn.Conv3d(256, 2, kernel_size=3, padding=1, stride=1) def forward(self, r5, r4, r3, r2, support): x = self.GC(r5) r =...
class MultiScaleDecoder(Decoder3d): def __init__(self, n_classes=2, add_spatial_coord=True): super(MultiScaleDecoder, self).__init__(n_classes) self.convG1 = nn.Conv3d(2048, 256, kernel_size=3, padding=1) self.embedding_head = MultiscaleCombinedHeadLongTemporalWindow(256, n_classes, True,...
class Resnet3dEmbeddingMultiDecoder(Resnet3d): def __init__(self, tw=8, sample_size=112, e_dim=7, decoders=None): super(Resnet3dEmbeddingMultiDecoder, self).__init__(tw=tw, sample_size=sample_size) resnet = resnet50_no_ts(sample_size=sample_size, sample_duration=tw) self.encoder = Encoder...
class Resnet3dChannelSeparated_ir(Resnet3dEmbeddingMultiDecoder): def __init__(self, tw=16, sample_size=112, e_dim=7, n_classes=2, decoders=None): decoders = ([Decoder3d(n_classes=n_classes), DecoderEmbedding(n_classes=e_dim)] if (decoders is None) else decoders) super(Resnet3dChannelSeparated_ir...
class Resnet3dCSNiRSameDecoders(Resnet3dEmbeddingMultiDecoder): def __init__(self, tw=16, sample_size=112, e_dim=7): super(Resnet3dCSNiRSameDecoders, self).__init__(decoders=[Decoder3d(), Decoder3d(n_classes=e_dim)]) self.encoder = Encoder3d_csn_ir(tw, sample_size)
class Resnet3dCSNiRLight(Resnet3dEmbeddingMultiDecoder): def __init__(self, tw=16, sample_size=112, e_dim=7): super(Resnet3dCSNiRLight, self).__init__(decoders=[DecoderLight(), DecoderLight(n_classes=e_dim, conv_t=True)]) self.encoder = Encoder3d_csn_ir(tw, sample_size)
class Resnet3dCSNiRMultiScale(Resnet3d): def __init__(self, tw=16, sample_size=112, e_dim=7, add_spatial_coord=True): super(Resnet3dCSNiRMultiScale, self).__init__() self.encoder = Encoder3d_csn_ir(tw, sample_size) self.decoder = MultiScaleDecoder(add_spatial_coord=add_spatial_coord) ...