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
urnng
urnng-master/train_lm.py
#!/usr/bin/env python3 import sys import os import argparse import json import random import shutil import copy import torch from torch import cuda import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter import torch.nn.functional as F import numpy as np import time import ...
6,303
36.52381
133
py
urnng
urnng-master/models.py
import torch from torch import nn import torch.nn.functional as F import numpy as np from utils import * from TreeCRF import ConstituencyTreeCRF from torch.distributions import Bernoulli class RNNLM(nn.Module): def __init__(self, vocab=10000, w_dim=650, h_dim=650, num_lay...
16,848
39.995134
112
py
urnng
urnng-master/parse.py
#!/usr/bin/env python3 import sys import os import argparse import json import random import shutil import copy import torch from torch import cuda import torch.nn as nn import numpy as np import time from utils import * import utils import re parser = argparse.ArgumentParser() # Data path options parser.add_argume...
7,103
35.060914
137
py
urnng
urnng-master/train.py
#!/usr/bin/env python3 import sys import os import argparse import json import random import shutil import copy import torch from torch import cuda import torch.nn as nn from torch.autograd import Variable from torch.nn.parameter import Parameter import torch.nn.functional as F import numpy as np import time import ...
14,042
41.683891
121
py
dgcnn
dgcnn-master/pytorch/main.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Yue Wang @Contact: yuewangx@mit.edu @File: main.py @Time: 2018/10/13 10:39 PM """ from __future__ import print_function import os import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.optim.l...
9,567
40.964912
119
py
dgcnn
dgcnn-master/pytorch/model.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Yue Wang @Contact: yuewangx@mit.edu @File: model.py @Time: 2018/10/13 6:35 PM """ import os import sys import copy import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F def knn(x, k): inner = -2*torch.matmul(x...
5,434
34.292208
181
py
dgcnn
dgcnn-master/pytorch/data.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Yue Wang @Contact: yuewangx@mit.edu @File: data.py @Time: 2018/10/13 6:21 PM """ import os import sys import glob import h5py import numpy as np from torch.utils.data import Dataset def download(): BASE_DIR = os.path.dirname(os.path.abspath(__file__)) ...
2,630
28.897727
110
py
dgcnn
dgcnn-master/pytorch/util.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @Author: Yue Wang @Contact: yuewangx@mit.edu @File: util @Time: 4/5/19 3:47 PM """ import numpy as np import torch import torch.nn.functional as F def cal_loss(pred, gold, smoothing=True): ''' Calculate cross entropy loss, apply label smoothing if needed. ''' ...
995
20.191489
75
py
MedCAT
MedCAT-master/setup.py
import setuptools with open("./README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="medcat", setup_requires=["setuptools_scm"], use_scm_version={"local_scheme": "no-local-version", "fallback_version": "unknown"}, author="w-is-h", author_email="w.kraljevic@gmail.com", ...
2,996
48.95
114
py
MedCAT
MedCAT-master/examples/run_standalone_meta_annotations.py
from medcat.datasets.helpers import encode_examples from datasets import load_dataset from transformers.data.data_collator import DataCollatorWithPadding from transformers import AutoTokenizer from torch.utils.data import DataLoader from medcat.meta_cat import MetaCAT import torch CACHE_DIR = './' DATASETS_CLASS_PATH ...
1,621
34.26087
146
py
MedCAT
MedCAT-master/medcat/cat.py
import os import glob import shutil import pickle import traceback import json import logging import math import time import psutil from time import sleep from multiprocess import Process, Manager, cpu_count from multiprocess.queues import Queue from multiprocess.synchronize import Lock from typing import Union, List, ...
82,532
46.460035
172
py
MedCAT
MedCAT-master/medcat/meta_cat.py
import os import json import logging import torch import numpy from multiprocessing import Lock from torch import nn, Tensor from spacy.tokens import Doc from datetime import datetime from typing import Iterable, Iterator, Optional, Dict, List, Tuple, cast, Union from medcat.utils.hasher import Hasher from medcat.confi...
24,788
40.732323
152
py
MedCAT
MedCAT-master/medcat/datasets/data_collator.py
from typing import Any, Dict, List import torch class CollateAndPadNER(object): def __init__(self, pad_id): self.pad_id = pad_id def __call__(self, features: List[Any]) -> Dict[str, torch.Tensor]: batch = {} max_len = max([len(f['input_ids']) for f in features]) batch['input_...
723
35.2
87
py
MedCAT
MedCAT-master/medcat/utils/data_utils.py
import json import torch import copy import numpy as np from sklearn.metrics import cohen_kappa_score from typing import Dict, List, Optional, Union, Tuple, Any, Set from spacy.tokens.doc import Doc from spacy.tokens.span import Span from medcat.cdb import CDB from collections import defaultdict import random import l...
39,699
41.826321
180
py
MedCAT
MedCAT-master/medcat/utils/meta_cat/models.py
import torch from collections import OrderedDict from typing import Optional, Any, List from torch import nn, Tensor from torch.nn import CrossEntropyLoss from transformers import BertPreTrainedModel, BertModel, BertConfig from transformers.modeling_outputs import TokenClassifierOutput from medcat.meta_cat import Confi...
6,023
39.16
122
py
MedCAT
MedCAT-master/medcat/utils/meta_cat/ml_utils.py
import os import random import math import torch import numpy as np import pandas as pd import torch.optim as optim from typing import List, Optional, Tuple, Any, Dict from torch import nn from scipy.special import softmax from medcat.config_meta_cat import ConfigMetaCAT from medcat.tokenizers.meta_cat_tokenizers impor...
11,484
37.029801
148
py
MedCAT
MedCAT-master/medcat/preprocessing/iterators.py
import pandas import re from typing import List, Optional, Dict, Iterable, Any, Tuple NUM = "NUMNUM" FAST_SPLIT = re.compile("[^A-Za-z0-9]") class EmbMimicCSV(object): """Iterate over MIMIC data in CSV format csv_paths: paths to csv files containing the mimic data """ def __init__(self, csv_paths...
5,797
35.696203
106
py
learning_best_average_power
learning_best_average_power-main/wald_train.py
import numpy as np import torch def generate_fixed_ref(xmpl, N, null, alt): alts = [alt] null = np.array([null]) theories = np.concatenate([null,alts]) Xnull = xmpl.sample_prob_model(null[0],N) Xalt0 = xmpl.sample_prob_model(alts[0],N) ynull = np.zeros(N) yalt0 = np.ones(N) ...
2,836
28.552083
95
py
learning_best_average_power
learning_best_average_power-main/wald_plots.py
import numpy as np import matplotlib.pyplot as plt import torch from wald_train import * from wald_groundtruth import * import scipy.stats as sps from sklearn.isotonic import IsotonicRegression def plot_data_showcase(xmpl, poi = 3.0, scale = 1.0): X,y,t = generate_data(xmpl, poi = poi, scale=scale, N = 1000) p...
11,250
34.269592
144
py
learning_best_average_power
learning_best_average_power-main/wald_train_pois.py
import wald_onoff as xmpl from wald_train import * from wald_plots import * from wald_groundtruth import * model,losses = train(xmpl, 50000) torch.save(model,'wald_pois.ckpt')
177
21.25
34
py
learning_best_average_power
learning_best_average_power-main/wald_train_gauss.py
import wald_gaussian as xmpl from wald_train import * from wald_plots import * from wald_groundtruth import * model,losses = train(xmpl, 50000) torch.save(model,'wald_gauss.ckpt')
181
21.75
35
py
LAGNN
LAGNN-main/main.py
from graph_transformer import GraphTransformerNet from egat_model import EGAT import argparse from torch.optim.lr_scheduler import ReduceLROnPlateau from dgl import seed import time import logging from sklearn import metrics from dgl.data.utils import load_graphs import random import torch.nn.functional as F import dgl...
13,473
40.204893
187
py
LAGNN
LAGNN-main/egat_model.py
import torch import torch.nn as nn import torch.nn.functional as F class EGATConv(nn.Module): def __init__(self, in_node_feats, in_edge_feats, out_node_feats, out_edge_feats, num_heads): super().__init__() ...
3,393
35.891304
128
py
HRSTNet
HRSTNet-main/tools_validate.py
import os import sys import argparse from seg.config.defaults import get_cfg from seg.utils.comm import default_setup from seg.engine.launch import launch from seg.engine.trainer import Trainer from seg.utils.comm import init_data_dir from seg.engine.trainer import val_epoch_brats def setup(args): """ Create ...
4,269
42.131313
117
py
HRSTNet
HRSTNet-main/tools_flops.py
import os import sys import argparse import torch from seg.config.defaults import get_cfg from seg.utils.comm import default_setup from seg.engine.launch import launch from seg.utils.comm import init_data_dir from seg.models.builder import get_model from mmcv.cnn import get_model_complexity_info def setup(args): ...
3,512
36.774194
93
py
HRSTNet
HRSTNet-main/tools_visualize.py
import os import sys import argparse from seg.config.defaults import get_cfg from seg.utils.comm import default_setup from seg.engine.launch import launch from seg.engine.trainer import Trainer from seg.utils.comm import init_data_dir def setup(args): """ Create configs and perform basic setups. """ c...
4,054
40.377551
93
py
HRSTNet
HRSTNet-main/tools_train.py
import os import sys import argparse from seg.config.defaults import get_cfg from seg.utils.comm import default_setup from seg.engine.launch import launch from seg.engine.trainer import Trainer from seg.utils.comm import init_data_dir def setup(args): """ Create configs and perform basic setups. """ c...
3,113
37.444444
95
py
HRSTNet
HRSTNet-main/tools_inference.py
import os import sys import argparse from seg.config.defaults import get_cfg from seg.utils.comm import default_setup from seg.engine.launch import launch from seg.engine.trainer import Trainer from seg.utils.comm import init_data_dir def setup(args): """ Create configs and perform basic setups. """ c...
4,510
41.961905
118
py
HRSTNet
HRSTNet-main/seg/solver/edice_loss.py
import torch import torch.nn as nn class EDiceLoss(nn.Module): """Dice loss tailored to Brats need. """ def __init__(self, do_sigmoid=True): super(EDiceLoss, self).__init__() self.do_sigmoid = do_sigmoid self.labels = ["ET", "TC", "WT"] self.device = "cpu" def binary_...
4,018
32.773109
102
py
HRSTNet
HRSTNet-main/seg/solver/build.py
import torch from seg.config.config import CfgNode from seg.utils.optimizer_utils import LinearWarmupCosineAnnealingLR from monai.losses import DiceCELoss from monai.metrics import DiceMetric from monai.utils.enums import MetricReduction from seg.solver.edice_loss import EDiceLoss, EDiceLoss_Val from monai.transforms i...
5,595
44.868852
111
py
HRSTNet
HRSTNet-main/seg/models/vt_unet.py
import torch import torch.nn as nn import copy from seg.utils.register import MODEL_REGISTRY from seg.models.vt_unet_utils import SwinTransformerSys3D class VTUNet(nn.Module): def __init__(self, config, num_classes=3, zero_head=False, embed_dim=96, win_size=7): super(VTUNet, self).__init__() self....
4,499
49.561798
115
py
HRSTNet
HRSTNet-main/seg/models/unetr.py
# Copyright 2020 - 2021 MONAI Consortium # 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/LICENSE-2.0 # Unless required by applicable law or agreed to in wri...
9,501
37.469636
126
py
HRSTNet
HRSTNet-main/seg/models/swin_unet.py
import torch from seg.utils.register import MODEL_REGISTRY from typing import Sequence, Tuple, Union from monai.networks.blocks import UnetOutBlock, UnetrBasicBlock, UnetrUpBlock from monai.utils import ensure_tuple_rep import numpy as np from seg.models.swin.swin_transformer import SwinTransformer import torch.nn as n...
10,105
37.280303
119
py
HRSTNet
HRSTNet-main/seg/models/hrtrans_utils.py
import torch import torch.nn as nn from torch.nn import LayerNorm from einops import rearrange from typing import Sequence, Type, Union, Tuple from seg.models.swin.patch_merging import PatchMerging from seg.models.swin.swin_blocks import BasicLayer from monai.networks.blocks import UnetrBasicBlock from monai.utils impo...
43,029
42.377016
114
py
HRSTNet
HRSTNet-main/seg/models/nn_unet.py
# Copyright (c) MONAI Consortium # 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/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, so...
18,686
46.549618
122
py
HRSTNet
HRSTNet-main/seg/models/hrtrans.py
import torch import torch.nn as nn from seg.utils.register import MODEL_REGISTRY from torch.nn import LayerNorm from monai.networks.blocks import PatchEmbed from typing import Sequence, Type from monai.utils import ensure_tuple_rep from seg.models.hrtrans_utils import FinalPatchExpand, HRTransStages, FinalStage import ...
5,322
32.904459
80
py
HRSTNet
HRSTNet-main/seg/models/vt_unet_utils.py
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint import logging from einops import rearrange from mmcv.runner import load_checkpoint from monai.networks.layers import trunc_normal_ from monai.networks.layers import DropPath from monai.netw...
42,855
40.486931
127
py
HRSTNet
HRSTNet-main/seg/models/extending_nnunet.py
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany # # 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:/...
42,868
47.113356
147
py
HRSTNet
HRSTNet-main/seg/models/swin/window_attention.py
import torch import torch.nn as nn from typing import Sequence from monai.networks.layers import trunc_normal_ class WindowAttention(nn.Module): """ Window based multi-head self attention module with relative position bias based on: "Liu et al., Swin Transformer: Hierarchical Vision Transformer using Shif...
4,959
42.893805
114
py
HRSTNet
HRSTNet-main/seg/models/swin/swin_transformer.py
import torch import torch.nn as nn import torch.nn.functional as F from typing import Sequence, Type from monai.networks.blocks import PatchEmbed from torch.nn import LayerNorm from seg.models.swin.swin_blocks import BasicLayer from seg.models.swin.patch_merging import PatchMerging from monai.utils import optional_impo...
4,980
37.022901
82
py
HRSTNet
HRSTNet-main/seg/models/swin/swin_utils.py
import torch def compute_mask(dims, window_size, shift_size, device): """Computing region masks based on: "Liu et al., Swin Transformer: Hierarchical Vision Transformer using Shifted Windows <https://arxiv.org/abs/2103.14030>" https://github.com/microsoft/Swin-Transformer Args: dims: dim...
4,654
34
120
py
HRSTNet
HRSTNet-main/seg/models/swin/swin_blocks.py
import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.checkpoint as checkpoint from torch.nn import LayerNorm import numpy as np from typing import Sequence, Type from monai.utils import optional_import from monai.networks.blocks import MLPBlock as Mlp from monai.networks.layers import D...
11,995
40.365517
118
py
HRSTNet
HRSTNet-main/seg/models/swin/patch_merging.py
import torch import torch.nn as nn import torch.nn.functional as F from typing import Type from torch.nn import LayerNorm class PatchMerging(nn.Module): """ Patch merging layer based on: "Liu et al., Swin Transformer: Hierarchical Vision Transformer using Shifted Windows <https://arxiv.org/abs/2103.14...
2,202
32.378788
89
py
HRSTNet
HRSTNet-main/seg/engine/visualization.py
import os import time import shutil import numpy as np import torch from torch.cuda.amp import GradScaler, autocast from tensorboardX import SummaryWriter import torch.nn.parallel from seg.utils.dist_utils import distributed_all_gather import seg.utils.dist_utils as dist_utils import torch.utils.data.distributed from m...
5,065
43.052174
118
py
HRSTNet
HRSTNet-main/seg/engine/launch.py
import logging from datetime import timedelta import torch import torch.distributed as dist import torch.multiprocessing as mp import seg.utils.dist_utils as dist_utils DEFAULT_TIMEOUT = timedelta(minutes=30) def _find_free_port(): import socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ...
4,128
31.769841
95
py
HRSTNet
HRSTNet-main/seg/engine/defaults.py
import seg.utils.dist_utils as dist_utils from torch.nn.parallel import DistributedDataParallel import torch def create_ddp_model(model, cfgs, *, fp16_compression=False, **kwargs): """ Create a DistributedDataParallel model if there are >1 processes. Args: model: a torch.nn.Module fp16_co...
1,071
41.88
152
py
HRSTNet
HRSTNet-main/seg/engine/trainer.py
# Copyright 2020 - 2021 MONAI Consortium # 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/LICENSE-2.0 # Unless required by applicable law or agreed to in wri...
84,685
50.574909
202
py
HRSTNet
HRSTNet-main/seg/utils/optimizer_utils.py
# Copyright 2020 - 2021 MONAI Consortium # 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/LICENSE-2.0 # Unless required by applicable law or agreed to in wri...
6,510
36.854651
119
py
HRSTNet
HRSTNet-main/seg/utils/dist_utils.py
import torch import numpy as np import math import torch.distributed as dist """ A torch process group which only includes processes that on the same machine as the current process. This variable is set when processes are spawned by `launch()` in "engine/launch.py". """ _LOCAL_PROCESS_GROUP = None def distributed...
5,084
33.591837
111
py
HRSTNet
HRSTNet-main/seg/utils/data_utils.py
# Copyright 2020 - 2021 MONAI Consortium # 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/LICENSE-2.0 # Unless required by applicable law or agreed to in wri...
2,672
42.112903
112
py
HRSTNet
HRSTNet-main/seg/utils/collect_env.py
# Copyright (c) Facebook, Inc. and its affiliates. import importlib import numpy as np import os import re import subprocess import sys from collections import defaultdict import PIL import torch import torchvision from tabulate import tabulate __all__ = ["collect_env_info"] def collect_torch_env(): try: ...
7,468
33.578704
96
py
HRSTNet
HRSTNet-main/seg/utils/register.py
from typing import Any import pydoc from fvcore.common.registry import Registry # for backward compatibility. # predictor registry MODEL_REGISTRY = Registry('MODEl') """ ``Registry`` and `locate` provide ways to map a string (typically found in config files) to callable objects. """ __all__ = ["Registry", "locate...
1,180
24.673913
96
py
HRSTNet
HRSTNet-main/seg/utils/env.py
import logging import numpy as np import os import random from datetime import datetime import torch def seed_all_rng(seed=None): """ Set the random seed for the RNG in torch, numpy and python. Args: seed (int): if None, will use a strong random seed. """ if seed is None: seed = (...
690
24.592593
68
py
HRSTNet
HRSTNet-main/datasets/abdomen.py
# Copyright 2020 - 2021 MONAI Consortium # 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/LICENSE-2.0 # Unless required by applicable law or agreed to in wri...
41,140
46.727378
132
py
HRSTNet
HRSTNet-main/datasets/vt_unet_brats/batch_utils.py
import random import torch.nn.functional as F from torch.utils.data._utils.collate import default_collate def custom_collate(batch): batch = pad_batch_to_max_shape(batch) return default_collate(batch) def determinist_collate(batch): batch = pad_batch_to_max_shape(batch) return default_collate(batch...
2,138
37.890909
105
py
HRSTNet
HRSTNet-main/datasets/vt_unet_brats/brats.py
import pathlib import SimpleITK as sitk import numpy as np import torch from sklearn.model_selection import KFold from torch.utils.data.dataset import Dataset from .config import get_brats_folder, get_test_brats_folder from .image_utils import pad_or_crop_image, irm_min_max_preprocess, zscore_normalise from skimage.tr...
8,995
47.627027
139
py
physics-aware-downsampling
physics-aware-downsampling-main/main.py
import collections import json from typing import Dict, NamedTuple import torch import torch.distributed as dist import torch.nn as nn from absl import app from absl import flags from absl import logging from torch.utils.data import distributed as dist_data import trainer import utils.tensorboard as tb from data impo...
11,082
43.870445
180
py
physics-aware-downsampling
physics-aware-downsampling-main/ground_truth.py
import enum import logging import multiprocessing import os import time import tqdm import numpy as np import pandas as pd import torch from hydraulics import boundary from hydraulics import saint_venant from hydraulics import simulation_utils as sim_utils INDEX_PATH = '/home/usgs_dem_data/dem/index.csv' FLUX_OUTPUT...
7,136
41.230769
84
py
physics-aware-downsampling
physics-aware-downsampling-main/evaluation.py
import collections import csv import datetime import json import os from typing import Dict, NamedTuple import torch import torch.nn as nn from absl import app from absl import flags from absl import logging from torch.utils.data import distributed as dist_data import trainer from data import data from hydraulics imp...
6,627
40.685535
99
py
physics-aware-downsampling
physics-aware-downsampling-main/trainer.py
import time from typing import Optional, Tuple import torch import torch.distributed as dist import torch.nn as nn from absl import logging from hydraulics import boundary from hydraulics import simulation_utils as sim_utils from utils import meters from utils import model_utils from utils import tensorboard as tb fr...
6,145
41.979021
80
py
physics-aware-downsampling
physics-aware-downsampling-main/models/swe_model.py
from typing import Optional import torch import torch.nn as nn from torch.utils import checkpoint import hydraulics.simulation_utils as sim_utils __all__ = ['swe_model'] class SweModel(nn.Module): def __init__(self, downsample_model, numerical_solver, coarse_dx, coarse_n_x, alpha, simulation_m...
3,050
39.144737
77
py
physics-aware-downsampling
physics-aware-downsampling-main/models/averagenet.py
# Lint as: python3 import torch import torch.nn as nn __all__ = ['average_net'] class AverageNet(nn.Module): def __init__(self, downsample_factor: int = 16): super(AverageNet, self).__init__() self.dummy_parameter = nn.Parameter(torch.zeros(1), True) self.avg = nn.AvgPool2d(kernel_size=d...
451
19.545455
65
py
physics-aware-downsampling
physics-aware-downsampling-main/models/edge_preserving.py
# Lint as: python3 import torch import torch.nn as nn import cv2 import numpy as np __all__ = ['edge_preserve'] class EdgePreserve(nn.Module): def __init__(self, downsample_factor: int = 16): super(EdgePreserve, self).__init__() self.kernel_size = 3 self.sigma_space = 50 self.sig...
1,145
29.972973
77
py
physics-aware-downsampling
physics-aware-downsampling-main/models/detour.py
# Lint as: python3 import torch import torch.nn as nn import torch.nn.functional from torch.utils import checkpoint batch_norm = nn.BatchNorm2d group_norm = nn.GroupNorm _use_group_norm = False def get_norm_layer(num_channels): if _use_group_norm: num_channels_per_group = 16 return nn.GroupNorm(...
5,964
34.933735
80
py
physics-aware-downsampling
physics-aware-downsampling-main/utils/evaluation_viewer.py
import base64 import sys from dataclasses import dataclass import cv2 import jinja2 import numpy as np import torch from matplotlib import figure as plt_fig from matplotlib.backends import backend_agg from utils import visualization as viz @dataclass class Sample: """Class for storing sample outputs.""" sam...
3,828
42.022472
80
py
physics-aware-downsampling
physics-aware-downsampling-main/utils/optimization.py
import torch import torch.nn as nn import torch.nn.functional as F class InundationLoss(nn.Module): def __init__(self, threshold: float = 0.5, reduction: str = 'mean'): super(InundationLoss, self).__init__() self.reduction = reduction self.threshold = threshold def forward(self, input...
1,441
36.947368
80
py
physics-aware-downsampling
physics-aware-downsampling-main/utils/visualization.py
import logging from typing import List, Optional import matplotlib import matplotlib.animation as animation import matplotlib.cm import matplotlib.pyplot as plt import numpy as np import torch from matplotlib.colors import LightSource def render_hillshade_water_image(z: np.ndarray, h: np.ndarray, ...
5,160
34.840278
80
py
physics-aware-downsampling
physics-aware-downsampling-main/utils/model_utils.py
# Lint as: python3 import logging from typing import Optional, Mapping, Text import torch import torch.nn as nn def get_model_gradients(model: nn.Module) -> Mapping[Text, torch.Tensor]: gradients = {} for name, weight in model.named_parameters(): gradients[name] = weight.grad.data.clone() return ...
1,282
31.075
73
py
physics-aware-downsampling
physics-aware-downsampling-main/utils/tensorboard.py
# Lint as: python3 import os from datetime import datetime from typing import Optional, Mapping, Any, Sequence import matplotlib.pyplot as plt import torch import torch.utils.tensorboard as tensorboard class TensorBoard(object): def __init__(self): self.log_dir = None self.writer = None ...
4,444
27.49359
80
py
physics-aware-downsampling
physics-aware-downsampling-main/utils/meters.py
import torch class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n ...
1,155
21.666667
61
py
physics-aware-downsampling
physics-aware-downsampling-main/data/data.py
import enum import logging from ast import literal_eval import numpy as np import pandas as pd import torch class GroundTruthType(enum.Enum): RAIN, FLUX = range(2) FLUX_INDEX_PATH = '/home/usgs_dem_data/flux_ground_truth/' RAIN_INDEX_PATH = '/home/usgs_dem_data/rain_ground_truth/' TRAIN_INDEX_NAME = 'train_gro...
4,047
39.48
78
py
physics-aware-downsampling
physics-aware-downsampling-main/source/utils.py
import numpy as np import pandas as pd from typing import Optional, Sequence from ast import literal_eval import torch def read_index_row(index: pd.DataFrame, row: int): dem = torch.tensor(np.load(index.iloc[row][1])) influx = literal_eval(index.iloc[row][2]) outflux = literal_eval(index.iloc[row][3]) ...
1,764
29.964912
80
py
physics-aware-downsampling
physics-aware-downsampling-main/hydraulics/saint_venant.py
# Lint as: python3 from typing import Optional, Tuple import torch import torch.nn as nn import torch.nn.functional as F G = 9.8 MANNING_COEFF_FLOODPLAIN = 0.05 _X_AXIS = 3 _Y_AXIS = 2 _EPSILON = 1e-8 class SaintVenantFlux(nn.Module): """1D saint venant equations with flux and height variables. Implemente...
5,431
42.111111
80
py
physics-aware-downsampling
physics-aware-downsampling-main/hydraulics/boundary.py
import abc import enum from typing import Sequence, Tuple import torch import torch.nn.functional as F G = 9.8 OUTFLUX_SLOPE = 0.2 def _flux_location_to_indices(dem_shape: int, flux_location: torch.Tensor, down_sample_factor: int): x, y, length = flux_location rows = dem_shape ...
6,425
42.127517
79
py
physics-aware-downsampling
physics-aware-downsampling-main/hydraulics/simulation_utils.py
import torch import torch.nn as nn G = 9.8 def downsample(z: torch.Tensor, ds_factor: int) -> torch.Tensor: """downsample 2d tensor z by a factor of ds_factor. z should have 3 dimensions of (batch size, rows, cols). if z is provided with 2 dimensions, a third (batch size = 1) is deduced automatically. ...
897
27.0625
78
py
mumin-build
mumin-build-main/src/mumin/embedder.py
"""Compute node embeddings for the dataset""" import json import warnings from functools import partial from typing import Dict, List, Tuple, Union import numpy as np import pandas as pd import torch from transformers import ( AutoFeatureExtractor, AutoModel, AutoModelForImageClassification, AutoToken...
13,768
32.913793
87
py
mumin-build
mumin-build-main/src/mumin/dgl.py
"""Functions related to exporting the dataset to the Deep Graph Library""" import json from pathlib import Path from typing import Dict, Tuple, Union import numpy as np import pandas as pd from torch import Tensor def build_dgl_dataset( nodes: Dict[str, pd.DataFrame], relations: Dict[Tuple[str, str, str], pd.Da...
12,485
37.183486
87
py
itabqa
itabqa-master/itabqa/experiments.py
import json import math import multiprocessing import os from collections import Counter, defaultdict from contextlib import closing from multiprocessing.pool import Pool from typing import List import numpy as np import pandas as pd import spacy import torch from tqdm import tqdm from transformers import Pipeline, pi...
16,730
29.200361
135
py
itabqa
itabqa-master/itabqa/m_gramformer.py
import torch from gramformer import Gramformer def set_seed(seed): torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed_all(seed) set_seed(1212) gf = Gramformer(models = 1, use_gpu=False) # 1=corrector, 2=detector influent_sentences = [ "He are moving here.", "I am doing fi...
1,006
28.617647
73
py
dreamerv2
dreamerv2-main/dreamerv2/agent.py
import tensorflow as tf from tensorflow.keras import mixed_precision as prec import common import expl class Agent(common.Module): def __init__(self, config, obs_space, act_space, step): self.config = config self.obs_space = obs_space self.act_space = act_space['action'] self.step = step self....
13,833
40.295522
78
py
dreamerv2
dreamerv2-main/dreamerv2/train.py
import collections import functools import logging import os import pathlib import re import sys import warnings try: import rich.traceback rich.traceback.install() except ImportError: pass os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' logging.getLogger().setLevel('ERROR') warnings.filterwarnings('ignore', '.*box bo...
7,266
35.888325
79
py
dreamerv2
dreamerv2-main/dreamerv2/common/tfutils.py
import pathlib import pickle import re import numpy as np import tensorflow as tf from tensorflow.keras import mixed_precision as prec try: from tensorflow.python.distribute import values except Exception: from google3.third_party.tensorflow.python.distribute import values tf.tensor = tf.convert_to_tensor for ba...
4,877
31.092105
76
py
dreamerv2
dreamerv2-main/dreamerv2/common/nets.py
import re import numpy as np import tensorflow as tf from tensorflow.keras import layers as tfkl from tensorflow_probability import distributions as tfd from tensorflow.keras.mixed_precision import experimental as prec import common class EnsembleRSSM(common.Module): def __init__( self, ensemble=5, stoch=3...
15,219
35.324582
79
py
DocSCAN
DocSCAN-main/src/DocSCAN.py
import sys, os, json, argparse import pandas as pd from sentence_transformers import SentenceTransformer from utils.memory import MemoryBank import torch from utils.DocSCAN_utils import DocScanDataset, DocScanModel from utils.losses import SCANLoss from utils.kneelocator import KneeLocator from sklearn.feature_extracti...
12,571
41.472973
159
py
DocSCAN
DocSCAN-main/src/DocSCAN_paper_replication.py
import sys, os, json, argparse import pandas as pd from sentence_transformers import SentenceTransformer from utils.memory import MemoryBank import torch from utils.DocSCAN_utils import DocScanDataset, DocScanModel from utils.losses import SCANLoss from sklearn.feature_extraction.text import TfidfVectorizer from tqdm i...
9,966
39.681633
165
py
DocSCAN
DocSCAN-main/src/utils/losses.py
import torch import torch.nn as nn import torch.nn.functional as F from sklearn.utils.class_weight import compute_class_weight import numpy as np EPS=1e-8 def entropy(x, input_as_probabilities): """ Helper function to compute the entropy over the batch input: batch w/ shape [b, num_classes] output: ...
2,197
31.80597
98
py
DocSCAN
DocSCAN-main/src/utils/memory.py
""" Authors: Wouter Van Gansbeke, Simon Vandenhende Licensed under the CC BY-NC 4.0 license (https://creativecommons.org/licenses/by-nc/4.0/) """ import numpy as np import torch from sklearn import metrics def evaluate(y, preds): print(metrics.classification_report(y, preds)) #print(metrics.confusion_matrix(y, preds...
2,129
32.809524
103
py
DocSCAN
DocSCAN-main/src/utils/DocSCAN_utils.py
import argparse import os import json import pandas as pd import torch import random import gc from collections import defaultdict import numpy as np from torch.utils.data import Dataset from transformers import AdamW, get_linear_schedule_with_warmup from transformers import DistilBertTokenizerFast, DistilBertModel f...
2,482
29.280488
79
py
DocSCAN
DocSCAN-main/src/utils/utils.py
import numpy as np from scipy.optimize import linear_sum_assignment from sklearn import metrics def _hungarian_match(flat_preds, flat_targets, preds_k, targets_k): # Based on implementation from IIC num_samples = len(flat_targets) assert (preds_k == targets_k) # one to one num_k = preds_k num_cor...
2,858
41.044118
181
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/common.py
# Copyright 2017--2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fi...
26,288
47.236697
140
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/common_image_captioning.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
14,551
46.555556
135
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_layers.py
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
5,378
37.697842
109
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_decoder.py
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
6,314
47.206107
120
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_loss.py
# Copyright 2017, 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" f...
7,049
43.904459
115
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_encoder.py
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
11,983
51.792952
124
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_rnn.py
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
11,111
47.103896
122
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_constraints.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
13,212
44.878472
130
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_inference.py
# Copyright 2017, 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" fi...
36,544
50.183473
146
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_operator.py
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
1,480
30.510638
78
py
EntityDescriptionGeneration
EntityDescriptionGeneration-master/test/unit/test_coverage.py
# Copyright 2017 Amazon.com, Inc. or its affiliates. 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. A copy of the License # is located at # # http://aws.amazon.com/apache2.0/ # # or in the "license" file acc...
7,982
53.678082
126
py