repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
CP2 | CP2-main/builder.py | # The CP2_MoCo model is built upon moco v2 code base:
# https://github.com/facebookresearch/moco
# Copyright (c) Facebook, Inc. and its affilates. All Rights Reserved
import torch
import torch.nn as nn
from mmseg.models import build_segmentor
class CP2_MOCO(nn.Module):
def __init__(self, cfg, dim=128, K=65536, m=0... | 6,009 | 34.146199 | 97 | py |
CP2 | CP2-main/loader.py | # tool functions from moco v2 code base:
# https://github.com/facebookresearch/moco
# Copyright (c) Facebook, Inc. and its affilates. All Rights Reserved
from PIL import ImageFilter
import random
class TwoCropsTransform:
"""Take two random crops of one image as the query and key."""
def __init__(self, base_tr... | 841 | 27.066667 | 79 | py |
CP2 | CP2-main/tools/train.py | import argparse
import copy
import os
import os.path as osp
import time
import mmcv
import torch
from mmcv.runner import init_dist
from mmcv.utils import Config, DictAction, get_git_hash
from mmseg import __version__
from mmseg.apis import set_random_seed, train_segmentor
from mmseg.datasets import build_dataset
from... | 6,051 | 33.19209 | 92 | py |
CP2 | CP2-main/mmseg/version.py | # Copyright (c) Open-MMLab. All rights reserved.
__version__ = '0.14.0'
def parse_version_info(version_str):
version_info = []
for x in version_str.split('.'):
if x.isdigit():
version_info.append(int(x))
elif x.find('rc') != -1:
patch_version = x.split('rc')
... | 502 | 25.473684 | 56 | py |
CP2 | CP2-main/mmseg/__init__.py | import mmcv
from .version import __version__, version_info
MMCV_MIN = '1.3.1'
MMCV_MAX = '1.4.0'
def digit_version(version_str):
digit_version = []
for x in version_str.split('.'):
if x.isdigit():
digit_version.append(int(x))
elif x.find('rc') != -1:
patch_version = x... | 850 | 26.451613 | 69 | py |
CP2 | CP2-main/mmseg/apis/inference.py | import matplotlib.pyplot as plt
import mmcv
import torch
from mmcv.parallel import collate, scatter
from mmcv.runner import load_checkpoint
from mmseg.datasets.pipelines import Compose
from mmseg.models import build_segmentor
def init_segmentor(config, checkpoint=None, device='cuda:0'):
"""Initialize a segmentor... | 4,582 | 32.698529 | 79 | py |
CP2 | CP2-main/mmseg/apis/test.py | import os.path as osp
import pickle
import shutil
import tempfile
import mmcv
import numpy as np
import torch
import torch.distributed as dist
from mmcv.image import tensor2imgs
from mmcv.runner import get_dist_info
def np2tmp(array, temp_file_name=None):
"""Save ndarray to local numpy file.
Args:
a... | 8,209 | 33.351464 | 79 | py |
CP2 | CP2-main/mmseg/apis/__init__.py | from .inference import inference_segmentor, init_segmentor, show_result_pyplot
from .test import multi_gpu_test, single_gpu_test
from .train import get_root_logger, set_random_seed, train_segmentor
__all__ = [
'get_root_logger', 'set_random_seed', 'train_segmentor', 'init_segmentor',
'inference_segmentor', 'mu... | 381 | 37.2 | 78 | py |
CP2 | CP2-main/mmseg/apis/train.py | import random
import warnings
import time
import numpy as np
import torch
from mmcv.parallel import MMDataParallel, MMDistributedDataParallel
from mmcv.runner import build_optimizer, build_runner
from mmseg.core import DistEvalHook, EvalHook
from mmseg.datasets import build_dataloader, build_dataset
from mmseg.utils ... | 4,066 | 32.61157 | 83 | py |
CP2 | CP2-main/mmseg/core/__init__.py | from .evaluation import * # noqa: F401, F403
from .seg import * # noqa: F401, F403
from .utils import * # noqa: F401, F403
| 126 | 30.75 | 45 | py |
CP2 | CP2-main/mmseg/core/evaluation/class_names.py | import mmcv
def cityscapes_classes():
"""Cityscapes class names for external use."""
return [
'road', 'sidewalk', 'building', 'wall', 'fence', 'pole',
'traffic light', 'traffic sign', 'vegetation', 'terrain', 'sky',
'person', 'rider', 'car', 'truck', 'bus', 'train', 'motorcycle',
... | 7,277 | 46.568627 | 79 | py |
CP2 | CP2-main/mmseg/core/evaluation/eval_hooks.py | import os.path as osp
import torch.distributed as dist
from mmcv.runner import DistEvalHook as _DistEvalHook
from mmcv.runner import EvalHook as _EvalHook
from torch.nn.modules.batchnorm import _BatchNorm
class EvalHook(_EvalHook):
"""Single GPU EvalHook, with efficient test support.
Args:
by_epoch ... | 3,528 | 36.147368 | 79 | py |
CP2 | CP2-main/mmseg/core/evaluation/metrics.py | from collections import OrderedDict
import mmcv
import numpy as np
import torch
def f_score(precision, recall, beta=1):
"""calcuate the f-score value.
Args:
precision (float | torch.Tensor): The precision value.
recall (float | torch.Tensor): The recall value.
beta (int): Determines ... | 13,051 | 38.914373 | 79 | py |
CP2 | CP2-main/mmseg/core/evaluation/__init__.py | from .class_names import get_classes, get_palette
from .eval_hooks import DistEvalHook, EvalHook
from .metrics import eval_metrics, mean_dice, mean_fscore, mean_iou
__all__ = [
'EvalHook', 'DistEvalHook', 'mean_dice', 'mean_iou', 'mean_fscore',
'eval_metrics', 'get_classes', 'get_palette'
]
| 301 | 32.555556 | 71 | py |
CP2 | CP2-main/mmseg/core/seg/__init__.py | from .builder import build_pixel_sampler
from .sampler import BasePixelSampler, OHEMPixelSampler
__all__ = ['build_pixel_sampler', 'BasePixelSampler', 'OHEMPixelSampler']
| 172 | 33.6 | 73 | py |
CP2 | CP2-main/mmseg/core/seg/builder.py | from mmcv.utils import Registry, build_from_cfg
PIXEL_SAMPLERS = Registry('pixel sampler')
def build_pixel_sampler(cfg, **default_args):
"""Build pixel sampler for segmentation map."""
return build_from_cfg(cfg, PIXEL_SAMPLERS, default_args)
| 253 | 27.222222 | 60 | py |
CP2 | CP2-main/mmseg/core/seg/sampler/base_pixel_sampler.py | from abc import ABCMeta, abstractmethod
class BasePixelSampler(metaclass=ABCMeta):
"""Base class of pixel sampler."""
def __init__(self, **kwargs):
pass
@abstractmethod
def sample(self, seg_logit, seg_label):
"""Placeholder for sample function."""
| 284 | 20.923077 | 46 | py |
CP2 | CP2-main/mmseg/core/seg/sampler/ohem_pixel_sampler.py | import torch
import torch.nn.functional as F
from ..builder import PIXEL_SAMPLERS
from .base_pixel_sampler import BasePixelSampler
@PIXEL_SAMPLERS.register_module()
class OHEMPixelSampler(BasePixelSampler):
"""Online Hard Example Mining Sampler for segmentation.
Args:
context (nn.Module): The contex... | 3,155 | 39.987013 | 103 | py |
CP2 | CP2-main/mmseg/core/seg/sampler/__init__.py | from .base_pixel_sampler import BasePixelSampler
from .ohem_pixel_sampler import OHEMPixelSampler
__all__ = ['BasePixelSampler', 'OHEMPixelSampler']
| 150 | 29.2 | 50 | py |
CP2 | CP2-main/mmseg/core/utils/misc.py | def add_prefix(inputs, prefix):
"""Add prefix for dict.
Args:
inputs (dict): The input dict with str keys.
prefix (str): The prefix to add.
Returns:
dict: The dict with keys updated with ``prefix``.
"""
outputs = dict()
for name, value in inputs.items():
outpu... | 371 | 19.666667 | 57 | py |
CP2 | CP2-main/mmseg/core/utils/__init__.py | from .misc import add_prefix
__all__ = ['add_prefix']
| 55 | 13 | 28 | py |
CP2 | CP2-main/mmseg/models/__init__.py | from .backbones import * # noqa: F401,F403
from .builder import (BACKBONES, HEADS, LOSSES, SEGMENTORS, build_backbone,
build_head, build_loss, build_segmentor)
from .decode_heads import * # noqa: F401,F403
from .losses import * # noqa: F401,F403
from .segmentors import * # noqa: F401,F403
__a... | 449 | 36.5 | 75 | py |
CP2 | CP2-main/mmseg/models/builder.py | import warnings
from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
MODELS = Registry('models', parent=MMCV_MODELS)
BACKBONES = MODELS
NECKS = MODELS
HEADS = MODELS
LOSSES = MODELS
SEGMENTORS = MODELS
def build_backbone(cfg):
"""Build backbone."""
return BACKBONES.build(cfg)
def bu... | 1,165 | 23.808511 | 71 | py |
CP2 | CP2-main/mmseg/models/decode_heads/fcn_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from ..builder import HEADS
from .decode_head import BaseDecodeHead
@HEADS.register_module()
class FCNHead(BaseDecodeHead):
"""Fully Convolution Networks for Semantic Segmentation.
This head is implemented of `FCNNet <https://arxiv.org/abs/1... | 3,166 | 33.423913 | 77 | py |
CP2 | CP2-main/mmseg/models/decode_heads/decode_head.py | from abc import ABCMeta, abstractmethod
import torch
import torch.nn as nn
from mmcv.cnn import normal_init
from mmcv.cnn import constant_init
from mmcv.runner import auto_fp16, force_fp32
from mmcv.runner import load_checkpoint
from mmseg.utils import get_root_logger
from mmseg.core import build_pixel_sampler
from m... | 9,545 | 38.283951 | 78 | py |
CP2 | CP2-main/mmseg/models/decode_heads/__init__.py | from .aspp_head import ASPPHead
from .fcn_head import FCNHead
__all__ = [
'FCNHead', 'ASPPHead',
]
| 104 | 14 | 31 | py |
CP2 | CP2-main/mmseg/models/decode_heads/aspp_head.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.ops import resize
from mmseg.models.builder import HEADS
from mmseg.models.decode_heads.decode_head import BaseDecodeHead
class ASPPModule(nn.ModuleList):
"""Atrous Spatial Pyramid Pooling (ASPP) Module.
Args:
dilations (t... | 3,807 | 31.547009 | 76 | py |
CP2 | CP2-main/mmseg/models/utils/se_layer.py | import mmcv
import torch.nn as nn
from mmcv.cnn import ConvModule
from .make_divisible import make_divisible
class SELayer(nn.Module):
"""Squeeze-and-Excitation Module.
Args:
channels (int): The input (and output) channels of the SE layer.
ratio (int): Squeeze ratio in SELayer, the intermedi... | 2,103 | 35.275862 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/weight_init.py | """Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/layers/drop.py."""
import math
import warnings
import torch
def _no_grad_trunc_normal_(tensor, mean, std, a, b):
"""Reference: https://people.sc.fsu.edu/~jburkardt/presentations
/truncated_normal.pdf"""
def norm... | 2,327 | 35.952381 | 76 | py |
CP2 | CP2-main/mmseg/models/utils/res_layer.py | from mmcv.cnn import build_conv_layer, build_norm_layer
from torch import nn as nn
class ResLayer(nn.Sequential):
"""ResLayer to build ResNet style backbone.
Args:
block (nn.Module): block used to build ResLayer.
inplanes (int): inplanes of block.
planes (int): planes of block.
... | 3,315 | 33.905263 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/self_attention_block.py | import torch
from mmcv.cnn import ConvModule, constant_init
from torch import nn as nn
from torch.nn import functional as F
class SelfAttentionBlock(nn.Module):
"""General self-attention block/non-local block.
Please refer to https://arxiv.org/abs/1706.03762 for details about key,
query and value.
A... | 6,125 | 37.2875 | 78 | py |
CP2 | CP2-main/mmseg/models/utils/up_conv_block.py | import torch
import torch.nn as nn
from mmcv.cnn import ConvModule, build_upsample_layer
class UpConvBlock(nn.Module):
"""Upsample convolution block in decoder for UNet.
This upsample convolution block consists of one upsample module
followed by one convolution block. The upsample module expands the
... | 3,968 | 37.911765 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/make_divisible.py | def make_divisible(value, divisor, min_value=None, min_ratio=0.9):
"""Make divisible function.
This function rounds the channel number to the nearest value that can be
divisible by the divisor. It is taken from the original tf repo. It ensures
that all layers have a channel number that is divisible by ... | 1,231 | 43 | 116 | py |
CP2 | CP2-main/mmseg/models/utils/inverted_residual.py | from mmcv.cnn import ConvModule
from torch import nn
from torch.utils import checkpoint as cp
from .se_layer import SELayer
class InvertedResidual(nn.Module):
"""InvertedResidual block for MobileNetV2.
Args:
in_channels (int): The input channels of the InvertedResidual block.
out_channels (i... | 7,005 | 32.521531 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/__init__.py | from .drop import DropPath
from .inverted_residual import InvertedResidual, InvertedResidualV3
from .make_divisible import make_divisible
from .res_layer import ResLayer
from .se_layer import SELayer
from .self_attention_block import SelfAttentionBlock
from .up_conv_block import UpConvBlock
from .weight_init import tru... | 502 | 34.928571 | 79 | py |
CP2 | CP2-main/mmseg/models/utils/drop.py | """Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/layers/drop.py."""
import torch
from torch import nn
class DropPath(nn.Module):
"""Drop paths (Stochastic Depth) per sample (when applied in main path of
residual blocks).
Args:
drop_prob (float): Drop r... | 1,015 | 30.75 | 78 | py |
CP2 | CP2-main/mmseg/models/segmentors/base.py | import logging
import warnings
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
import mmcv
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
from mmcv.runner import auto_fp16
class BaseSegmentor(nn.Module):
"""Base class for segmentors."""
__m... | 10,350 | 36.777372 | 79 | py |
CP2 | CP2-main/mmseg/models/segmentors/encoder_decoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from mmseg.core import add_prefix
from mmseg.ops import resize
from .. import builder
from ..builder import SEGMENTORS
from .base import BaseSegmentor
@SEGMENTORS.register_module()
class EncoderDecoder(BaseSegmentor):
"""Encoder Decoder segmentor... | 11,752 | 36.790997 | 79 | py |
CP2 | CP2-main/mmseg/models/segmentors/__init__.py | from .base import BaseSegmentor
from .encoder_decoder import EncoderDecoder
__all__ = ['BaseSegmentor', 'EncoderDecoder']
| 123 | 23.8 | 45 | py |
CP2 | CP2-main/mmseg/models/losses/dice_loss.py | """Modified from https://github.com/LikeLy-Journey/SegmenTron/blob/master/
segmentron/solver/loss.py (Apache-2.0 License)"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weighted_loss
@weighted_loss
def dice_loss(pred,
... | 4,239 | 34.333333 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/lovasz_loss.py | """Modified from https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytor
ch/lovasz_losses.py Lovasz-Softmax and Jaccard hinge loss in PyTorch Maxim
Berman 2018 ESAT-PSI KU Leuven (MIT License)"""
import mmcv
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .u... | 11,391 | 36.473684 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/utils.py | import functools
import mmcv
import numpy as np
import torch.nn.functional as F
def get_class_weight(class_weight):
"""Get class weight for loss function.
Args:
class_weight (list[float] | str | None): If class_weight is a str,
take it as a file name and read from it.
"""
if isin... | 3,690 | 29.254098 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/accuracy.py | import torch.nn as nn
def accuracy(pred, target, topk=1, thresh=None):
"""Calculate accuracy according to the prediction and target.
Args:
pred (torch.Tensor): The model prediction, shape (N, num_class, ...)
target (torch.Tensor): The target of each prediction, shape (N, , ...)
topk (... | 2,970 | 36.607595 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/cross_entropy_loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weight_reduce_loss
def cross_entropy(pred,
label,
weight=None,
class_weight=None,
reduction='mean',
... | 7,437 | 36.376884 | 79 | py |
CP2 | CP2-main/mmseg/models/losses/__init__.py | from .accuracy import Accuracy, accuracy
from .cross_entropy_loss import (CrossEntropyLoss, binary_cross_entropy,
cross_entropy, mask_cross_entropy)
from .dice_loss import DiceLoss
from .lovasz_loss import LovaszLoss
from .utils import reduce_loss, weight_reduce_loss, weighted_loss
__a... | 529 | 39.769231 | 72 | py |
CP2 | CP2-main/mmseg/models/backbones/resnet.py | import torch.nn as nn
import torch.utils.checkpoint as cp
from mmcv.cnn import (build_conv_layer, build_norm_layer, build_plugin_layer,
constant_init, kaiming_init)
from mmcv.runner import load_checkpoint
from mmcv.utils.parrots_wrapper import _BatchNorm
from mmseg.utils import get_root_logger
fr... | 24,210 | 34.139332 | 79 | py |
CP2 | CP2-main/mmseg/models/backbones/vit.py | """Modified from https://github.com/rwightman/pytorch-image-
models/blob/master/timm/models/vision_transformer.py."""
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from mmcv.cnn import (Conv2d, Linear, build_activation_layer, build_norm_layer,
... | 18,574 | 38.270613 | 128 | py |
CP2 | CP2-main/mmseg/models/backbones/__init__.py | from .resnet import ResNet
from .vit import VisionTransformer
__all__ = [
'ResNet', 'VisionTransformer'
]
| 111 | 15 | 34 | py |
CP2 | CP2-main/mmseg/datasets/custom.py | import os
import os.path as osp
from collections import OrderedDict
from functools import reduce
import mmcv
import numpy as np
from mmcv.utils import print_log
from prettytable import PrettyTable
from torch.utils.data import Dataset
from mmseg.core import eval_metrics
from mmseg.utils import get_root_logger
from .bu... | 14,628 | 35.481297 | 79 | py |
CP2 | CP2-main/mmseg/datasets/voc.py | import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class PascalVOCDataset(CustomDataset):
"""Pascal VOC dataset.
Args:
split (str): Split txt file for Pascal VOC.
"""
CLASSES = ('background', 'aeroplane', 'bicycle', 'bird', 'boa... | 1,130 | 36.7 | 79 | py |
CP2 | CP2-main/mmseg/datasets/ade.py | import os.path as osp
import tempfile
import mmcv
import numpy as np
from PIL import Image
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class ADE20KDataset(CustomDataset):
"""ADE20K dataset.
In segmentation map annotation for ADE20K, 0 stands for background, w... | 8,130 | 48.579268 | 79 | py |
CP2 | CP2-main/mmseg/datasets/hrf.py | import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class HRFDataset(CustomDataset):
"""HRF dataset.
In segmentation map annotation for HRF, 0 stands for background, which is
included in 2 categories. ``reduce_zero_label`` is fixed to False. ... | 747 | 25.714286 | 77 | py |
CP2 | CP2-main/mmseg/datasets/chase_db1.py | import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class ChaseDB1Dataset(CustomDataset):
"""Chase_db1 dataset.
In segmentation map annotation for Chase_db1, 0 stands for background,
which is included in 2 categories. ``reduce_zero_label`` is... | 781 | 26.928571 | 79 | py |
CP2 | CP2-main/mmseg/datasets/cityscapes.py | import os.path as osp
import tempfile
import mmcv
import numpy as np
from mmcv.utils import print_log
from PIL import Image
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class CityscapesDataset(CustomDataset):
"""Cityscapes dataset.
The ``img_suffix`` is fixed ... | 8,446 | 37.747706 | 96 | py |
CP2 | CP2-main/mmseg/datasets/dataset_wrappers.py | from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
from .builder import DATASETS
@DATASETS.register_module()
class ConcatDataset(_ConcatDataset):
"""A wrapper of concatenated dataset.
Same as :obj:`torch.utils.data.dataset.ConcatDataset`, but
concat the group flag for image aspect rati... | 1,499 | 28.411765 | 78 | py |
CP2 | CP2-main/mmseg/datasets/pascal_context.py | import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class PascalContextDataset(CustomDataset):
"""PascalContext dataset.
In segmentation map annotation for PascalContext, 0 stands for background,
which is included in 60 categories. ``reduce_z... | 5,202 | 49.028846 | 79 | py |
CP2 | CP2-main/mmseg/datasets/drive.py | import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class DRIVEDataset(CustomDataset):
"""DRIVE dataset.
In segmentation map annotation for DRIVE, 0 stands for background, which is
included in 2 categories. ``reduce_zero_label`` is fixed to F... | 771 | 26.571429 | 79 | py |
CP2 | CP2-main/mmseg/datasets/__init__.py | from .ade import ADE20KDataset
from .builder import DATASETS, PIPELINES, build_dataloader, build_dataset
from .chase_db1 import ChaseDB1Dataset
from .cityscapes import CityscapesDataset
from .custom import CustomDataset
from .dataset_wrappers import ConcatDataset, RepeatDataset
from .drive import DRIVEDataset
from .hrf... | 798 | 38.95 | 78 | py |
CP2 | CP2-main/mmseg/datasets/builder.py | import copy
import platform
import random
from functools import partial
import numpy as np
from mmcv.parallel import collate
from mmcv.runner import get_dist_info
from mmcv.utils import Registry, build_from_cfg
from mmcv.utils.parrots_wrapper import DataLoader, PoolDataLoader
from torch.utils.data import DistributedSa... | 5,871 | 33.541176 | 79 | py |
CP2 | CP2-main/mmseg/datasets/stare.py | import os.path as osp
from .builder import DATASETS
from .custom import CustomDataset
@DATASETS.register_module()
class STAREDataset(CustomDataset):
"""STARE dataset.
In segmentation map annotation for STARE, 0 stands for background, which is
included in 2 categories. ``reduce_zero_label`` is fixed to F... | 761 | 26.214286 | 79 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/loading.py | import os.path as osp
import mmcv
import numpy as np
from ..builder import PIPELINES
@PIPELINES.register_module()
class LoadImageFromFile(object):
"""Load an image from file.
Required keys are "img_prefix" and "img_info" (a dict that must contain the
key "filename"). Added or updated keys are "filename... | 5,873 | 37.142857 | 79 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/compose.py | import collections
from mmcv.utils import build_from_cfg
from ..builder import PIPELINES
@PIPELINES.register_module()
class Compose(object):
"""Compose multiple transforms sequentially.
Args:
transforms (Sequence[dict | callable]): Sequence of transform object or
config dict to be compo... | 1,464 | 27.173077 | 79 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/formating.py | from collections.abc import Sequence
import mmcv
import numpy as np
import torch
from mmcv.parallel import DataContainer as DC
from ..builder import PIPELINES
def to_tensor(data):
"""Convert objects of various python types to :obj:`torch.Tensor`.
Supported types are: :class:`numpy.ndarray`, :class:`torch.T... | 9,228 | 30.934256 | 79 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/__init__.py | from .compose import Compose
from .formating import (Collect, ImageToTensor, ToDataContainer, ToTensor,
Transpose, to_tensor)
from .loading import LoadAnnotations, LoadImageFromFile
from .test_time_aug import MultiScaleFlipAug
from .transforms import (CLAHE, AdjustGamma, Normalize, Pad,
... | 813 | 46.882353 | 77 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/transforms.py | import mmcv
import numpy as np
from mmcv.utils import deprecated_api_warning, is_tuple_of
from numpy import random
from ..builder import PIPELINES
@PIPELINES.register_module()
class Resize(object):
"""Resize images & seg.
This transform resizes the input image to some scale. If the input dict
contains t... | 30,945 | 33.770787 | 79 | py |
CP2 | CP2-main/mmseg/datasets/pipelines/test_time_aug.py | import warnings
import mmcv
from ..builder import PIPELINES
from .compose import Compose
@PIPELINES.register_module()
class MultiScaleFlipAug(object):
"""Test-time augmentation with multiple scales and flipping.
An example configuration is as followed:
.. code-block::
img_scale=(2048, 1024),
... | 5,173 | 37.61194 | 79 | py |
CP2 | CP2-main/mmseg/utils/logger.py | import logging
from mmcv.utils import get_logger
def get_root_logger(log_file=None, log_level=logging.INFO):
"""Get the root logger.
The logger will be initialized if it has not been initialized. By default a
StreamHandler will be added. If `log_file` is specified, a FileHandler will
also be added. ... | 899 | 31.142857 | 79 | py |
CP2 | CP2-main/mmseg/utils/collect_env.py | from mmcv.utils import collect_env as collect_base_env
from mmcv.utils import get_git_hash
import mmseg
def collect_env():
"""Collect the information of the running environments."""
env_info = collect_base_env()
env_info['MMSegmentation'] = f'{mmseg.__version__}+{get_git_hash()[:7]}'
return env_info... | 436 | 23.277778 | 76 | py |
CP2 | CP2-main/mmseg/utils/__init__.py | from .collect_env import collect_env
from .logger import get_root_logger
__all__ = ['get_root_logger', 'collect_env']
| 119 | 23 | 44 | py |
CP2 | CP2-main/mmseg/ops/wrappers.py | import warnings
import torch.nn as nn
import torch.nn.functional as F
def resize(input,
size=None,
scale_factor=None,
mode='nearest',
align_corners=None,
warning=True):
if warning:
if size is not None and align_corners:
input_h, input_w =... | 1,827 | 34.843137 | 79 | py |
CP2 | CP2-main/mmseg/ops/__init__.py | from .encoding import Encoding
from .wrappers import Upsample, resize
__all__ = ['Upsample', 'resize', 'Encoding']
| 116 | 22.4 | 44 | py |
CP2 | CP2-main/mmseg/ops/encoding.py | import torch
from torch import nn
from torch.nn import functional as F
class Encoding(nn.Module):
"""Encoding Layer: a learnable residual encoder.
Input is of shape (batch_size, channels, height, width).
Output is of shape (batch_size, num_codes, channels).
Args:
channels: dimension of the ... | 2,788 | 36.186667 | 78 | py |
CP2 | CP2-main/configs/config_pretrain.py | norm_cfg = dict(type='BN', requires_grad=True)
pretrain_path = None # Please set the path to pretrained weights for Quick Tuning
model = dict(
type='EncoderDecoder',
pretrained=pretrain_path,
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
... | 952 | 27.029412 | 84 | py |
CP2 | CP2-main/configs/config_finetune.py | # model settings
norm_cfg = dict(type='SyncBN', requires_grad=True)
pretrain_path = '' # Please set the path to pretrained model
data_root = '' # Please set the path to your finetuing dataset (PASCAL VOC 2012)
model = dict(
type='EncoderDecoder',
pretrained=pretrain_path,
backbone=dict(
typ... | 3,664 | 29.798319 | 85 | py |
NeuralIdeals | NeuralIdeals-master/examples.py | # -*- coding: utf-8 -*-
"""
Examples of NeuralCode
AUTHORS:
- Ethan Petersen (2015-09) [initial version]
This file constructs some examples of NeuralCodes.
The examples are accessible by typing: ``neuralcodes.example()``
"""
class NeuralCodeExamples():
r"""
Some examples of neuralcodes.
... | 4,237 | 12.80456 | 139 | py |
NeuralIdeals | NeuralIdeals-master/neuralcode.py | import itertools
import time
import math
from multiprocessing.pool import ThreadPool
from itertools import tee, izip
from sage.rings.polynomial import *
from sage.rings.polynomial.pbori import *
from sage.rings.ideal import *
r"""
Neural Ideals in SageMath: A package to perform computations with neural ideals associa... | 39,713 | 39.115152 | 2,149 | py |
SA-UNet | SA-UNet-master/Dropblock.py | import keras
import keras.backend as K
class DropBlock1D(keras.layers.Layer):
"""See: https://arxiv.org/pdf/1810.12890.pdf"""
def __init__(self,
block_size,
keep_prob,
sync_channels=False,
data_format=None,
**kwargs):
... | 7,815 | 38.474747 | 103 | py |
SA-UNet | SA-UNet-master/keras_dataAug.py |
from PIL import Image, ImageEnhance, ImageOps, ImageFile
import numpy as np
import random
import threading, os, time
import logging
logger = logging.getLogger(__name__)
ImageFile.LOAD_TRUNCATED_IMAGES = True
class DataAugmentation:
def __init__(self):
pass
@staticmethod
def openImage(image):
... | 5,744 | 30.565934 | 120 | py |
SA-UNet | SA-UNet-master/Train_chase.py | import os
import numpy as np
import cv2
from keras.callbacks import TensorBoard, ModelCheckpoint
np.random.seed(42)
import scipy.misc as mc
import matplotlib.pyplot as plt
data_location = ''
training_images_loc = data_location + 'CHASE/train/imageS/'
training_label_loc = data_location + 'CHASE/train/labelS/'
validate_... | 4,715 | 35.84375 | 143 | py |
SA-UNet | SA-UNet-master/Eval_drive.py | 1 | 0 | 0 | py | |
SA-UNet | SA-UNet-master/util.py | def crop_to_shape(data, shape):
"""
Crops the array to the given image shape by removing the border (expects a tensor of shape [batches, nx, ny, channels].
:param data: the array to crop
:param shape: the target shape
"""
#
offset0 = (data.shape[1] - shape[1])//2
offset1 = (data.shape[... | 1,398 | 42.71875 | 123 | py |
SA-UNet | SA-UNet-master/Train_drive.py | import os
import cv2
from keras.callbacks import TensorBoard, ModelCheckpoint
import matplotlib.pyplot as plt
import numpy as np
from scipy.misc.pilutil import *
data_location = ''
training_images_loc = data_location + 'DRIVE/train/images/'
training_label_loc = data_location + 'DRIVE/train/labels/'
validate_images_... | 4,541 | 35.336 | 119 | py |
SA-UNet | SA-UNet-master/flip.py | import cv2
import os
# Please modify the path
path="DRIVE/train/images"
save="Drive/flip/images/"
for name in os.listdir(path):
image = cv2.imread(path+name)
# Flipped Horizontally
h_flip = cv2.flip(image, 1)
cv2.imwrite(save+"h"+name, h_flip)
# Flipped Vertically
v_flip = cv2.flip(image, 0)... | 476 | 20.681818 | 40 | py |
SA-UNet | SA-UNet-master/SA_UNet.py |
from keras.optimizers import *
from keras.models import Model
from keras.layers import Input,Conv2DTranspose, MaxPooling2D,BatchNormalization,concatenate,Activation
from Spatial_Attention import *
def Backbone(input_size=(512, 512, 3), block_size=7,keep_prob=0.9,start_neurons=16,lr=1e-3):
inputs = Input(input_... | 9,007 | 45.43299 | 102 | py |
SA-UNet | SA-UNet-master/Spatial_Attention.py | from keras.layers import GlobalAveragePooling2D, GlobalMaxPooling2D, Reshape, Dense, multiply, Permute, Concatenate, \
Conv2D, Add, Activation, Lambda,Conv1D
from Dropblock import *
def spatial_attention(input_feature):
kernel_size = 7
if K.image_data_format() == "channels_first":
channel = input_... | 1,364 | 40.363636 | 118 | py |
SA-UNet | SA-UNet-master/Eval_chase.py | 1 | 0 | 0 | py | |
multeval | multeval-master/reg-test/write-sgm.py | #!/usr/bin/env python
# Stolen from METEOR's mt-diff.py tool
# (under the LGPL license)
import math, os, re, shutil, sys, tempfile
def main(argv):
# Usage
if len(argv[1:]) < 3:
print 'usage: {0} <lang> <hyps> <out_dir> <ref1> [ref2 ...]'. \
format(argv[0])
print 'langs: {0}'.format... | 2,144 | 25.8125 | 78 | py |
pegnn | pegnn-master/train_autoencoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch_geometric.loader import DataLoader
import json
from src.datasets import CSVDataset
from src.utils.scaler import LatticeScaler
from src.utils.visualize import get_fig
from src.utils.debug import check_grad
from sr... | 6,650 | 31.602941 | 88 | py |
pegnn | pegnn-master/train_benchmark.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch_geometric.loader import DataLoader
import json
from src.datasets import CSVDataset
from src.utils.scaler import LatticeScaler
from src.utils.visualize import get_fig
from src.utils.debug import check_grad
from sr... | 7,547 | 32.251101 | 93 | py |
pegnn | pegnn-master/src/models/operator/loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from src.datasets.data import CrystalData
from src.utils.scaler import LatticeScaler
from src.models.operator.utils import lattice_params_to_matrix_torch
from typing import Dict, Tuple
def get_metrics(batch: CrystalData, reconstructed: torch.FloatT... | 2,878 | 32.476744 | 148 | py |
pegnn | pegnn-master/src/models/operator/utils.py | import torch
import torch.nn as nn
import tqdm
import os
import json
from dataclasses import dataclass
def save_step(spike_dir, batch, model, opti):
os.makedirs(spike_dir, exist_ok=True)
batch_dict = {
"cell": batch.cell.tolist(),
"pos": batch.pos.tolist(),
"z": batch.z.tolist(),
... | 8,969 | 28.409836 | 90 | py |
pegnn | pegnn-master/src/models/operator/denoise.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import src.models.layers.operator.gnn as ops
from src.models.operator.utils import build_mlp, lattice_params_to_matrix_torch
from src.utils.geometry import Geometry
from torch_scatter import scatter_mean
class Denoise(nn.Module):
def __init__(
... | 4,657 | 29.051613 | 79 | py |
pegnn | pegnn-master/src/models/operator/autoencoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import src.models.layers.operator.gnn as ops
from src.models.operator.utils import build_mlp
from src.utils.geometry import Geometry
from torch_scatter import scatter_mean
from typing import Tuple
class AutoEncoder(nn.Module):
def __init__(
... | 4,223 | 25.236025 | 88 | py |
pegnn | pegnn-master/src/models/layers/random.py | import torch
import torch.nn as nn
class RandomMatrixSL3Z(nn.Module):
def __init__(self):
super().__init__()
generators = torch.tensor(
[
[[1, 0, 1], [0, -1, -1], [0, 1, 0]],
[[0, 1, 0], [0, 0, 1], [1, 0, 0]],
[[0, 1, 0], [1, 0, 0], [-1,... | 1,510 | 25.982143 | 85 | py |
pegnn | pegnn-master/src/models/layers/operator/gnn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_scatter import scatter
from typing import Tuple
from src.utils.geometry import Geometry
from src.utils.shape import build_shapes, assert_tensor_match, shape
from src.models.layers.operator.operator import Operator, make_operator
class E... | 10,092 | 29.492447 | 88 | py |
pegnn | pegnn-master/src/models/layers/operator/operator.py | import torch
import torch.nn as nn
from src.utils.geometry import Geometry
from src.models.layers.operator.grad import Grad
import enum
from typing import List
import abc
class Operator(nn.Module):
def __init__(self, operators_edges, operators_triplets, normalize: bool = True):
super().__init__()
... | 11,933 | 31.254054 | 103 | py |
pegnn | pegnn-master/src/models/layers/operator/grad_unittest.py | import torch
import torch.nn as nn
from torch.autograd.functional import jacobian
from .grad import Grad
import unittest
import time
class TestGrad(unittest.TestCase):
batch_size = 1024
verbose = True
def log(self, *args, **kwargs):
if TestGrad.verbose:
print(*args, **kwargs)
d... | 11,560 | 31.566197 | 75 | py |
pegnn | pegnn-master/src/models/layers/operator/grad.py | import torch
import torch.nn as nn
class Grad(nn.Module):
def __init__(self):
super().__init__()
self.I = nn.Parameter(torch.eye(3), requires_grad=False)
self.K = nn.Parameter(torch.tensor([[[0, 0, 0], [0, 0, 1], [0, -1, 0]], [[0, 0, -1], [0, 0, 0], [
1, 0, 0... | 7,661 | 36.014493 | 120 | py |
pegnn | pegnn-master/src/datasets/data.py | from __future__ import annotations
import torch
import torch.nn.functional as F
from torch_geometric.data import Data
class CrystalData(Data):
def __init__(self, *args, **kwargs):
if "pos_cart" in kwargs:
assert isinstance(kwargs["cell"], torch.FloatTensor)
assert isinstance(kwarg... | 2,855 | 27.848485 | 88 | py |
pegnn | pegnn-master/src/datasets/__init__.py | from .csv_dataset import CSVDataset
__all__ = ["CSVDataset"]
| 62 | 14.75 | 35 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.