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 |
|---|---|---|---|---|---|---|
RandStainNA | RandStainNA-master/classification/timm/models/layers/global_context.py | """ Global Context Attention Block
Paper: `GCNet: Non-local Networks Meet Squeeze-Excitation Networks and Beyond`
- https://arxiv.org/abs/1904.11492
Official code consulted as reference: https://github.com/xvjiarui/GCNet
Hacked together by / Copyright 2021 Ross Wightman
"""
from torch import nn as nn
import torc... | 2,445 | 34.970588 | 105 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/activations.py | """ Activations
A collection of activations fn and modules with a common interface so that they can
easily be swapped. All have an `inplace` arg even if not used.
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch import nn as nn
from torch.nn import functional as F
def swish(x, inplace:... | 4,040 | 26.678082 | 107 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/eca.py | """
ECA module from ECAnet
paper: ECA-Net: Efficient Channel Attention for Deep Convolutional Neural Networks
https://arxiv.org/abs/1910.03151
Original ECA model borrowed from https://github.com/BangguWu/ECANet
Modified circular ECA implementation and adaption for use in timm package
by Chris Ha https://github.com/V... | 6,386 | 42.746575 | 108 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/space_to_depth.py | import torch
import torch.nn as nn
class SpaceToDepth(nn.Module):
def __init__(self, block_size=4):
super().__init__()
assert block_size == 4
self.bs = block_size
def forward(self, x):
N, C, H, W = x.size()
x = x.view(N, C, H // self.bs, self.bs, W // self.bs, self.bs)... | 1,750 | 31.425926 | 102 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/create_attn.py | """ Attention Factory
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
from functools import partial
from .bottleneck_attn import BottleneckAttn
from .cbam import CbamModule, LightCbamModule
from .eca import EcaModule, CecaModule
from .gather_excite import GatherExcite
from .global_context import Gl... | 3,526 | 38.188889 | 109 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/median_pool.py | """ Median Pool
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch.nn as nn
import torch.nn.functional as F
from .helpers import to_2tuple, to_4tuple
class MedianPool2d(nn.Module):
""" Median pool (usable as median filter when stride=1) module.
Args:
kernel_size: size of pooling kern... | 1,737 | 33.76 | 87 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/test_time_pool.py | """ Test Time Pooling (Average-Max Pool)
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
from torch import nn
import torch.nn.functional as F
from .adaptive_avgmax_pool import adaptive_avgmax_pool2d
_logger = logging.getLogger(__name__)
class TestTimePoolHead(nn.Module):
def __init__(sel... | 1,995 | 36.660377 | 101 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/selective_kernel.py | """ Selective Kernel Convolution/Attention
Paper: Selective Kernel Networks (https://arxiv.org/abs/1903.06586)
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch import nn as nn
from .conv_bn_act import ConvBnAct
from .helpers import make_divisible
from .trace_utils import _assert
def _k... | 5,349 | 43.214876 | 116 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/norm_act.py | """ Normalization + Activation Layers
"""
import torch
from torch import nn as nn
from torch.nn import functional as F
from .create_act import get_act_layer
class BatchNormAct2d(nn.BatchNorm2d):
"""BatchNorm + Activation
This module performs BatchNorm + Activation in a manner that will remain backwards
... | 3,545 | 40.232558 | 109 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/create_conv2d.py | """ Create Conv2d Factory Method
Hacked together by / Copyright 2020 Ross Wightman
"""
from .mixed_conv2d import MixedConv2d
from .cond_conv2d import CondConv2d
from .conv2d_same import create_conv2d_pad
def create_conv2d(in_channels, out_channels, kernel_size, **kwargs):
""" Select a 2d convolution implementat... | 1,500 | 45.90625 | 101 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/create_norm_act.py | """ NormAct (Normalizaiton + Activation Layer) Factory
Create norm + act combo modules that attempt to be backwards compatible with separate norm + act
isntances in models. Where these are used it will be possible to swap separate BN + act layers with
combined modules like IABN or EvoNorms.
Hacked together by / Copyr... | 3,450 | 40.083333 | 118 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/padding.py | """ Padding Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
from typing import List, Tuple
import torch.nn.functional as F
# Calculate symmetric padding for a convolution
def get_padding(kernel_size: int, stride: int = 1, dilation: int = 1, **_) -> int:
padding = ((stride - 1) + dilati... | 2,167 | 37.035088 | 99 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/drop.py | """ DropBlock, DropPath
PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.
Papers:
DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)
Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.09382)
Code:
DropBlock impl ins... | 6,732 | 39.806061 | 118 | py |
RandStainNA | RandStainNA-master/classification/timm/models/layers/inplace_abn.py | import torch
from torch import nn as nn
try:
from inplace_abn.functions import inplace_abn, inplace_abn_sync
has_iabn = True
except ImportError:
has_iabn = False
def inplace_abn(x, weight, bias, running_mean, running_var,
training=True, momentum=0.1, eps=1e-05, activation="leaky_re... | 3,353 | 37.113636 | 111 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/madgrad.py | """ PyTorch MADGRAD optimizer
MADGRAD: https://arxiv.org/abs/2101.11075
Code from: https://github.com/facebookresearch/madgrad
"""
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import ma... | 6,893 | 36.264865 | 120 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/adahessian.py | """ AdaHessian Optimizer
Lifted from https://github.com/davda54/ada-hessian/blob/master/ada_hessian.py
Originally licensed MIT, Copyright 2020, David Samuel
"""
import torch
class Adahessian(torch.optim.Optimizer):
"""
Implements the AdaHessian algorithm from "ADAHESSIAN: An Adaptive Second OrderOptimizer fo... | 6,535 | 40.630573 | 129 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/radam.py | """RAdam Optimizer.
Implementation lifted from: https://github.com/LiyuanLucasLiu/RAdam
Paper: `On the Variance of the Adaptive Learning Rate and Beyond` - https://arxiv.org/abs/1908.03265
"""
import math
import torch
from torch.optim.optimizer import Optimizer
class RAdam(Optimizer):
def __init__(self, params, ... | 3,468 | 37.544444 | 100 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/nvnovograd.py | """ Nvidia NovoGrad Optimizer.
Original impl by Nvidia from Jasper example:
- https://github.com/NVIDIA/DeepLearningExamples/blob/master/PyTorch/SpeechRecognition/Jasper
Paper: `Stochastic Gradient Methods with Layer-wise Adaptive Moments for Training of Deep Networks`
- https://arxiv.org/abs/1905.11286
"""
im... | 4,856 | 39.140496 | 99 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/adabelief.py | import math
import torch
from torch.optim.optimizer import Optimizer
class AdaBelief(Optimizer):
r"""Implements AdaBelief algorithm. Modified from Adam in PyTorch
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
lr (float, optiona... | 9,827 | 47.653465 | 116 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/adamp.py | """
AdamP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/adamp.py
Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217
Code: https://github.com/clovaai/AdamP
Copyright (c) 2020-present NAVER Corp.
MIT license
"""
impor... | 3,574 | 32.726415 | 117 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/nadam.py | import math
import torch
from torch.optim.optimizer import Optimizer
class Nadam(Optimizer):
"""Implements Nadam algorithm (a variant of Adam based on Nesterov momentum).
It has been proposed in `Incorporating Nesterov Momentum into Adam`__.
Arguments:
params (iterable): iterable of parameters ... | 3,871 | 40.634409 | 109 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/adamw.py | """ AdamW Optimizer
Impl copied from PyTorch master
NOTE: Builtin optim.AdamW is used by the factory, this impl only serves as a Python based reference, will be removed
someday
"""
import math
import torch
from torch.optim.optimizer import Optimizer
class AdamW(Optimizer):
r"""Implements AdamW algorithm.
Th... | 5,147 | 40.853659 | 116 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/adafactor.py | """ Adafactor Optimizer
Lifted from https://github.com/pytorch/fairseq/blob/master/fairseq/optim/adafactor.py
Original header/copyright below.
"""
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source... | 7,459 | 43.404762 | 114 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/rmsprop_tf.py | """ RMSProp modified to behave like Tensorflow impl
Originally cut & paste from PyTorch RMSProp
https://github.com/pytorch/pytorch/blob/063946d2b3f3f1e953a2a3b54e0b34f1393de295/torch/optim/rmsprop.py
Licensed under BSD-Clause 3 (ish), https://github.com/pytorch/pytorch/blob/master/LICENSE
Modifications Copyright 2021... | 6,143 | 42.885714 | 115 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/sgdp.py | """
SGDP Optimizer Implementation copied from https://github.com/clovaai/AdamP/blob/master/adamp/sgdp.py
Paper: `Slowing Down the Weight Norm Increase in Momentum-based Optimizers` - https://arxiv.org/abs/2006.08217
Code: https://github.com/clovaai/AdamP
Copyright (c) 2020-present NAVER Corp.
MIT license
"""
import ... | 2,296 | 31.352113 | 110 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/lars.py | """ PyTorch LARS / LARC Optimizer
An implementation of LARS (SGD) + LARC in PyTorch
Based on:
* PyTorch SGD: https://github.com/pytorch/pytorch/blob/1.7/torch/optim/sgd.py#L100
* NVIDIA APEX LARC: https://github.com/NVIDIA/apex/blob/master/apex/parallel/LARC.py
Additional cleanup and modifications to properly su... | 5,255 | 37.933333 | 117 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/lookahead.py | """ Lookahead Optimizer Wrapper.
Implementation modified from: https://github.com/alphadl/lookahead.pytorch
Paper: `Lookahead Optimizer: k steps forward, 1 step back` - https://arxiv.org/abs/1907.08610
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch.optim.optimizer import Optimizer
from c... | 2,463 | 38.741935 | 93 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/optim_factory.py | """ Optimizer Factory w/ Custom Weight Decay
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional
import torch
import torch.nn as nn
import torch.optim as optim
from .adabelief import AdaBelief
from .adafactor import Adafactor
from .adahessian import Adahessian
from .adamp import AdamP
fr... | 8,415 | 37.605505 | 108 | py |
RandStainNA | RandStainNA-master/classification/timm/optim/lamb.py | """ PyTorch Lamb optimizer w/ behaviour similar to NVIDIA FusedLamb
This optimizer code was adapted from the following (starting with latest)
* https://github.com/HabanaAI/Model-References/blob/2b435114fe8e31f159b1d3063b8280ae37af7423/PyTorch/nlp/bert/pretraining/lamb.py
* https://github.com/NVIDIA/DeepLearningExample... | 9,184 | 46.590674 | 129 | py |
RandStainNA | RandStainNA-master/classification/timm/loss/asymmetric_loss.py | import torch
import torch.nn as nn
class AsymmetricLossMultiLabel(nn.Module):
def __init__(self, gamma_neg=4, gamma_pos=1, clip=0.05, eps=1e-8, disable_torch_grad_focal_loss=False):
super(AsymmetricLossMultiLabel, self).__init__()
self.gamma_neg = gamma_neg
self.gamma_pos = gamma_pos
... | 3,225 | 31.918367 | 107 | py |
RandStainNA | RandStainNA-master/classification/timm/loss/cross_entropy.py | """ Cross Entropy w/ smoothing or soft targets
Hacked together by / Copyright 2021 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class LabelSmoothingCrossEntropy(nn.Module):
""" NLL loss with label smoothing.
"""
def __init__(self, smoothing=0.1):
super(Lab... | 1,145 | 29.972973 | 77 | py |
RandStainNA | RandStainNA-master/classification/timm/loss/jsd.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .cross_entropy import LabelSmoothingCrossEntropy
class JsdCrossEntropy(nn.Module):
""" Jensen-Shannon Divergence + Cross-Entropy Loss
Based on impl here: https://github.com/google-research/augmix/blob/master/imagenet.py
From paper: ... | 1,595 | 38.9 | 96 | py |
RandStainNA | RandStainNA-master/classification/timm/loss/binary_cross_entropy.py | """ Binary Cross Entropy w/ a few extras
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryCrossEntropy(nn.Module):
""" BCE with optional one-hot from dense targets, label smoothing, thresholding
N... | 2,030 | 41.3125 | 120 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/jit.py | """ JIT scripting/tracing utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import os
import torch
def set_jit_legacy():
""" Set JIT executor to legacy w/ support for op fusion
This is hopefully a temporary need in 1.5/1.5.1/1.6 to restore performance due to changes
in the JIT exectutor. These... | 1,992 | 38.078431 | 94 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/clip_grad.py | import torch
from timm.utils.agc import adaptive_clip_grad
def dispatch_clip_grad(parameters, value: float, mode: str = 'norm', norm_type: float = 2.0):
""" Dispatch to gradient clipping method
Args:
parameters (Iterable): model parameters to clip
value (float): clipping value/factor/norm, m... | 796 | 32.208333 | 93 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/cuda.py | """ CUDA / AMP utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
try:
from apex import amp
has_apex = True
except ImportError:
amp = None
has_apex = False
from .clip_grad import dispatch_clip_grad
class ApexScaler:
state_dict_key = "amp"
def __call__(self, loss, opti... | 1,703 | 29.428571 | 111 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/model.py | """ Model / state_dict utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import fnmatch
import torch
from torchvision.ops.misc import FrozenBatchNorm2d
from .model_ema import ModelEma
def unwrap_model(model):
if isinstance(model, ModelEma):
return unwrap_model(model.ema)
else:
ret... | 12,085 | 43.109489 | 131 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/random.py | import random
import numpy as np
import torch
def random_seed(seed=42, rank=0):
torch.manual_seed(seed + rank)
np.random.seed(seed + rank)
random.seed(seed + rank)
| 178 | 16.9 | 34 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/distributed.py | """ Distributed training/validation utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
from torch import distributed as dist
from .model import unwrap_model
def reduce_tensor(tensor, n):
rt = tensor.clone()
dist.all_reduce(rt, op=dist.ReduceOp.SUM)
rt /= n
return rt
def distr... | 896 | 29.931034 | 75 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/checkpoint_saver.py | """ Checkpoint Saver
Track top-n training checkpoints and maintain recovery checkpoints on specified intervals.
Hacked together by / Copyright 2020 Ross Wightman
"""
import glob
import operator
import os
import logging
import json #12.24加入
import torch
from .model import unwrap_model, get_state_dict
_logger = lo... | 9,243 | 44.313725 | 278 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/agc.py | """ Adaptive Gradient Clipping
An impl of AGC, as per (https://arxiv.org/abs/2102.06171):
@article{brock2021high,
author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan},
title={High-Performance Large-Scale Image Recognition Without Normalization},
journal={arXiv preprint arXiv:},
year={2021... | 1,624 | 36.790698 | 103 | py |
RandStainNA | RandStainNA-master/classification/timm/utils/model_ema.py | """ Exponential Moving Average (EMA) of model updates
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
from collections import OrderedDict
from copy import deepcopy
import torch
import torch.nn as nn
_logger = logging.getLogger(__name__)
class ModelEma:
""" Model Exponential Moving Average ... | 5,670 | 43.653543 | 102 | py |
RandStainNA | RandStainNA-master/classification/timm/data/dataset_factory.py | """ Dataset Factory
Hacked together by / Copyright 2021, Ross Wightman
"""
import os
from torchvision.datasets import CIFAR100, CIFAR10, MNIST, QMNIST, KMNIST, FashionMNIST, ImageNet, ImageFolder
try:
from torchvision.datasets import Places365
has_places365 = True
except ImportError:
has_places365 = False... | 5,706 | 37.560811 | 110 | py |
RandStainNA | RandStainNA-master/classification/timm/data/dataset.py | """ Quick n Simple Image Folder, Tarfile based DataSet
Hacked together by / Copyright 2019, Ross Wightman
"""
import torch.utils.data as data
import os
import torch
import logging
from PIL import Image
from .parsers import create_parser
_logger = logging.getLogger(__name__)
_ERROR_RETRY = 50
class ImageDataset(... | 4,805 | 30.411765 | 108 | py |
RandStainNA | RandStainNA-master/classification/timm/data/mixup.py | """ Mixup and Cutmix
Papers:
mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412)
CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899)
Code Reference:
CutMix: https://github.com/clovaai/CutMix-PyTorch
Hacked together by / Co... | 14,722 | 45.444795 | 120 | py |
RandStainNA | RandStainNA-master/classification/timm/data/transforms_factory.py | """ Transforms Factory
Factory methods for building image transforms for use with TIMM (PyTorch Image Models)
Hacked together by / Copyright 2019, Ross Wightman
"""
import math
import torch
from torchvision import transforms
from torchvision.transforms import RandomErasing as RandomErasing_torch #1.23添加
from torchvis... | 17,307 | 42.27 | 246 | py |
RandStainNA | RandStainNA-master/classification/timm/data/distributed_sampler.py | import math
import torch
from torch.utils.data import Sampler
import torch.distributed as dist
class OrderedDistributedSampler(Sampler):
"""Sampler that restricts data loading to a subset of the dataset.
It is especially useful in conjunction with
:class:`torch.nn.parallel.DistributedDataParallel`. In suc... | 5,125 | 38.430769 | 113 | py |
RandStainNA | RandStainNA-master/classification/timm/data/random_erasing.py | """ Random Erasing (Cutout)
Originally inspired by impl at https://github.com/zhunzhong07/Random-Erasing, Apache 2.0
Copyright Zhun Zhong & Liang Zheng
Hacked together by / Copyright 2019, Ross Wightman
"""
import random
import math
import torch
def _get_pixels(per_pixel, rand_color, patch_size, dtype=torch.float32... | 4,767 | 44.846154 | 95 | py |
RandStainNA | RandStainNA-master/classification/timm/data/loader.py | """ Loader Factory, Fast Collate, CUDA Prefetcher
Prefetcher and Fast Collate inspired by NVIDIA APEX example at
https://github.com/NVIDIA/apex/commit/d5e2bb4bdeedd27b1dfaf5bb2b24d6c000dee9be#diff-cf86c282ff7fba81fad27a559379d5bf
Hacked together by / Copyright 2019, Ross Wightman
"""
import random
from functools impo... | 12,817 | 33.926431 | 118 | py |
RandStainNA | RandStainNA-master/classification/timm/data/transforms.py | import torch
import torchvision.transforms.functional as F
from torchvision import transforms #2.13加入
try:
from torchvision.transforms.functional import InterpolationMode
has_interpolation_mode = True
except ImportError:
has_interpolation_mode = False
from PIL import Image, ImageFilter #1.20加入
import warnin... | 28,278 | 40.103198 | 174 | py |
RandStainNA | RandStainNA-master/classification/timm/data/parsers/parser_tfds.py | """ Dataset parser interface that wraps TFDS datasets
Wraps many (most?) TFDS image-classification datasets
from https://github.com/tensorflow/datasets
https://www.tensorflow.org/datasets/catalog/overview#image_classification
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
import torch
import torch.... | 15,819 | 52.087248 | 120 | py |
RandStainNA | RandStainNA-master/classification/tests/test_layers.py | import pytest
import torch
import torch.nn as nn
import platform
import os
from timm.models.layers import create_act_layer, get_act_layer, set_layer_config
class MLP(nn.Module):
def __init__(self, act_layer="relu", inplace=True):
super(MLP, self).__init__()
self.fc1 = nn.Linear(1000, 100)
... | 1,644 | 21.847222 | 80 | py |
RandStainNA | RandStainNA-master/classification/tests/test_models.py | import pytest
import torch
import platform
import os
import fnmatch
try:
from torchvision.models.feature_extraction import create_feature_extractor, get_graph_node_names, NodePathTracer
has_fx_feature_extraction = True
except ImportError:
has_fx_feature_extraction = False
import timm
from timm import list... | 20,064 | 42.243534 | 119 | py |
RandStainNA | RandStainNA-master/classification/tests/test_utils.py | from torch.nn.modules.batchnorm import BatchNorm2d
from torchvision.ops.misc import FrozenBatchNorm2d
import timm
from timm.utils.model import freeze, unfreeze
def test_freeze_unfreeze():
model = timm.create_model('resnet18')
# Freeze all
freeze(model)
# Check top level module
assert model.fc.we... | 1,978 | 33.719298 | 65 | py |
RandStainNA | RandStainNA-master/classification/tests/test_optim.py | """ Optimzier Tests
These tests were adapted from PyTorch' optimizer tests.
"""
import math
import pytest
import functools
from copy import deepcopy
import torch
from torch.testing._internal.common_utils import TestCase
from torch.autograd import Variable
from timm.scheduler import PlateauLRScheduler
from timm.opti... | 24,464 | 32.331063 | 114 | py |
RandStainNA | RandStainNA-master/segmentation/CA25.py | from email.mime import base
from CA25net import *
import scipy.io
import numpy as np
import time
import torch
# from shutil import copyfile
# device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
device = 'cpu'
print(device)
base_dir = '/root/autodl-tmp/pycharm_project_CA2.5'
train_path = '/root/autodl-tmp/MoNuSe... | 5,784 | 31.683616 | 201 | py |
RandStainNA | RandStainNA-master/segmentation/CIA.py | from CIAnet import *
import scipy.io
import numpy as np
import time
import os
from PIL import Image
from torchvision import transforms
from torch.utils.data import DataLoader,TensorDataset
from tqdm import tqdm
import yaml
import random
# from Dataset import ciaData
from transform import color_norm_jitter, HEDJitter, L... | 22,675 | 46.143451 | 246 | py |
RandStainNA | RandStainNA-master/segmentation/transform.py | import torch
import torchvision.transforms.functional as F
from torchvision import transforms #2.13加入
try:
from torchvision.transforms.functional import InterpolationMode
has_interpolation_mode = True
except ImportError:
has_interpolation_mode = False
from PIL import Image, ImageFilter #1.20加入
import warnin... | 15,678 | 44.184438 | 174 | py |
RandStainNA | RandStainNA-master/segmentation/CIA_tta.py | from CIAnet import *
import scipy.io
import numpy as np
import time
import os
from PIL import Image
from torchvision import transforms
from torch.utils.data import DataLoader,TensorDataset
from tqdm import tqdm
import yaml
import random
# from Dataset import ciaData
from transform import color_norm_jitter, HEDJitter, L... | 24,432 | 46.350775 | 246 | py |
RandStainNA | RandStainNA-master/segmentation/CIAnet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
import math
from torchvision.io import read_image
from torch.utils.data import Dataset,DataLoader,TensorDataset
from os import listdir
import os
from PIL import Image
from torchvision import transforms
device = 'cuda:0' if torch.cuda... | 14,754 | 33.717647 | 149 | py |
RandStainNA | RandStainNA-master/segmentation/CA25net.py | import numpy as np
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from torchvision import models
from torch.utils.data import Dataset,DataLoader,TensorDataset
from torch.autograd import Variable
from os import listdir
from torchvision.io import read_imag... | 16,634 | 34.697425 | 149 | py |
RandStainNA | RandStainNA-master/segmentation/colornorm/Reinhard_quick.py | import cv2
import numpy as np
import time
import copy
from skimage import color, io
from PIL import Image
# 到时候可以尝试numpy优化
def quick_loop(image, image_avg, image_std, temp_avg, temp_std, isHed=False):
# for k in range(3):
# image_new[:,:,k] = (image[:,:,k] - image_avg[k]) * (temp_std[k] / (image_std[k])... | 6,783 | 37.11236 | 154 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/scotland_carbon/src/grid_search.py | import numpy as np
import pandas as pd
import joblib
import itertools
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import cross_validate, ShuffleSplit
f... | 8,751 | 47.353591 | 279 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/scotland_carbon/src/train.py | import numpy as np
import pandas as pd
import joblib
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, mean_absolute_percentage_error
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.ensemble import RandomForestRegressor
import xgboost
from utils import load_csv_to_pd, FE... | 3,173 | 37.240964 | 127 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-AGB/tuning.py |
def xgb_maxdepth_childweight(params, dtrain, dtest):
params['eval_metric'] = "mae"
gridsearch_params = [
(max_depth, min_child_weight)
for max_depth in range(2,12,2)
for min_child_weight in range(1,6)
]
# Define initial best params and MAE
min_mae = float("Inf")
best_p... | 10,956 | 35.523333 | 283 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-AGB/main.py | #import sklearn
import warnings
warnings.filterwarnings(action='ignore', category=DeprecationWarning)
from sklearn.model_selection import cross_val_score, cross_validate, train_test_split, RepeatedKFold, GridSearchCV
from sklearn.ensemble import RandomForestRegressor
from sklearn.datasets import make_classification
fr... | 13,057 | 35.887006 | 152 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-AGB/model_params.py | EXPANDED_SPECIES_TRAIN = ['Category_Non woodland', 'Category_Woodland',
'Species_Assumed woodland', 'Species_Bare area', 'Species_Broadleaved',
'Species_Conifer', 'Species_Failed', 'Species_Felled',
'Species_Grassland', 'Species_Ground prep', 'Species_Low density',
'Species_Mixed mainly broadleaved', 'Speci... | 4,459 | 34.967742 | 107 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/brt/eval.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "models/brtmodel_SoilGrids_nonlog_1... | 2,028 | 26.794521 | 115 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/bag/eval.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "models/bagmodel.joblib.pkl"
print(... | 1,922 | 26.084507 | 115 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/nns/gridsearch.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
import itertools
from models import SimpleNet
i... | 4,373 | 33.714286 | 216 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/nns/eval.py | import torch
from torch import tensor
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
import rasterio
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from sklearn.metrics import r2_sco... | 4,701 | 29.335484 | 119 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/nns/models.py | import torch
import torch.nn as nn
class SimpleNet(nn.Module):
'''
Network Architecture from the Emadi 2020 paper on Norther Iran Soils
Estimated values:
Dropout = 0.2-0.8
Learning rate = 0.001-0.05
Epochs = 100
'''
def __init__(self, input_neurons, layers=5, neurons=50, dro... | 1,213 | 30.947368 | 73 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/nns/train.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from models import SimpleNet
import eval
USE_G... | 4,964 | 33.72028 | 163 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/plsr/eval.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "models/plsrmodel.joblib.pkl"
print... | 1,928 | 26.169014 | 115 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/ensemble/eval_stack.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "models/stackmodel.joblib.pkl"
prin... | 1,934 | 26.253521 | 115 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/ensemble/eval_vot.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "models/votmodel.joblib.pkl"
print(... | 1,922 | 26.084507 | 115 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/rfs/eval.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "models/rfmodel.joblib.pkl"
print("... | 1,916 | 26 | 115 | py |
Carbon-Trading-Verfication | Carbon-Trading-Verfication-master/archive/Estimating-SOC/src/mlp/eval.py | import numpy as np
import pandas as pd
import joblib
import rasterio
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score
from sklearn.ensemble import GradientBoostingRegressor
print("Start")
model_path = "../../models/mlpmodel.joblib.pkl"
... | 1,907 | 25.873239 | 94 | py |
video-classification | video-classification-master/ResNetCRNN/functions.py | import os
import numpy as np
from PIL import Image
from torch.utils import data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from tqdm import tqdm
## ------------------- label conversion tools ------------------ ##
de... | 15,041 | 37.768041 | 149 | py |
video-classification | video-classification-master/ResNetCRNN/ResNetCRNN_check_prediction.py | import os
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import matplotlib.pyplot as plt
from functions import *
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.metrics import accuracy_score
import pandas as pd
import pickle
# set ... | 3,785 | 32.504425 | 139 | py |
video-classification | video-classification-master/ResNetCRNN/UCF101_ResNetCRNN.py | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
import torch.utils.data as data
import torchvision
from torch.autograd import Variable
import matplotlib.pyplot as plt
from functions import *
f... | 9,379 | 34.938697 | 140 | py |
video-classification | video-classification-master/Conv3D/UCF101_3DCNN.py | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
import torch.utils.data as data
import torchvision
from torch.autograd import Variable
import matplotlib.pyplot as plt
from functions import *
f... | 7,929 | 32.744681 | 140 | py |
video-classification | video-classification-master/Conv3D/functions.py | import os
import numpy as np
from PIL import Image
from torch.utils import data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from tqdm import tqdm
## ------------------- label conversion tools ------------------ ##
de... | 15,041 | 37.768041 | 149 | py |
video-classification | video-classification-master/Conv3D/Conv3D_check_prediction.py | import os
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import matplotlib.pyplot as plt
from functions import *
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.metrics import accuracy_score
import pandas as pd
import pickle
# set ... | 3,461 | 30.189189 | 140 | py |
video-classification | video-classification-master/ResNetCRNN_varylength/UCF101_ResNetCRNN_varlen.py | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from torch.optim.lr_scheduler import ReduceLROnPlateau
import torch.utils.data as data
import torchvision
from torch.autograd import Variable
im... | 10,635 | 36.059233 | 140 | py |
video-classification | video-classification-master/ResNetCRNN_varylength/functions.py | import os
import numpy as np
from PIL import Image
from torch.utils import data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from tqdm import tqdm
## ------------------- label conversion tools ------------------ ##
d... | 11,857 | 40.607018 | 149 | py |
video-classification | video-classification-master/ResNetCRNN_varylength/ResNetCRNN_check_prediction.py | import os
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import matplotlib.pyplot as plt
from functions import *
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.metrics import accuracy_score
import pandas as pd
import pickle
# set ... | 3,726 | 32.276786 | 139 | py |
video-classification | video-classification-master/CRNN/UCF101_CRNN.py | import os
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
import torch.utils.data as data
import torchvision
from torch.autograd import Variable
import matplotlib.pyplot as plt
from functions import *
f... | 8,722 | 33.892 | 140 | py |
video-classification | video-classification-master/CRNN/functions.py | import os
import numpy as np
from PIL import Image
from torch.utils import data
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transforms
from tqdm import tqdm
## ------------------- label conversion tools ------------------ ##
de... | 15,041 | 37.768041 | 149 | py |
video-classification | video-classification-master/CRNN/CRNN_check_prediction.py | import os
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
import matplotlib.pyplot as plt
from functions import *
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.metrics import accuracy_score
import pandas as pd
import pickle
# set ... | 3,820 | 32.814159 | 139 | py |
MuHDi | MuHDi-master/muhdi/dataset/base_dataset.py | from pathlib import Path
import random
import numpy as np
from PIL import Image
from torch.utils import data
class BaseDataset(data.Dataset):
def __init__(self, root, list_path, set_,
max_iters, image_size, labels_size, mean):
self.root = Path(root)
self.set = set_
self.li... | 1,648 | 30.113208 | 92 | py |
MuHDi | MuHDi-master/muhdi/dataset/mapillary.py | import json
import warnings
from pathlib import Path
import numpy as np
from PIL import Image
from skimage import color
from torch.utils import data
from muhdi.utils import project_root
from muhdi.utils.serialization import json_load
# from valeodata import download
DEFAULT_INFO_PATH = project_root / 'muhdi/dataset/... | 11,481 | 48.27897 | 104 | py |
MuHDi | MuHDi-master/muhdi/scripts/test.py | import argparse
import os
import os.path as osp
import pprint
import warnings
from torch.utils import data
from muhdi.model.deeplabv2 import get_deeplab_v2
from muhdi.dataset.cityscapes import CityscapesDataSet
from muhdi.dataset.gta5 import GTA5DataSet
from muhdi.dataset.mapillary import MapillaryDataSet
from muhdi.... | 5,988 | 44.371212 | 91 | py |
MuHDi | MuHDi-master/muhdi/scripts/train.py | import argparse
import os
import os.path as osp
import pprint
import random
import warnings
import numpy as np
import yaml
import torch
from torch.utils import data
from muhdi.model.deeplabv2 import get_deeplab_v2, get_deeplab_v2_attention, get_deeplab_v2_muhdi
from muhdi.dataset.gta5 import GTA5DataSet
from muhdi.da... | 12,633 | 46.318352 | 108 | py |
MuHDi | MuHDi-master/muhdi/domain_adaptation/eval_UDA.py | import os.path as osp
import time
import re
import numpy as np
import torch
from torch import nn
from tqdm import tqdm
from muhdi.utils.func import per_class_iu, fast_hist
from muhdi.utils.serialization import pickle_dump, pickle_load
def evaluate_domain_adaptation(models, test_loader_list, cfg,
... | 8,729 | 44.947368 | 115 | py |
MuHDi | MuHDi-master/muhdi/domain_adaptation/train_UDA.py | import os
import math
import sys
from pathlib import Path
import os.path as osp
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.optim as optim
from torch import nn
from tqdm import tqdm
from muhdi.model.discriminator import get_fc_discriminator, restor... | 26,171 | 39.451314 | 152 | py |
MuHDi | MuHDi-master/muhdi/utils/loss.py | import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def cross_entropy_2d(predict, target):
"""
Args:
predict:(n, c, h, w)
target:(n, h, w)
"""
assert not target.requires_grad
assert predict.dim() == 4
assert target.dim() == 3
... | 2,970 | 42.057971 | 96 | py |
MuHDi | MuHDi-master/muhdi/utils/func.py | import numpy as np
import torch
import torch.nn as nn
from muhdi.utils.loss import cross_entropy_2d
def bce_loss(y_pred, y_label):
y_truth_tensor = torch.FloatTensor(y_pred.size())
y_truth_tensor.fill_(y_label)
y_truth_tensor = y_truth_tensor.to(y_pred.get_device())
return nn.BCEWithLogitsLoss()(y_pr... | 1,877 | 29.290323 | 83 | py |
MuHDi | MuHDi-master/muhdi/model/discriminator.py | import torch
from torch import nn
def get_fc_discriminator(num_classes, ndf=64):
return nn.Sequential(
nn.Conv2d(num_classes, ndf, kernel_size=4, stride=2, padding=1),
nn.LeakyReLU(negative_slope=0.2, inplace=True),
nn.Conv2d(ndf, ndf * 2, kernel_size=4, stride=2, padding=1),
nn.Le... | 1,695 | 41.4 | 72 | py |
MuHDi | MuHDi-master/muhdi/model/deeplabv2.py | import torch
import torch.nn as nn
from torch.nn.modules.module import Module
from torch.nn.parameter import Parameter
import torch.nn.functional as F
import torch.nn.init as init
affine_par = True
class Bottleneck(nn.Module):
expansion = 4
def __init__(self, inplanes, planes, stride=1, dilation=1, downsamp... | 17,891 | 36.120332 | 99 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.