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 |
|---|---|---|---|---|---|---|
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/network_training/nnFormerTrainerV2_Dual.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://w... | 31,541 | 47.451613 | 149 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/network_training/network_trainer.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://w... | 31,373 | 41.569878 | 153 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/data_augmentation/downsampling.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://w... | 4,164 | 38.292453 | 132 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/optimizer/ranger.py | ############
# https://github.com/lessw2020/Ranger-Deep-Learning-Optimizer
# This code was taken from the repo above and was not created by me (Fabian)! Full credit goes to the original authors
############
import math
import torch
from torch.optim.optimizer import Optimizer
class Ranger(Optimizer):
def __init_... | 6,465 | 41.261438 | 132 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/loss_functions/dice_loss.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://w... | 14,057 | 31.922717 | 121 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/loss_functions/TopK_loss.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://w... | 1,366 | 39.205882 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/loss_functions/crossentropy.py | from torch import nn, Tensor
import torch.nn.functional as F
import torch
from typing import Callable, Optional
from nnformer.utilities.nd_softmax import softmax_helper
class RobustCrossEntropyLoss(nn.CrossEntropyLoss):
"""
this is just a compatibility layer because my target tensor is float and has an extra d... | 2,840 | 33.228916 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/loss_functions/NoiseRobustDice_loss.py | from torch import nn, Tensor
import torch.nn.functional as F
import torch
from nnformer.utilities.nd_softmax import softmax_helper
from nnformer.training.loss_functions.crossentropy import Talyer2CrossEntropyLoss
def reshape_tensor_to_2D(x):
"""
reshape input variables of shape [B, C, D, H, W] to [voxel_n, C]
... | 7,775 | 36.384615 | 115 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/loss_functions/deep_supervision.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://w... | 1,679 | 37.181818 | 117 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/training/loss_functions/Reconstruction_Segmentation.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://w... | 15,094 | 31.32334 | 121 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/network_architecture/generic_UNet_last_cut.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://w... | 59,508 | 47.499593 | 190 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/network_architecture/neural_network.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://w... | 43,835 | 51.878166 | 137 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/network_architecture/neural_network_last_cut.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://w... | 52,876 | 52.846232 | 187 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/network_architecture/initialization.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://w... | 1,673 | 41.923077 | 158 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/network_architecture/generic_UNet.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://w... | 21,156 | 45.39693 | 180 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/utilities/nd_softmax.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://w... | 1,882 | 36.66 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/utilities/tensor_utilities.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://w... | 1,624 | 28.545455 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/utilities/to_torch.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://w... | 1,292 | 33.945946 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/utilities/distributed.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://w... | 3,172 | 34.255556 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/run/load_pretrained_weights.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://w... | 2,506 | 38.793651 | 114 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/inference/predict_simple.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://w... | 16,240 | 60.98855 | 172 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/inference/predict.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://w... | 42,909 | 52.172243 | 182 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/inference/pretrained_models/predict_simple.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://w... | 13,603 | 59.19469 | 125 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/nnformer/inference/pretrained_models/predict.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://w... | 42,682 | 52.088308 | 182 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/batchgenerators/dataloading/multi_threaded_augmenter.py | # Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... | 11,396 | 38.164948 | 118 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/batchgenerators/dataloading/data_loader.py | # Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... | 9,440 | 37.068548 | 121 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/batchgenerators/examples/cifar10.py | import re
import torch
from batchgenerators.dataloading import MultiThreadedAugmenter
import numpy as np
import os
from batchgenerators.dataloading.data_loader import DataLoaderFromDataset
from batchgenerators.datasets.cifar import HighPerformanceCIFARLoader, CifarDataset
from batchgenerators.transforms.spatial_transfo... | 5,372 | 37.106383 | 118 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/batchgenerators/examples/brats2017/brats2017_dataloader_3D.py | from time import time
from batchgenerators.augmentations.crop_and_pad_augmentations import crop
from batchgenerators.dataloading import MultiThreadedAugmenter
from batchgenerators.examples.brats2017.config import brats_preprocessed_folder, num_threads_for_brats_example
from batchgenerators.transforms import Compose
fro... | 11,679 | 50.453744 | 131 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/batchgenerators/examples/brats2017/brats2017_dataloader_2D.py | from time import time
import numpy as np
from batchgenerators.augmentations.crop_and_pad_augmentations import crop
from batchgenerators.augmentations.utils import pad_nd_image
from batchgenerators.dataloading import MultiThreadedAugmenter
from batchgenerators.dataloading.data_loader import DataLoader
from batchgenerat... | 8,388 | 49.233533 | 131 | py |
Semi-Supervised-nnUNet | Semi-Supervised-nnUNet-master/batchgenerators/transforms/utility_transforms.py | # Copyright 2017 Division of Medical Image Computing, German Cancer Research Center (DKFZ)
#
# 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
#... | 16,794 | 36.911964 | 182 | py |
pts-uncertainty | pts-uncertainty-main/pts_calibrator.py | import os
import tensorflow as tf
import numpy as np
class PTS_calibrator():
"""Class for Parameterized Temperature Scaling (PTS)"""
def __init__(
self,
epochs,
lr,
weight_decay,
batch_size,
nlayers,
n_nodes,
length_logits,
top_k_logits
... | 4,067 | 32.073171 | 111 | py |
spenser | spenser-main/spenser/engine.py | import os
import sys, getopt
from spenser.grammar import Grammar
from spenser.utils import save_pop, pickle_population, unpickle_population, load_config, pickle_evaluator
from spenser.evaluator import Evaluator
from spenser.individual import Individual
from pathlib import Path
from os import makedirs
import random
im... | 16,275 | 32.284254 | 238 | py |
spenser | spenser-main/spenser/data.py | import snntorch as snn
import torch
from torchvision import datasets, transforms
from snntorch import utils
from torch.utils.data import DataLoader, random_split, Subset
from snntorch import spikegen
from sklearn.model_selection import train_test_split
import numpy as np
# Training Parameters
MNIST='./data/mnist'
FMNI... | 2,997 | 29.907216 | 114 | py |
spenser | spenser-main/spenser/evaluator.py | from spenser.data import load_dataset
from time import time as t
import torch, torch.nn as nn
import snntorch as snn
from snntorch import surrogate
from snntorch import functional as SF
from snntorch import utils
from typing import OrderedDict
from snntorch import spikegen
DEBUG = True
device = torch.device("cuda:0"... | 19,643 | 32.294915 | 136 | py |
spenser | spenser-main/spenser/individual.py | from spenser.module import Module
from multiprocessing import Pool
from multiprocessing import Queue
from multiprocessing import set_start_method
from multiprocessing import Process
import torch, torch.nn as nn
import traceback
DEBUG = True
def evaluate(args): #pragma: no cover
"""
Function used to deploy... | 7,555 | 30.352697 | 103 | py |
spenser | spenser-main/spenser/libs.py |
# Copyright 2019 Filipe Assuncao
# 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,... | 1,063 | 23.744186 | 74 | py |
HRTransNet | HRTransNet-main/test.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: test.py
@time: 2021/11/25 10:12
"""
import torch
import torch.nn.functional as F
import sys
sys.path.append('./models')
import numpy as np
import os, argparse
import cv2
from models.hrt import HighResolutionTransformer
from data... | 2,167 | 28.297297 | 82 | py |
HRTransNet | HRTransNet-main/data.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: data.py
@time: 2021/11/25 10:14
"""
import torch
import torch.nn as nn
import numpy as np
import os
from PIL import Image
import torch.utils.data as data
import torchvision.transforms as transforms
import random
import numpy as n... | 10,517 | 37.811808 | 127 | py |
HRTransNet | HRTransNet-main/train.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: train.py
@time: 2021/11/25 10:11
"""
import os
import torch
import torch.nn.functional as F
import sys
sys.path.append('./models')
import numpy as np
from datetime import datetime
from models.hrt import HighResolutionTransformer
... | 7,746 | 36.97549 | 137 | py |
HRTransNet | HRTransNet-main/tools/pytorch_utils.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: pytorch_utils.py
@time: 2021/11/25 10:16
"""
import os
def adjust_learning_rate(optimizer, epoch, initial_lr=0.001, decay_epoch=10):
"""Sets the learning rate to the initial LR decayed by 10 every 30 epochs"""
lr = max(in... | 1,672 | 24.348485 | 80 | py |
HRTransNet | HRTransNet-main/models/cnn_trans_fuse.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: cnn_trans_fuse.py
@time: 2021/11/26 10:50
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from thop import profile, clever_format
def conv3x3(in_planes, out_planes, stride=1, has_bias=False):
"3x3 convo... | 5,295 | 33.38961 | 108 | py |
HRTransNet | HRTransNet-main/models/hrt.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: model.py
@time: 2021/11/22 13:50
"""
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.modules.bottleneck_block import Bottleneck, BottleneckDWP
from models.modules.transform... | 27,769 | 34.786082 | 106 | py |
HRTransNet | HRTransNet-main/models/swin_transformer.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: SwinTransformer.py
@time: 2021/5/6 8:23
"""
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import numpy as np
import torch.nn.funct... | 27,843 | 41.380518 | 119 | py |
HRTransNet | HRTransNet-main/models/model.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: model.py
@time: 2021/11/2 14:08
"""
import torch
import torch.nn as nn
import numpy as np
from models.hrt import HighResolutionTransformer
from models.swin_transformer import SwinTransformer
import yaml
path = "../config/hrt_base... | 917 | 26 | 68 | py |
HRTransNet | HRTransNet-main/models/MCGFuse.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: MGFuse.py
@time: 2021/12/6 9:31
"""
import torch
import torch.nn as nn
from models.coordatt import CoordAtt
import numpy as np
class MCG(nn.Module):
def __init__(self, rgb_inchannels, depth_inchannels,h,w):
super(MCG,... | 1,833 | 26.787879 | 79 | py |
HRTransNet | HRTransNet-main/models/coordatt.py | import torch
import torch.nn as nn
import math
import torch.nn.functional as F
from thop import profile, clever_format
class h_sigmoid(nn.Module):
def __init__(self, inplace=True):
super(h_sigmoid, self).__init__()
self.relu = nn.ReLU6(inplace=inplace)
def forward(self, x):
return self... | 1,654 | 26.131148 | 77 | py |
HRTransNet | HRTransNet-main/models/modules/multihead_attention.py | # --------------------------------------------------------
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Modified by RainbowSecret from:
# https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/activation.py#L852
# ------------------------------------------------... | 26,035 | 36.30086 | 115 | py |
HRTransNet | HRTransNet-main/models/modules/basic_block.py | # --------------------------------------------------------
# High Resolution Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Rao Fu, RainbowSecret
# --------------------------------------------------------
import os
import pdb
import logging
import tor... | 1,590 | 23.859375 | 69 | py |
HRTransNet | HRTransNet-main/models/modules/multihead_isa_attention.py | # --------------------------------------------------------
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Modified by Lang Huang, RainbowSecret from:
# https://github.com/openseg-group/openseg.pytorch/blob/master/lib/models/modules/isa_block.py
# --------------------------... | 5,672 | 34.236025 | 102 | py |
HRTransNet | HRTransNet-main/models/modules/transformer_block.py | # --------------------------------------------------------
# High Resolution Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Rao Fu, RainbowSecret
# --------------------------------------------------------
import os
import pdb
import math
import loggin... | 4,709 | 31.708333 | 87 | py |
HRTransNet | HRTransNet-main/models/modules/bottleneck_block.py | # --------------------------------------------------------
# High Resolution Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Rao Fu, RainbowSecret
# --------------------------------------------------------
import os
import logging
import torch.nn as nn... | 2,891 | 26.807692 | 80 | py |
HRTransNet | HRTransNet-main/models/modules/ffn_block.py | # --------------------------------------------------------
# High Resolution Transformer
# Copyright (c) 2021 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Rao Fu, RainbowSecret
# --------------------------------------------------------
import torch
import torch.nn as nn
class Ml... | 3,338 | 28.548673 | 77 | py |
HRTransNet | HRTransNet-main/models/cnn/cnn_resnet.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: cnn_resnet.py
@time: 2021/11/22 13:16
"""
import torch
from torch import Tensor
import torch.nn as nn
# from .utils import load_state_dict_from_url
from typing import Type, Any, Callable, Union, List, Optional
__all__ = ['ResNet... | 15,586 | 37.870324 | 111 | py |
HRTransNet | HRTransNet-main/models/decoder_fuse/transformer_dec_fuse.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: transformer_dec_fuse.py
@time: 2021/12/8 01:00
"""
import copy
from typing import Optional, List
import torch
import torch.nn.functional as F
from torch import nn, Tensor
import numpy as np
import time
from models.decoder_fuse.tr... | 8,350 | 42.26943 | 162 | py |
HRTransNet | HRTransNet-main/models/decoder_fuse/transformer_block.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: transformer_block.py
@time: 2021/12/8 11:15
"""
import torch
import torch.nn as nn
import numpy as np
def get_sinusoid_encoding(n_position, d_hid):
''' Sinusoid position encoding table '''
def get_position_angle_vec(posi... | 724 | 29.208333 | 95 | py |
HRTransNet | HRTransNet-main/models/decoder_fuse/position_encoding.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Various positional encodings for the transformer.
"""
import math
import torch
from torch import nn
# from util.misc import NestedTensor
class PositionEmbeddingSine(nn.Module):
"""
This is a more standard version of the position embed... | 3,338 | 36.1 | 103 | py |
HRTransNet | HRTransNet-main/models/decoder_fuse/utils/transformrer_utils.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: utils.py
@time: 2021/12/8 13:25
"""
import torch
import torch.nn as nn
import numpy as np
import torch
import numpy as np
from models.decoder_fuse.utils.misc import NestedTensor
class Preprocessor(object):
def __init__(self)... | 2,338 | 40.035088 | 100 | py |
HRTransNet | HRTransNet-main/models/decoder_fuse/utils/misc.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import os
import subprocess
import time
from collections import defaultdict, deque
import datetime
import pickle
from typing import Optional, List... | 15,497 | 32.115385 | 141 | py |
HRTransNet | HRTransNet-main/models/transformer/swin_transformer.py | # -*- coding: utf-8 -*-
"""
@author: caigentan@AnHui University
@software: PyCharm
@file: swin_transformer.py
@time: 2021/11/26 16:08
"""
import torch
import torch.nn as nn
import torch.utils.checkpoint as checkpoint
from timm.models.layers import DropPath, to_2tuple, trunc_normal_
import numpy as np
import torch.nn.fu... | 24,869 | 38.983923 | 119 | py |
nflgame | nflgame-master/nflgame/update_sched.py | from __future__ import absolute_import, division, print_function
import argparse
import time
import json
import os
import sys
import urllib2
from collections import OrderedDict
import xml.dom.minidom as xml
import nflgame
def year_phase_week(year=None, phase=None, week=None):
cur_year, _ = nflgame.live.current_y... | 6,986 | 34.467005 | 88 | py |
irismil | irismil-main/mil.py | import os
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.layers import Dense, TimeDistributed, Input, Lambda, Softmax, LeakyReLU, BatchNormalization, Dropout, Conv1D, Flatten, MaxPooling1D
from... | 16,703 | 39.941176 | 175 | py |
irismil | irismil-main/model_runner.py | # some configuration
EPOCHS = 200 # upper limit of epochs
DATA_FILE = "IRISMIL_dataset_10000_bags.npz"
BASENAME = "full10" # basename used in stored results
# arguments
import os, sys
if len(sys.argv) != 4:
print("""Usage: python abMIL_runner.py <model> <parameter> <runs_per_fold>
model: ibMIL or abMIL
par... | 7,481 | 39.663043 | 189 | py |
efsl | efsl-main/train_classifier.py | import os
import yaml
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from tqdm import tqdm
from tensorboardX import SummaryWriter
import utils
import utils.few_shot as fs
from utils.get_data_loader import get_fs_loader, get_classification_loader
from utils.get_model import get_... | 7,328 | 31.865471 | 131 | py |
efsl | efsl-main/test_efsl.py | import torch
import torch.nn as nn
from tqdm import tqdm
import os
import pickle as pkl
import utils
import utils.few_shot as fs
from utils.get_data_loader import get_fs_loader
from utils.get_model import get_model
from utils.get_config import get_config_test as get_config
from pathlib import Path
def main(config):... | 2,448 | 27.476744 | 142 | py |
efsl | efsl-main/train_efsl.py | import os
import yaml
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from tensorboardX import SummaryWriter
import utils
import utils.few_shot as fs
from utils.get_data_loader import get_fs_loader
from utils.get_model import get_model
from utils.get_config import get_config_train_fsl as ... | 7,401 | 31.60793 | 167 | py |
efsl | efsl-main/models/resnet_new.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.distributions import Bernoulli
from .models import register
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... | 12,664 | 33.986188 | 120 | py |
efsl | efsl-main/models/classifier.py | import math
import torch
import torch.nn as nn
import models
import utils
from .models import register
@register('classifier')
class Classifier(nn.Module):
def __init__(self, encoder, encoder_args,
classifier, classifier_args):
super().__init__()
self.encoder = models.make(... | 1,883 | 17.291262 | 74 | py |
efsl | efsl-main/models/relation_net.py | import torch
import torch.nn as nn
from .models import register
from .masking_utils import encoder_wrapper
import models
from .masking_utils import MultiBlock
@register('relation-net')
class RelationNet(nn.Module):
def __init__(self, encoder, encoder_args, method='cos', temp=10., temp_learnable=True, **kwargs):
... | 1,941 | 33.070175 | 153 | py |
efsl | efsl-main/models/masking_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import models
import utils
from .models import register
from .masking_utils import encoder_wrapper
@register('masking-model')
class MaskingModel(nn.Module):
def __init__(self, encoder, encoder_args, masking, masking_args):
super... | 2,376 | 36.140625 | 121 | py |
efsl | efsl-main/models/models.py | import torch
models = {}
def register(name):
def decorator(cls):
models[name] = cls
return cls
return decorator
def make(name, **kwargs):
if name is None:
return None
model = models[name](**kwargs)
if torch.cuda.is_available():
model.cuda()
return model
de... | 1,061 | 23.136364 | 126 | py |
efsl | efsl-main/models/cosine.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import models
import utils
from .models import register
from .masking_utils import encoder_wrapper
@register('cosine')
class Cosine(nn.Module):
def __init__(self, encoder, encoder_args={}, method='cos', temp=10., temp_learnabl... | 1,373 | 31.714286 | 111 | py |
efsl | efsl-main/models/feat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from .models import register
from .masking_utils import encoder_wrapper
import models
import utils
@register('feat')
class Feat(nn.Module):
def __init__(self, encoder, encoder_args, method='cos', temp=10., temp_learnable=True, *... | 4,364 | 34.778689 | 111 | py |
efsl | efsl-main/models/masking_utils.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .models import register
from .resnet_new import conv3x3, DropBlock, SELayer, BasicBlock
@register('mean-aggregator')
class MeanAggregator(nn.Module):
def __init__(self):
super().__init__()
def forward(self, x):
return t... | 8,492 | 35.926087 | 164 | py |
efsl | efsl-main/utils/get_data_loader.py | import utils
from data.dataset import CustomDataset
from data.sampler import EpisodicSampler
from data.dataset import TrainDataset
from torch.utils.data import DataLoader
def get_fs_loader(sub_dsname, config):
if config.get(sub_dsname) is not None:
dataset = CustomDataset(config[sub_dsname], **config[f'{s... | 1,538 | 37.475 | 140 | py |
efsl | efsl-main/utils/few_shot.py | import torch
import utils
import torch.nn.functional as F
def split_shot_query(data, way, shot, query, pseudo, ep_per_batch=1):
img_shape = data.shape[1:]
data = data.view(ep_per_batch, way, shot + query + pseudo, *img_shape)
x_shot, x_query, x_pseudo = data.split([shot, query, pseudo], dim=2)
x_shot... | 1,437 | 30.955556 | 91 | py |
efsl | efsl-main/utils/get_model.py | import torch
import torch.nn as nn
import models
def get_model(config):
if config.get('model_checkpoint') is not None:
saved_model = torch.load(config['model_checkpoint'])
model = models.load(saved_model)
else:
model = models.make(name=config['model'], **config['model_args'])
... | 995 | 32.2 | 73 | py |
efsl | efsl-main/utils/__init__.py | import os
import shutil
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD, Adam
from torch.optim.lr_scheduler import MultiStepLR
from . import few_shot
from collections.abc import Mapping
from flatten_dict import flatten
import pickle as pkl
f... | 6,238 | 24.887967 | 76 | py |
efsl | efsl-main/data/sampler.py | import numpy as np
import torch
class EpisodicSampler:
def __init__(self, dataset, n_batch, n_way, n_shot, n_query, n_pseudo, episodes_per_batch=1):
self.dataset = dataset
self.n_batch = n_batch
self.n_way = n_way
self.n_shot = n_shot
self.n_query = n_query
self.n_... | 3,097 | 45.939394 | 154 | py |
efsl | efsl-main/data/dataset.py | from PIL import Image
import numpy as np
import os
import pickle as pkl
from torch.utils.data import Dataset
from torchvision import transforms
import h5py as hp
import utils
import cv2 as cv
def trim_target_cls(src_classes, data_root, dataset, ilsvrc_int_id2unique_int_id, wnid2unique_int_id):
if dataset in ['cif... | 18,185 | 43.793103 | 190 | py |
pytorch-maml-rl | pytorch-maml-rl-master/test.py | import maml_rl.envs
import gym
import torch
import json
import numpy as np
from tqdm import trange
from maml_rl.baseline import LinearFeatureBaseline
from maml_rl.samplers import MultiTaskSampler
from maml_rl.utils.helpers import get_policy_for_env, get_input_size
from maml_rl.utils.reinforcement_learning import get_r... | 4,103 | 37.35514 | 88 | py |
pytorch-maml-rl | pytorch-maml-rl-master/train.py | import gym
import torch
import json
import os
import yaml
from tqdm import trange
import maml_rl.envs
from maml_rl.metalearners import MAMLTRPO
from maml_rl.baseline import LinearFeatureBaseline
from maml_rl.samplers import MultiTaskSampler
from maml_rl.utils.helpers import get_policy_for_env, get_input_size
from maml... | 4,670 | 38.252101 | 84 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/baseline.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
class LinearFeatureBaseline(nn.Module):
"""Linear baseline based on handcrafted features, as described in [1]
(Supplementary Material 2).
[1] Yan Duan, Xi Chen, Rein Houthooft, John Schulman, Pieter Ab... | 3,151 | 36.975904 | 87 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/episode.py | import numpy as np
import torch
import torch.nn.functional as F
from maml_rl.utils.torch_utils import weighted_normalize
class BatchEpisodes(object):
def __init__(self, batch_size, gamma=0.95, device='cpu'):
self.batch_size = batch_size
self.gamma = gamma
self.device = device
self... | 6,016 | 36.842767 | 85 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/policies/normal_mlp.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Independent, Normal
from collections import OrderedDict
from maml_rl.policies.policy import Policy, weight_init
class NormalMLPPolicy(Policy):
"""Policy network based on a multi-layer perceptron (MLP), w... | 2,325 | 38.423729 | 142 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/policies/policy.py | import torch
import torch.nn as nn
from collections import OrderedDict
def weight_init(module):
if isinstance(module, nn.Linear):
nn.init.xavier_uniform_(module.weight)
module.bias.data.zero_()
class Policy(nn.Module):
def __init__(self, input_size, output_size):
super(Policy, self)._... | 1,240 | 32.540541 | 81 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/policies/categorical_mlp.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Categorical
from collections import OrderedDict
from maml_rl.policies.policy import Policy, weight_init
class CategoricalMLPPolicy(Policy):
"""Policy network based on a multi-layer perceptron (MLP), with a
`Cat... | 2,009 | 40.020408 | 148 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/tests/test_episode.py | import pytest
import torch
from maml_rl.episode import BatchEpisodes
from maml_rl.envs.utils.sync_vector_env import SyncVectorEnv
from maml_rl.samplers.sampler import make_env
from maml_rl.tests.utils import make_unittest_env
@pytest.mark.parametrize('batch_size', [1, 8])
def test_batch_episodes(batch_size):
ep... | 1,793 | 32.222222 | 75 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/tests/utils/test_torch_utils.py | import pytest
import numpy as np
import torch
import torch.nn as nn
from maml_rl.utils.torch_utils import (weighted_mean, weighted_normalize,
vector_to_parameters)
def test_weighted_mean():
lengths = [2, 3, 7, 5, 11]
# Inputs
inputs_np = np.random.rand(13, 5).astyp... | 3,711 | 28 | 87 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/samplers/multi_task_sampler.py | import torch
import torch.multiprocessing as mp
import asyncio
import threading
import time
from datetime import datetime, timezone
from copy import deepcopy
from maml_rl.samplers.sampler import Sampler, make_env
from maml_rl.envs.utils.sync_vector_env import SyncVectorEnv
from maml_rl.episode import BatchEpisodes
fr... | 13,271 | 38.736527 | 87 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/metalearners/base.py | import torch
import asyncio
from maml_rl.samplers import MultiTaskSampler
class GradientBasedMetaLearner(object):
def __init__(self, policy, device='cpu'):
self.device = torch.device(device)
self.policy = policy
self.policy.to(self.device)
self._event_loop = asyncio.get_event_loop... | 672 | 28.26087 | 68 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/metalearners/maml_trpo.py | import torch
from torch.nn.utils.convert_parameters import parameters_to_vector
from torch.distributions.kl import kl_divergence
from maml_rl.samplers import MultiTaskSampler
from maml_rl.metalearners.base import GradientBasedMetaLearner
from maml_rl.utils.torch_utils import (weighted_mean, detach_distribution,
... | 7,273 | 39.865169 | 83 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/utils/optimization.py | import torch
def conjugate_gradient(f_Ax, b, cg_iters=10, residual_tol=1e-10):
p = b.clone().detach()
r = b.clone().detach()
x = torch.zeros_like(b).float()
rdotr = torch.dot(r, r)
for i in range(cg_iters):
z = f_Ax(p).detach()
v = rdotr / torch.dot(p, z)
x += v * p
... | 527 | 21.956522 | 65 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/utils/torch_utils.py | import torch
import numpy as np
from torch.distributions import Categorical, Independent, Normal
from torch.nn.utils.convert_parameters import _check_param_device
def weighted_mean(tensor, lengths=None):
if lengths is None:
return torch.mean(tensor)
if tensor.dim() < 2:
raise ValueError('Expec... | 2,436 | 32.847222 | 78 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/utils/helpers.py | import gym
import torch
from functools import reduce
from operator import mul
from maml_rl.policies import CategoricalMLPPolicy, NormalMLPPolicy
def get_policy_for_env(env, hidden_sizes=(100, 100), nonlinearity='relu'):
continuous_actions = isinstance(env.action_space, gym.spaces.Box)
input_size = get_input... | 1,074 | 33.677419 | 74 | py |
pytorch-maml-rl | pytorch-maml-rl-master/maml_rl/utils/reinforcement_learning.py | import numpy as np
from maml_rl.utils.torch_utils import weighted_mean, to_numpy
def value_iteration(transitions, rewards, gamma=0.95, theta=1e-5):
rewards = np.expand_dims(rewards, axis=2)
values = np.zeros(transitions.shape[0], dtype=np.float32)
delta = np.inf
while delta >= theta:
q_values ... | 1,436 | 34.925 | 81 | py |
SimKGC | SimKGC-main/main.py | import torch
import json
import torch.backends.cudnn as cudnn
from config import args
from trainer import Trainer
from logger_config import logger
def main():
ngpus_per_node = torch.cuda.device_count()
cudnn.benchmark = True
logger.info("Use {} gpus for training".format(ngpus_per_node))
trainer = T... | 520 | 21.652174 | 90 | py |
SimKGC | SimKGC-main/doc.py | import os
import json
import torch
import torch.utils.data.dataset
from typing import Optional, List
from config import args
from triplet import reverse_triplet
from triplet_mask import construct_mask, construct_self_negative_mask
from dict_hub import get_entity_dict, get_link_graph, get_tokenizer
from logger_config ... | 7,685 | 34.748837 | 100 | py |
SimKGC | SimKGC-main/evaluate.py | import os
import json
import tqdm
import torch
from time import time
from typing import List, Tuple
from dataclasses import dataclass, asdict
from config import args
from doc import load_data, Example
from predict import BertPredictor
from dict_hub import get_entity_dict, get_all_triplet_dict
from triplet import Enti... | 7,456 | 40.893258 | 120 | py |
SimKGC | SimKGC-main/triplet_mask.py | import torch
from typing import List
from config import args
from dict_hub import get_train_triplet_dict, get_entity_dict, EntityDict, TripletDict
entity_dict: EntityDict = get_entity_dict()
train_triplet_dict: TripletDict = get_train_triplet_dict() if not args.is_test else None
def construct_mask(row_exs: List, c... | 1,875 | 34.396226 | 96 | py |
SimKGC | SimKGC-main/utils.py | import os
import glob
import torch
import shutil
import numpy as np
import torch.nn as nn
from logger_config import logger
class AttrDict:
pass
def save_checkpoint(state: dict, is_best: bool, filename: str):
torch.save(state, filename)
if is_best:
shutil.copyfile(filename, os.path.dirname(file... | 3,102 | 28.552381 | 85 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.