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 |
|---|---|---|---|---|---|---|
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/word-embeddings/train_baseline_de_bpemb_fasttext.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
BytePairEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.ColumnCorpus(data_folder=Path("... | 1,701 | 26.901639 | 93 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/flair-embeddings/train_baseline_de_hh.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.ColumnCorpus(data_folder=Path("../... | 1,724 | 26.822581 | 93 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/flair-embeddings/train_baseline_de_default.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.ColumnCorpus(data_folder=Path("../... | 1,705 | 26.516129 | 93 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/flair-embeddings/train_baseline_de_redewiedergabe.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.ColumnCorpus(data_folder=Path("../... | 1,736 | 27.016129 | 93 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/flair-embeddings/train_baseline_de_wz.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.ColumnCorpus(data_folder=Path("../... | 1,724 | 26.822581 | 93 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/flair-embeddings/train_baseline_de_clef.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.ColumnCorpus(data_folder=Path("../... | 1,869 | 26.910448 | 93 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/stacked/train_stacked_with_dev_3.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings,
TransformerWordEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.Col... | 1,893 | 28.59375 | 154 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/stacked/train_stacked_3.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings,
TransformerWordEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.Col... | 1,860 | 28.539683 | 154 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/stacked/train_stacked_meto_with_dev_2.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings,
TransformerWordEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.Col... | 2,057 | 30.181818 | 155 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/stacked/train_stacked_2.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings,
TransformerWordEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.Col... | 2,004 | 29.846154 | 155 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/stacked/train_stacked_meto_2.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings,
TransformerWordEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.Col... | 2,024 | 30.153846 | 155 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2020/stacked/train_stacked_1.py | from pathlib import Path
from typing import List
import torch
import flair.datasets
from flair.data import Corpus
from flair.embeddings import (
TokenEmbeddings,
WordEmbeddings,
StackedEmbeddings,
FlairEmbeddings,
TransformerWordEmbeddings
)
# 1. get the corpus
corpus: Corpus = flair.datasets.Col... | 1,997 | 29.738462 | 154 | py |
clef-hipe | clef-hipe-main/experiments/future/flair-ner-trainer-ft.py | import click
import json
import sys
import flair
import torch
from typing import List
from flair.datasets import ColumnCorpus
from flair.embeddings import (
TokenEmbeddings,
StackedEmbeddings,
TransformerWordEmbeddings
)
from flair import set_seed
from flair.models import SequenceTagger
from flair.traine... | 3,476 | 28.466102 | 148 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2022/flair-fine-tuner-kb.py | import click
import json
import sys
import flair
import torch
from typing import List
from flair.data import MultiCorpus
from flair.datasets import ColumnCorpus, NER_HIPE_2022
from flair.embeddings import (
TokenEmbeddings,
StackedEmbeddings,
)
from flair import set_seed
from flair.models import SequenceTagg... | 4,042 | 29.398496 | 155 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2022/flair-evaluator.py | import click
import json
import sys
import flair
import torch
from typing import List
from flair.data import MultiCorpus
from flair.datasets import ColumnCorpus, NER_HIPE_2022
from flair.embeddings import (
TokenEmbeddings,
StackedEmbeddings,
TransformerWordEmbeddings
)
from flair import set_seed
from fl... | 1,494 | 26.685185 | 139 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2022/flair-fine-tuner-multistage.py | import click
import json
import sys
import flair
import torch
from typing import List
from flair.data import MultiCorpus
from flair.datasets import ColumnCorpus, NER_HIPE_2022
from flair.embeddings import (
TokenEmbeddings,
StackedEmbeddings,
TransformerWordEmbeddings
)
from flair import set_seed
from fl... | 3,229 | 30.666667 | 170 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2022/flair-we-trainer.py | import click
import json
import sys
import flair
import torch
from typing import List
from flair.data import MultiCorpus
from flair.datasets import ColumnCorpus, NER_HIPE_2022
from flair.embeddings import (
FastTextEmbeddings
)
from flair import set_seed
from flair.models import SequenceTagger
from flair.trainer... | 2,796 | 29.736264 | 144 | py |
clef-hipe | clef-hipe-main/experiments/clef-hipe-2022/flair-fine-tuner.py | import click
import json
import sys
import flair
import torch
from typing import List
from flair.data import MultiCorpus
from flair.datasets import ColumnCorpus, NER_HIPE_2022
from flair.embeddings import (
TokenEmbeddings,
StackedEmbeddings,
TransformerWordEmbeddings
)
from flair import set_seed
from fl... | 4,687 | 32.726619 | 152 | py |
TA | TA-main/attack_mask.py | from foolbox.attacks.blended_noise import LinearSearchBlendedUniformNoiseAttack
from foolbox.attacks.base import MinimizationAttack, get_criterion
import sys
import torch_dct
from attack_utils import *
import time
global device
# initialize an adversarial example with uniform noise
def get_x_adv(x_o: torch.Tensor, l... | 10,756 | 41.686508 | 268 | py |
TA | TA-main/TA.py | import json
import torch
import os
import argparse
import time
import attack_mask as attack
from attack_utils import get_model, read_imagenet_data_specify, save_results
from foolbox.distances import l2
import numpy as np
from PIL import Image
import torch_dct
device = torch.device('cuda:0' if torch.cuda.is_available()... | 3,892 | 26.223776 | 110 | py |
TA | TA-main/attack_utils.py | import torch
import random
import numpy as np
from PIL import Image
import json
import os
import pandas as pd
from foolbox import PyTorchModel
import torchvision.models as models
from datetime import datetime
import pandas as pd
def get_model(args,device):
model_name = args.model_name
if model_name == 'resnet-... | 4,368 | 33.952 | 80 | py |
LMEDR | LMEDR-main/evaluation_PersonaChat.py | import random
import logging
from pprint import pformat
from collections import defaultdict
from functools import partial
import torch
from parlai.core.agents import Agent
from parlai.scripts.eval_model import setup_args as base_setup_args
from ParlAI.projects.convai2.eval_hits import eval_hits, setup_args as setup_arg... | 10,640 | 47.368182 | 162 | py |
LMEDR | LMEDR-main/train_dstc.py | import sys
import logging
import os
import argparse
from transformers import BartTokenizer, AdamW, WEIGHTS_NAME, CONFIG_NAME
from model.modeling_bart import LMEDRModel
import torch
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
from torch.nn.parallel import DistributedDataParallel
import time... | 17,322 | 45.818919 | 147 | py |
LMEDR | LMEDR-main/dstc_generate.py | import sys
import logging
import os
import argparse
from transformers import BartTokenizer
from model.modeling_bart import LMEDRModel
import torch
import numpy as np
import json
from tqdm import tqdm
from collections import defaultdict
from pprint import pformat
from build_dstc import build_test
def init_config():
... | 4,480 | 35.729508 | 106 | py |
LMEDR | LMEDR-main/eval_PersonaChat_build.py | from torch.nn.utils.rnn import pad_sequence
import torch
import numpy as np
def create_encoder_input(per, history, query_id, res_id, latent_id, persona_id, sep_id, eos_id):
encoder_input_ids = []
per_input_ids = [latent_id] + [persona_id]
for x in per:
per_input_ids += x + [sep_id]
encoder_in... | 2,748 | 40.029851 | 121 | py |
LMEDR | LMEDR-main/build_data_PersonaChat.py | import random
from tqdm import tqdm
import torch
from collections import defaultdict
from torch.nn.utils.rnn import pad_sequence
import numpy as np
import json
def get_token_id(tokenizer):
bos_id = tokenizer.bos_token_id
eos_id = tokenizer.eos_token_id
pad_id = tokenizer.pad_token_id
sep_id = tokeniz... | 10,602 | 41.412 | 121 | py |
LMEDR | LMEDR-main/build_dstc.py | from tqdm import trange, tqdm
import torch
from collections import defaultdict
from torch.nn.utils.rnn import pad_sequence
import numpy as np
import json
import jsonlines
def get_token_id(tokenizer):
bos_id = tokenizer.bos_token_id
eos_id = tokenizer.eos_token_id
pad_id = tokenizer.pad_token_id
sep_id... | 10,338 | 41.72314 | 124 | py |
LMEDR | LMEDR-main/train_PersonaChat.py | import sys
import logging
import os
import argparse
from transformers import BartTokenizer, AdamW, WEIGHTS_NAME, CONFIG_NAME
from model.modeling_bart import LMEDRModel
import torch
import numpy as np
from torch.utils.data import DataLoader, TensorDataset
from torch.nn.parallel import DistributedDataParallel
from ignite... | 20,240 | 50.9 | 151 | py |
LMEDR | LMEDR-main/other/generation_utils.py | # coding=utf-8
# Copyright 2020 The Google AI Language Team Authors, Facebook AI Research authors and The HuggingFace Inc. team.
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... | 144,097 | 54.401 | 201 | py |
LMEDR | LMEDR-main/model/memory_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class MemoryLoss(nn.Module):
def __init__(self, eps=1e-8):
super(MemoryLoss, self).__init__()
self.eps = eps
def forward(self, memory1, memory2):
memory1 = F.normalize(memory1)
memory2 = F.normalize(memory2)
... | 473 | 22.7 | 53 | py |
LMEDR | LMEDR-main/model/modeling_bart.py | # coding=utf-8
# Copyright 2021 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/... | 81,570 | 42.597541 | 159 | py |
varpool | varpool-main/run_all_fits.py | import argparse
import os
from multiprocessing import Pool
import torch
from itertools import product
import yaml
import pandas as pd
parser = argparse.\
ArgumentParser(description='Runs a single fit experiment in parallel over a set of subtypes and dataset seeds.')
parser.add_argument('--feats_top_dir',
... | 8,576 | 36.618421 | 116 | py |
varpool | varpool-main/scripts/redo_save_preds.py | """
This script trains a multi-instance learning network to solve a supervised task e.g. classification or survival prediction.
"""
import pandas as pd
from tqdm import tqdm
import os
import argparse
from time import time
from datetime import datetime
import yaml
import numpy as np
import torch
import torch.nn as nn
f... | 27,532 | 37.888418 | 488 | py |
varpool | varpool-main/scripts/run_tune.py | import argparse
import pathlib
import os
from functools import partial
from multiprocessing import Pool
from sklearn.model_selection import ParameterGrid
import numpy as np
import torch
from var_pool.nn.tune_utils import run_train
from var_pool.script_utils import parse_mil_task_yaml
parser = argparse.\
ArgumentP... | 9,258 | 35.167969 | 376 | py |
varpool | varpool-main/scripts/baseline_cox.py | """
Simple idea from Richard. Extract mean embeddings from WSI and train linear Cox
"""
import pandas as pd
import os
import argparse
from time import time
import numpy as np
import torch
from sksurv.linear_model import CoxPHSurvivalAnalysis
from sksurv.util import Surv
from var_pool.nn.datasets.BagDatasets import B... | 5,935 | 36.808917 | 172 | py |
varpool | varpool-main/scripts/eval.py | import pandas as pd
import os
import argparse
from time import time
import yaml
import torch
from torch.utils.data import DataLoader
from var_pool.nn.train.loops import eval_loop
from var_pool.nn.stream_evaler import ClfEvaler, DiscreteSurvivalEvaler,\
CoxSurvivalEvaler, RankSurvivalEvaler
from var_pool.nn.datase... | 10,685 | 34.73913 | 180 | py |
varpool | varpool-main/scripts/train.py | """
This script trains a multi-instance learning network to solve a supervised task e.g. classification or survival prediction.
"""
import pandas as pd
from tqdm import tqdm
import os
import argparse
from time import time
from datetime import datetime
import yaml
import numpy as np
import torch
import torch.nn as nn
f... | 34,685 | 37.327072 | 488 | py |
varpool | varpool-main/scripts/visualize.py | import os
import argparse
import torch
from var_pool.script_utils import parse_mil_task_yaml
from var_pool.mhist.get_model_from_args import get_model
from var_pool.gpu_utils import assign_free_gpus
from var_pool.file_utils import join_and_make
from var_pool.nn.datasets.VisualDatasets import VisualDataset
from var_po... | 7,762 | 39.857895 | 180 | py |
varpool | varpool-main/tcga_scripts/viz_top_patches-extremes_only.py | import argparse
from itertools import chain
import os
import numpy as np # TODO: this fixes weird import error with torch
import torch
from var_pool.mhist.get_model_from_args import get_model
from var_pool.mhist.tcga_agg_slides_to_patient_level import \
tcga_agg_slides_to_patient_level
from var_pool.file_utils i... | 6,280 | 35.730994 | 169 | py |
varpool | varpool-main/tcga_scripts/viz_top_patches.py | import argparse
from itertools import chain
import os
import numpy as np # this fixes weird import error with torch
import torch
from tqdm import tqdm
from var_pool.mhist.get_model_from_args import get_model
from var_pool.mhist.tcga_agg_slides_to_patient_level import \
tcga_agg_slides_to_patient_level
from var_p... | 6,651 | 36.581921 | 169 | py |
varpool | varpool-main/var_pool/gpu_utils.py | import subprocess
import numpy as np
import torch
import time
def assign_free_gpus(max_gpus=3):
"""
Identify least-utilized GPU and return the corresponding ID
Parameters
----------
max_gpus (int, optional): Max GPUs is the maximum number of gpus to assign.
Defaults ... | 1,513 | 34.209302 | 109 | py |
varpool | varpool-main/var_pool/nn/seeds.py | import os
import numpy as np
import torch
import random
def set_seeds(device, seed=1):
"""
Sets seeds to get reproducible experiments.
Parametrs
---------
device: torch.device
The device we are using.
seed: int
The seed.
"""
random.seed(seed)
os.environ['PYTHONHA... | 623 | 19.8 | 71 | py |
varpool | varpool-main/var_pool/nn/ComparablePairSampler.py | from torch.utils.data import Sampler
from itertools import combinations
import numpy as np
# TODO: add shuffle
class ComparablePairSampler(Sampler):
"""
Iterates over comparable pairs.
Parameters
----------
times: array-like, (n_samples, )
The survival times.
censor: array-like, (n_sa... | 1,674 | 24 | 110 | py |
varpool | varpool-main/var_pool/nn/utils.py | import torch.nn as nn
import torch.optim as optim
def get_network_summary(net):
"""
Prints a summary of neural network including the number of parameters.
Output
----------
summary: str
A text summary of the network.
"""
num_params = 0
num_params_train = 0
summary = str(... | 2,070 | 22.534091 | 78 | py |
varpool | varpool-main/var_pool/nn/SurvRankingLoss.py | import torch.nn as nn
import torch
from itertools import combinations
class SurvRankingLoss(nn.Module):
"""
Implements the surivival ranking loss which approximates the negaive c-index; see Section 3.2 of (Luck et al, 2018) -- but be careful of the typo in their c-index formula.
The c-index for risk sco... | 3,507 | 31.183486 | 175 | py |
varpool | varpool-main/var_pool/nn/CoxLoss.py | import torch.nn as nn
import torch
import numpy as np
from itertools import combinations
class CoxLoss_alternative(nn.Module):
"""
Implements the Cox proportional hazards loss for deep learning models. See Equation (4) of (Katzman et al, 2018) without the L2 term.
Parameters
----------
reduction:... | 5,171 | 31.734177 | 244 | py |
varpool | varpool-main/var_pool/nn/NLLSurvLoss.py | import torch
import torch.nn as nn
class NLLSurvLoss(nn.Module):
"""
The negative log-likelihood loss function for the discrete time to event model (Zadeh and Schmid, 2020).
Code borrowed from https://github.com/mahmoodlab/Patch-GCN/blob/master/utils/utils.py
Parameters
----------
alpha: flo... | 3,987 | 30.904 | 165 | py |
varpool | varpool-main/var_pool/nn/stream_evaler.py | import numpy as np
from scipy.special import softmax, expit
import torch
from warnings import warn
from sklearn.metrics import roc_auc_score,\
accuracy_score, balanced_accuracy_score, f1_score # classification_report
from sksurv.metrics import concordance_index_censored
from var_pool.utils import get_counts_and_... | 15,033 | 30.320833 | 250 | py |
varpool | varpool-main/var_pool/nn/datasets/GraphDatasets.py | """
Dataset for graph neural network. Assumes the Data object has been already created
"""
import torch
from torch_geometric.data import Data
class GraphDataset:
"""
Graph Dataset.
Parameters
----------
fpaths: list of str
list of graph .pt files
y: Dataframe
Dataframe holding... | 3,263 | 27.884956 | 89 | py |
varpool | varpool-main/var_pool/nn/datasets/fixed_bag_size.py | import torch
from torch.utils.data._utils.collate import default_collate
import numpy as np
def to_fixed_size_bag(bag, fixed_bag_size=512):
"""
Takes an input bag and returns a bag of a fixed size through either random subsampling or zero padding.
The random sampling is always done with torch so if you wa... | 4,391 | 30.597122 | 205 | py |
varpool | varpool-main/var_pool/nn/datasets/BagDatasets.py | import h5py
import torch
from torch.utils.data import Dataset
import numpy as np
import pandas as pd
from time import time
from var_pool.file_utils import get_file_names
# TODO: I want to move this to another module for readability, but when
# I do that, class BagDataset(ResponseMixin, Dataset) throws
# a TypeError:... | 13,863 | 31.544601 | 228 | py |
varpool | varpool-main/var_pool/nn/train/GradAccum.py | import numpy as np
class GradAccum:
"""
Calculates loss function divosor for adjusting the loss when training with gradient accumulation.
This object handles the case when number of batches is not divisible by the gradient accumultation and/or the case when the number of samples is not divisible by the ba... | 4,935 | 32.127517 | 181 | py |
varpool | varpool-main/var_pool/nn/train/loops.py | import torch
from tqdm import tqdm
from torch.nn.modules.loss import _WeightedLoss
import torch_geometric
from var_pool.nn.stream_evaler import BaseStreamEvaler
from var_pool.nn.train.GradAccum import GradAccum
# TODO: think through grad accum and nn.DataParallel
# TODO: perhaps add override_sum_to_mean_reduction o... | 9,747 | 32.044068 | 309 | py |
varpool | varpool-main/var_pool/nn/train/EarlyStopper.py | import numpy as np
import os
import torch
from copy import deepcopy
class EarlyStopper:
"""
Checks early stopping criteria and saves a model checkpoint anytime a record is set. Note the model checkpoints are saved everytime a record is set i.e. at the beginning of the patience period.
Parameters
----... | 5,779 | 32.218391 | 261 | py |
varpool | varpool-main/var_pool/nn/train/tests/utils_grad_accum.py | import numpy as np
import torch
from torch.utils.data import DataLoader, Dataset
import torch.nn as nn
import torch.optim as optim
from var_pool.nn.train.GradAccum import GradAccum
def check_GradAccum(n_samples, batch_size, grad_accum):
"""
Checks the GradAccum() object by checking that gradient accumulatio... | 5,001 | 25.188482 | 140 | py |
varpool | varpool-main/var_pool/nn/arch/AttnMIL.py | """
Attention based multiple instance learning architecture.
This code was built off
https://github.com/AMLab-Amsterdam/AttentionDeepMIL/blob/master/model.py
https://github.com/KatherLab/HIA/blob/main/models/model_Attmil.py
https://github.com/mahmoodlab/PORPOISE/blob/master/models/model_attention_mil.py"""
from number... | 11,068 | 32.24024 | 253 | py |
varpool | varpool-main/var_pool/nn/arch/GlobalPoolMIL.py | import torch.nn as nn
import torch
class GlobalPoolMil(nn.Module):
"""
Global pool the bags (e.g. mean pool) the on linear layer.
Parameters
----------
in_feats: int
Feature input dimension.
out_dim: int
Output dimension.
pool: str
Which pooling operation to appl... | 682 | 19.69697 | 62 | py |
varpool | varpool-main/var_pool/nn/arch/utils.py | import torch.nn as nn
def mlp_from_tuple(dims, act='relu'):
"""
Creates a multi-layer perceptron.
Parameters
----------
dims: list of ints
The dimensions of the layers including the input and output layer i.e. there are len(dims) - 1 total layers
act: str
Activation function.... | 819 | 21.162162 | 115 | py |
varpool | varpool-main/var_pool/nn/arch/VarPool.py | """
Variance Pooling + Attention based multiple instance learning architecture.
"""
import torch
import torch.nn as nn
from numbers import Number
import numpy as np
from var_pool.nn.arch.AttnMIL_utils import AttnMILMixin, get_attn_module,\
EncodeAndMultipleAttend
from var_pool.nn.arch.utils import mlp_from_tuple
... | 10,234 | 32.778878 | 216 | py |
varpool | varpool-main/var_pool/nn/arch/AttnMIL_utils.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from var_pool.nn.arch.AttnMIL import Attn, GatendAttn
class AttnMILMixin:
"""
Mixin for attention MIL modules
Parameters
----------
enc_and_attend: nn.Module -> attn_scores,
"""
def compute_bag_feats_and_attn_scores(sel... | 6,936 | 29.831111 | 253 | py |
varpool | varpool-main/var_pool/nn/arch/SumMIL.py | """
Sum MIL architecture from Deep Set framework
This code was built off
https://github.com/AMLab-Amsterdam/AttentionDeepMIL/blob/master/model.py
https://github.com/KatherLab/HIA/blob/main/models/model_Attmil.py
https://github.com/mahmoodlab/PORPOISE/blob/master/models/model_attention_mil.py"""
from numbers import Num... | 10,691 | 34.759197 | 253 | py |
varpool | varpool-main/var_pool/nn/arch/VarPool_switch.py | """
Variance Pooling + Attention based multiple instance learning architecture.
"""
import torch
import torch.nn as nn
from var_pool.nn.arch.AttnMIL_utils import AttnMILMixin, get_attn_module,\
EncodeAndMultipleAttend
from var_pool.nn.arch.VarPool import VarPool
class AttnMeanAndVarPoolMIL_with_switch(AttnMILMix... | 8,427 | 34.263598 | 190 | py |
varpool | varpool-main/var_pool/nn/arch/PatchGCN.py | """
PatchGCN architecture from Richard's code
(TODO) Still work in the progress
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GENConv, DeepGCNLayer
# from torch_geometric.transforms.normalize_features import NormalizeFeatures
from var_pool.nn.arch.AttnM... | 12,746 | 31.768638 | 124 | py |
varpool | varpool-main/var_pool/viz/top_attn.py | import numpy as np
import pandas as pd
import h5py
from pathlib import Path
import os
import torch
from openslide import open_slide
from var_pool.file_utils import get_file_names
from var_pool.viz.utils import read_region, make_image_grid, get_idxs_largest
def viz_top_attn_patches(model, wsi_fpath, h5_fpath, autogen... | 4,527 | 28.986755 | 115 | py |
varpool | varpool-main/var_pool/viz/var_pool_extremes.py | import pandas as pd
import numpy as np
import os
from itertools import product
from openslide import open_slide
import torch
import matplotlib.pyplot as plt
import seaborn as sns
from var_pool.file_utils import get_file_names, join_and_make
from var_pool.viz.top_attn import load_patient_patch_data
from var_pool.viz.ut... | 14,311 | 33.570048 | 199 | py |
varpool | varpool-main/var_pool/mhist/get_model_with_switch.py | import torch.nn as nn
from var_pool.nn.arch.VarPool_switch import AttnMeanAndVarPoolMIL_with_switch as AMVPool_with_switch
from var_pool.mhist.get_model import _get_head_network
def get_switch_parts(n_bag_feats, encoder_dim, out_dim, n_var_pools,
head_hidden_dim, head_n_hidden_layers,
... | 3,667 | 30.084746 | 100 | py |
varpool | varpool-main/var_pool/mhist/get_model.py | import torch.nn as nn
from warnings import warn
from var_pool.nn.arch.AttnMIL import AttnMeanPoolMIL
from var_pool.nn.arch.VarPool import AttnMeanAndVarPoolMIL
from var_pool.nn.arch.SumMIL import SumMIL, SumVarPoolMIL
from var_pool.nn.arch.PatchGCN import PatchGCN, PatchGCN_varpool, MIL_Graph_FC, MIL_Graph_FC_varpool
... | 15,267 | 31.21097 | 353 | py |
varpool | varpool-main/var_pool/mhist/patch_gcn_arch.py | """
Modules from https://github.com/mahmoodlab/Patch-GCN/
"""
import torch.nn as nn
import torch
import torch.nn.functional as F
class MIL_Attention_FC_surv(nn.Module):
def __init__(self, size_arg="small", dropout=0.25, n_classes=4):
r"""
Attention MIL Implementation
Args:
size... | 3,220 | 33.634409 | 87 | py |
IS-CSE | IS-CSE-main/evaluation.py | import sys
import io, os
import numpy as np
import logging
import argparse
from prettytable import PrettyTable
import torch
import transformers
from transformers import AutoModel, AutoTokenizer
# Set up logger
logging.basicConfig(format='%(asctime)s : %(message)s', level=logging.DEBUG)
# Set PATHs
PATH_TO_SENTEVAL = ... | 8,127 | 38.456311 | 165 | py |
IS-CSE | IS-CSE-main/simcse_to_huggingface.py | """
Convert SimCSE's checkpoints to Huggingface style.
"""
import argparse
import torch
import os
import json
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--path", type=str, help="Path of SimCSE checkpoint folder")
args = parser.parse_args()
print("SimCSE checkpoint -> Hugging... | 1,327 | 29.181818 | 107 | py |
IS-CSE | IS-CSE-main/train.py | import logging
import math
import os
import sys
from dataclasses import dataclass, field
from typing import Optional, Union, List, Dict, Tuple
import torch
import collections
import random
from datasets import load_dataset
import transformers
from transformers import (
CONFIG_MAPPING,
MODEL_FOR_MASKED_LM_MAPP... | 24,484 | 39.205255 | 144 | py |
IS-CSE | IS-CSE-main/simcse/tool.py | import logging
from tqdm import tqdm
import numpy as np
from numpy import ndarray
import torch
from torch import Tensor, device
import transformers
from transformers import AutoModel, AutoTokenizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.preprocessing import normalize
from typing import List... | 12,064 | 41.038328 | 160 | py |
IS-CSE | IS-CSE-main/simcse/trainers.py | import collections
import inspect
import math
import sys
import os
import re
import json
import shutil
import time
import warnings
from pathlib import Path
import importlib.util
from packaging import version
from transformers import Trainer
from transformers.modeling_utils import PreTrainedModel
from transformers.train... | 25,481 | 44.341637 | 149 | py |
IS-CSE | IS-CSE-main/simcse/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
import pdb
import transformers
from transformers import RobertaTokenizer
from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead
from transformers.models.bert.modeling... | 18,496 | 36.826176 | 151 | py |
IS-CSE | IS-CSE-main/SentEval/examples/infersent.py | # Copyright (c) 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.
#
"""
InferSent models. See https://github.com/facebookresearch/InferSent.
"""
from __future__ import absolute_import, division,... | 2,463 | 31 | 92 | py |
IS-CSE | IS-CSE-main/SentEval/examples/bow.py | # Copyright (c) 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.
#
from __future__ import absolute_import, division, unicode_literals
import sys
import io
import numpy as np
import logging
# ... | 3,423 | 29.300885 | 82 | py |
IS-CSE | IS-CSE-main/SentEval/examples/googleuse.py | # Copyright (c) 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.
#
from __future__ import absolute_import, division
import os
import sys
import logging
import tensorflow as tf
import tensorflow... | 2,205 | 31.441176 | 86 | py |
IS-CSE | IS-CSE-main/SentEval/examples/models.py | # Copyright (c) 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.
#
"""
This file contains the definition of encoders used in https://arxiv.org/pdf/1705.02364.pdf
"""
import numpy as np
import t... | 9,875 | 36.12782 | 94 | py |
IS-CSE | IS-CSE-main/SentEval/examples/gensen.py | # Copyright (c) 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.
#
"""
Clone GenSen repo here: https://github.com/Maluuba/gensen.git
And follow instructions for loading the model used in batcher... | 2,429 | 31.4 | 82 | py |
IS-CSE | IS-CSE-main/SentEval/examples/skipthought.py | # Copyright (c) 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.
#
from __future__ import absolute_import, division, unicode_literals
"""
Example of file for SkipThought in SentEval
"""
import ... | 2,048 | 32.048387 | 97 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/engine.py | # Copyright (c) 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.
#
'''
Generic sentence evaluation scripts wrapper
'''
from __future__ import absolute_import, division, unicode_literals
from ... | 6,525 | 49.2 | 139 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/rank.py | # Copyright (c) 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.
#
'''
Image-Caption Retrieval with COCO dataset
'''
from __future__ import absolute_import, division, unicode_literals
import os... | 4,643 | 41.605505 | 129 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/snli.py | # Copyright (c) 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.
#
'''
SNLI - Entailment
'''
from __future__ import absolute_import, division, unicode_literals
import codecs
import os
import io... | 4,577 | 39.157895 | 75 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/utils.py | # Copyright (c) 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.
#
from __future__ import absolute_import, division, unicode_literals
import numpy as np
import re
import inspect
from torch impo... | 2,713 | 27.270833 | 79 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/binary.py | # Copyright (c) 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.
#
'''
Binary classifier and corresponding datasets : MR, CR, SUBJ, MPQA
'''
from __future__ import absolute_import, division, uni... | 3,712 | 38.924731 | 79 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/mrpc.py | # Copyright (c) 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.
#
'''
MRPC : Microsoft Research Paraphrase (detection) Corpus
'''
from __future__ import absolute_import, division, unicode_liter... | 4,202 | 39.028571 | 80 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/probing.py | # Copyright (c) 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.
#
'''
probing tasks
'''
from __future__ import absolute_import, division, unicode_literals
import os
import io
import copy
impo... | 6,786 | 38.459302 | 120 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/sick.py | # Copyright (c) 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.
#
'''
SICK Relatedness and Entailment
'''
from __future__ import absolute_import, division, unicode_literals
import os
import io... | 9,243 | 41.599078 | 80 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/trec.py | # Copyright (c) 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.
#
'''
TREC question-type classification
'''
from __future__ import absolute_import, division, unicode_literals
import os
import... | 3,565 | 38.622222 | 79 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/sst.py | # Copyright (c) 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.
#
'''
SST - binary classification
'''
from __future__ import absolute_import, division, unicode_literals
import os
import io
im... | 3,946 | 39.690722 | 94 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/tools/relatedness.py | # Copyright (c) 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.
#
"""
Semantic Relatedness (supervised) with Pytorch
"""
from __future__ import absolute_import, division, unicode_literals
impo... | 4,552 | 32.725926 | 100 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/tools/validation.py | # Copyright (c) 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.
#
"""
Validation and classification
(train) : inner-kfold classifier
(train, test) : kfold classifier
(train, d... | 10,358 | 40.939271 | 93 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/tools/classifier.py | # Copyright (c) 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.
#
"""
Pytorch Classifier class in the style of scikit-learn
Classifiers include Logistic Regression and MLP
"""
from __future__ ... | 7,737 | 37.118227 | 94 | py |
IS-CSE | IS-CSE-main/SentEval/senteval/tools/ranking.py | # Copyright (c) 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.
#
"""
Image Annotation/Search for COCO with Pytorch
"""
from __future__ import absolute_import, division, unicode_literals
impor... | 15,275 | 41.433333 | 109 | py |
gym-electric-motor | gym-electric-motor-master/setup.py | import setuptools
AUTHORS = [
'Arne Traue', 'Gerrit Book', 'Praneeth Balakrishna',
'Pascal Peters', 'Pramod Manjunatha', 'Darius Jakobeit', 'Felix Book',
'Max Schenke', 'Wilhelm Kirchgässner', 'Oliver Wallscheid',
]
with open('requirements.txt', 'r') as f:
requirements = f.read().splitlines()
with ... | 1,058 | 31.090909 | 77 | py |
gym-electric-motor | gym-electric-motor-master/examples/reinforcement_learning_controllers/ddpg_series_omega_control.py | """Run this file from within the 'examples' folder:
>> cd examples
>> python ddpg_series_omega_control.py
"""
from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Flatten, Input, \
Concatenate
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from rl.a... | 5,289 | 36.51773 | 129 | py |
gym-electric-motor | gym-electric-motor-master/examples/reinforcement_learning_controllers/dqn_series_current_control.py | """Run this file from within the 'examples' folder:
>> cd examples
>> python dqn_series_current_control.py
"""
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.policy import LinearAnn... | 4,950 | 42.052174 | 113 | py |
gym-electric-motor | gym-electric-motor-master/examples/reinforcement_learning_controllers/ddpg_pmsm_dq_current_control.py | from tensorflow.keras.models import Sequential, Model
from tensorflow.keras.layers import Dense, Flatten, Input, \
Concatenate
from tensorflow.keras import initializers, regularizers
from tensorflow.keras.optimizers import Adam
from rl.agents import DDPGAgent
from rl.memory import SequentialMemory
from rl.random im... | 10,837 | 38.410909 | 129 | py |
gym-electric-motor | gym-electric-motor-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 5,403 | 30.418605 | 155 | py |
BMXNet-v2 | BMXNet-v2-master/tools/rec2idx.py | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | 3,417 | 30.943925 | 77 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.