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 |
|---|---|---|---|---|---|---|
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/backbone/fbnet.py | from __future__ import absolute_import, division, print_function, unicode_literals
import copy
import json
import logging
from collections import OrderedDict
from . import (
fbnet_builder as mbuilder,
fbnet_modeldef as modeldef,
)
import torch.nn as nn
from maskrcnn_benchmark.modeling import registry
from mas... | 7,845 | 30.011858 | 83 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/backbone/backbone.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.make_layers import conv_with_kaiming_uniform
from . import fpn as fpn_module
from . import resnet
from . im... | 3,024 | 34.174419 | 81 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/backbone/fpn.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
class FPN(nn.Module):
"""
Module that adds FPN on top of a list of feature maps.
The feature maps are currently supposed to be in increasing depth
order, and must b... | 3,939 | 38.4 | 86 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/detector/generalized_rcnn.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Implements the Generalized R-CNN framework
"""
import torch
from torch import nn
from maskrcnn_benchmark.structures.image_list import to_image_list
from ..backbone import build_backbone
from ..rpn.rpn import build_rpn
from ..roi_heads.roi_he... | 3,101 | 37.296296 | 152 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/inference.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist
from maskrcnn_benchmark.structures.boxlist_ops... | 7,648 | 36.312195 | 102 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/anchor_generator.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import numpy as np
import torch
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
class BufferList(nn.Module):
"""
Similar to nn.ParameterList, but for buffers
"""
def __init__(self... | 9,947 | 33.303448 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/loss.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This file contains specific functions for computing losses on the RPN
file
"""
import torch
from torch.nn import functional as F
from .utils import concat_box_prediction_layers
from ..balanced_positive_negative_sampler import BalancedPositiv... | 6,203 | 35.928571 | 133 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Utility functions minipulating the prediction layers
"""
from ..utils import cat
import torch
def permute_and_flatten(layer, N, A, C, H, W):
layer = layer.view(N, -1, C, H, W)
layer = layer.permute(0, 3, 4, 1, 2)
layer = layer.re... | 1,855 | 36.877551 | 80 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/rpn.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from maskrcnn_benchmark.modeling.rpn.retinanet.retinanet import build_ret... | 5,809 | 37.993289 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/retinanet/inference.py | import torch
from ..inference import RPNPostProcessor
from ..utils import permute_and_flatten
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from maskrcnn_benchmark.modeling.utils import cat
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops impor... | 6,923 | 34.507692 | 79 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/retinanet/loss.py | """
This file contains specific functions for computing losses on the RetinaNet
file
"""
import torch
from torch.nn import functional as F
from ..utils import concat_box_prediction_layers
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.layers import SigmoidFocalLoss
from maskrcnn_benchma... | 3,484 | 31.268519 | 83 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/rpn/retinanet/retinanet.py | import math
import torch
import torch.nn.functional as F
from torch import nn
from .inference import make_retinanet_postprocessor
from .loss import make_retinanet_loss_evaluator
from ..anchor_generator import make_anchor_generator_retinanet
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
class RetinaNet... | 5,290 | 33.357143 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/da_heads/loss.py | """
This file contains specific functions for computing losses on the da_heads
file
"""
import torch
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.layers import consistency_loss
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.structures.boxlist_ops i... | 7,287 | 40.645714 | 139 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/da_heads/da_heads.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from __future__ import print_function
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.layers import GradientScalarLayer
from .loss import make_da_heads_loss_evaluator
class DAImgHead(nn.Module):
"""
... | 6,527 | 41.116129 | 285 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/roi_heads.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .box_head.box_head import build_roi_box_head
from .mask_head.mask_head import build_roi_mask_head
from .keypoint_head.keypoint_head import build_roi_keypoint_head
class CombinedROIHeads(torch.nn.ModuleDict):
"""
Combine... | 3,273 | 41.519481 | 100 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/mask_head/inference.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from maskrcnn_benchmark.structures.bounding_box import BoxList
# TODO check if want to return a single BoxList or a composite
# object
class MaskPostProcessor(n... | 6,540 | 30.907317 | 87 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_mask_feature_extractors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
from torch.nn import functional as F
from ..box_head.roi_box_feature_extractors import ResNet50Conv5ROIFeatureExtractor
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_benchmark.layers import Conv2d
from m... | 2,372 | 32.9 | 82 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch.nn import functional as F
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
from maskrcnn_benchmar... | 5,547 | 37.262069 | 80 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_mask_predictors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.layers import Conv2d
from maskrcnn_benchmark.layers import ConvTranspose2d
class MaskRCNNC4Predictor(nn.Module):
def __init__(self, cfg):
super(MaskRCN... | 1,609 | 34.777778 | 83 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
from .roi_mask_feature_extractors import make_roi_mask_feature_extractor
from .roi_mask_predictors import make_roi_mask_predictor
from .inference imp... | 3,024 | 35.445783 | 86 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_nms
from maskrcnn_benchmark.structures.boxlist_ops impor... | 6,445 | 37.369048 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/box_head/roi_box_feature_extractors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.modeling.backbone import resnet
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_be... | 5,279 | 34.2 | 81 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/box_head/box_head.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from .roi_box_feature_extractors import make_roi_box_feature_extractor
from .roi_box_predictors import make_roi_box_predictor
from .inference import make_roi_box_post_processor
from .loss import make_roi_box_loss_... | 3,118 | 36.578313 | 96 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/box_head/loss.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch.nn import functional as F
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.struc... | 9,438 | 37.369919 | 155 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/box_head/roi_box_predictors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from maskrcnn_benchmark.modeling import registry
from torch import nn
@registry.ROI_BOX_PREDICTOR.register("FastRCNNPredictor")
class FastRCNNPredictor(nn.Module):
def __init__(self, config, pretrained=None):
super(FastRCNNPredictor, ... | 2,320 | 36.435484 | 87 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/inference.py | import torch
from torch import nn
class KeypointPostProcessor(nn.Module):
def __init__(self, keypointer=None):
super(KeypointPostProcessor, self).__init__()
self.keypointer = keypointer
def forward(self, x, boxes):
mask_prob = x
scores = None
if self.keypointer:
... | 4,468 | 34.468254 | 102 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/roi_keypoint_feature_extractors.py | from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_benchmark.layers import Conv2d
class KeypointRCNNFeatureExtractor(nn.Module):
def __init__(self, cfg):
super(KeypointRCNNFeatureExtractor, self).__init__()
resolution =... | 1,796 | 32.90566 | 87 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/loss.py | import torch
from torch.nn import functional as F
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.modeling.balanced_positive_negative_sampler import (
BalancedPositiveNegativeSampler,
)
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
from maskrcnn_benchmark.modeli... | 7,103 | 37.608696 | 90 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/keypoint_head.py | import torch
from .roi_keypoint_feature_extractors import make_roi_keypoint_feature_extractor
from .roi_keypoint_predictors import make_roi_keypoint_predictor
from .inference import make_roi_keypoint_post_processor
from .loss import make_roi_keypoint_loss_evaluator
class ROIKeypointHead(torch.nn.Module):
def __i... | 1,955 | 37.352941 | 81 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/modeling/roi_heads/keypoint_head/roi_keypoint_predictors.py | from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark import layers
class KeypointRCNNPredictor(nn.Module):
def __init__(self, cfg):
super(KeypointRCNNPredictor, self).__init__()
input_features = cfg.MODEL.ROI_KEYPOINT_HEAD.CONV_LAYERS[-1]
num_keypoints = cfg.M... | 1,214 | 29.375 | 79 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/structures/image_list.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from __future__ import division
import torch
class ImageList(object):
"""
Structure that holds a list of images (of possibly
varying sizes) as a single tensor.
This works by padding the images to the same size,
and storing in... | 3,140 | 36.843373 | 105 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/structures/segmentation_mask.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import pycocotools.mask as mask_utils
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
class Mask(object):
"""
This class is unfinished and not meant for use yet
It is supposed to contain the mask for an object as
... | 7,009 | 31.453704 | 86 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/structures/bounding_box.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
class BoxList(object):
"""
This class represents a set of bounding boxes.
The bounding boxes are represented as a Nx4 Tensor.
In order to uniquely determine the bou... | 9,645 | 35.127341 | 92 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/structures/boxlist_ops.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .bounding_box import BoxList
from maskrcnn_benchmark.layers import nms as _box_nms
def boxlist_nms(boxlist, nms_thresh, max_proposals=-1, score_field="scores"):
"""
Performs non-maximum suppression on a boxlist, with s... | 3,637 | 27.20155 | 97 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn_benchmark/structures/keypoint.py | import torch
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
class Keypoints(object):
def __init__(self, keypoints, size, mode=None):
# FIXME remove check once we have better integration with device
# in my version this would consistently return a CPU tensor
device = keypoints.device ... | 6,555 | 33.687831 | 97 | py |
DA-Object-Detection | DA-Object-Detection-main/maskrcnn-benchmark/maskrcnn_benchmark/layers/SEAdaptor.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class SEAdaptor(nn.Module):
def __init__(self, n_channels, reduction=16):
super(SEAdaptor, self).__init__()
if n_channels % reduction != 0:
raise ValueError('n_channels must be divisible by reduction (default = 16)')
... | 781 | 34.545455 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/checkpoint.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict
import os
from tempfile import TemporaryDirectory
import unittest
import torch
from torch import nn
from maskrcnn_benchmark.utils.model_serialization import load_state_dict
from maskrcnn_benchmark.utils.checkpo... | 4,645 | 38.042017 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_detectors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import glob
import os
import copy
import torch
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.structures.image_list import to_image_list
import utils
CONFIG_FILES = [
# bbox
... | 4,223 | 28.333333 | 71 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_nms.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import numpy as np
import torch
from maskrcnn_benchmark.layers import nms as box_nms
class TestNMS(unittest.TestCase):
def test_nms_cpu(self):
""" Match unit test UtilsNMSTest.TestNMS in
caffe2/operators/... | 7,612 | 33.292793 | 76 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_backbones.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import copy
import torch
# import modules to to register backbones
from maskrcnn_benchmark.modeling.backbone import build_backbone # NoQA
from maskrcnn_benchmark.modeling import registry
from maskrcnn_benchmark.config import cfg as... | 1,914 | 33.196429 | 75 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_feature_extractors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import copy
import torch
# import modules to to register feature extractors
from maskrcnn_benchmark.modeling.backbone import build_backbone # NoQA
from maskrcnn_benchmark.modeling.roi_heads.roi_heads import build_roi_heads # NoQA
f... | 3,070 | 31.670213 | 82 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_fbnet.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import numpy as np
import torch
import maskrcnn_benchmark.modeling.backbone.fbnet_builder as fbnet_builder
TEST_CUDA = torch.cuda.is_available()
def _test_primitive(self, device, op_name, op_func, N, C_in, C_out, expand, strid... | 2,845 | 32.482353 | 84 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_predictors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import copy
import torch
# import modules to to register predictors
from maskrcnn_benchmark.modeling.backbone import build_backbone # NoQA
from maskrcnn_benchmark.modeling.roi_heads.roi_heads import build_roi_heads # NoQA
from mask... | 3,214 | 31.474747 | 82 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_data_samplers.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import random
import unittest
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import Sampler
from torch.utils.data.sampler import SequentialSampler
from torch.utils.data.sampler import RandomSampler... | 5,532 | 34.928571 | 88 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_rpn_heads.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import copy
import torch
# import modules to to register rpn heads
from maskrcnn_benchmark.modeling.backbone import build_backbone # NoQA
from maskrcnn_benchmark.modeling.rpn.rpn import build_rpn # NoQA
from maskrcnn_benchmark.mode... | 1,992 | 30.634921 | 71 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_segmentation_mask.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import torch
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
class TestSegmentationMask(unittest.TestCase):
def __init__(self, method_name='runTest'):
super(TestSegmentationMask, self).__in... | 2,414 | 33.5 | 76 | py |
DA-Object-Detection | DA-Object-Detection-main/tests/test_box_coder.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import numpy as np
import torch
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
class TestBoxCoder(unittest.TestCase):
def test_box_decoder(self):
""" Match unit test UtilsBoxesTest.TestBboxTransformRandom... | 3,112 | 27.3 | 80 | py |
DA-Object-Detection | DA-Object-Detection-main/demo/webcam.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
import time
def main():
parser = argparse.ArgumentParser(description="PyTorch Object Detection Webcam Demo")
parser.add_argument(
... | 2,598 | 29.576471 | 110 | py |
DA-Object-Detection | DA-Object-Detection-main/demo/predictor.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import cv2
import torch
from torchvision import transforms as T
from maskrcnn_benchmark.modeling.detector import build_detection_model
from maskrcnn_benchmark.utils.checkpoint import DetectronCheckpointer
from maskrcnn_benchmark.structures.image_l... | 15,583 | 34.337868 | 122 | py |
DA-Object-Detection | DA-Object-Detection-main/demo/demo.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
import time
def main():
parser = argparse.ArgumentParser(description="PyTorch Object Detection Webcam Demo")
parser.add_argument(
... | 2,259 | 28.736842 | 88 | py |
QU-net-Plus-Plus | QU-net-Plus-Plus-main/code/model_new.py | import tensorflow as tf
from tensorflow.keras.models import Model
import tensorflow.keras as keras
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Input, Conv2D, ZeroPadding2D, UpSampling2D, Dense, concatenate, Conv2DTranspose
from tensorflow.keras.layers import MaxPooling2D, GlobalAverage... | 12,171 | 44.081481 | 157 | py |
smote_variants | smote_variants-master/setup.py | import os
import codecs
from setuptools import setup, find_packages
def readme():
with codecs.open('README.rst', encoding='utf-8-sig') as f:
return f.read()
version_file= os.path.join('smote_variants', '_version.py')
__version__= "0.0.0"
with open(version_file) as f:
exec(f.read())
from setuptools.c... | 3,246 | 34.293478 | 166 | py |
smote_variants | smote_variants-master/examples/legacy/007_paper_examples.py |
# coding: utf-8
# # Examples from the paper
#
# In this notebook, provide the codes used for illustration in the corresponding paper with all the supplementary code segments excluded from the paper due to space limitations.
# In[1]:
import scipy
import sklearn
import keras
import imblearn
import numpy as np
impo... | 3,282 | 21.641379 | 177 | py |
smote_variants | smote_variants-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 6,058 | 28.70098 | 79 | py |
smote_variants | smote_variants-master/smote_variants/oversampling/_deago.py | """
This module implements the DEAGO method.
"""
import os
import random
import warnings
warnings.simplefilter("ignore", DeprecationWarning)
import numpy as np # pylint: disable=wrong-import-position
from sklearn.preprocessing import StandardScaler # pylint: disable=wrong-import-position
from ..base import OverSampl... | 11,919 | 41.269504 | 153 | py |
diffusion-mcmc | diffusion-mcmc-main/global_vdm_2d.py |
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import jax
import jax.numpy as jnp
from flax import linen as nn
import optax
#%matplotlib inline
import time
import pylab as pl
from IPython import display
from tqdm.notebook import trange, tqdm
import random
#from google.colab import files
#... | 14,680 | 29.458506 | 106 | py |
CSI | CSI-master/eval.py | from common.eval import *
model.eval()
if P.mode == 'test_acc':
from evals import test_classifier
with torch.no_grad():
error = test_classifier(P, model, test_loader, 0, logger=None)
elif P.mode == 'test_marginalized_acc':
from evals import test_classifier
with torch.no_grad():
error ... | 1,645 | 29.481481 | 92 | py |
CSI | CSI-master/train.py | from utils.utils import Logger
from utils.utils import save_checkpoint
from utils.utils import save_linear_checkpoint
from common.train import *
from evals import test_classifier
if 'sup' in P.mode:
from training.sup import setup
else:
from training.unsup import setup
train, fname = setup(P.mode, P)
logger =... | 1,742 | 29.051724 | 108 | py |
CSI | CSI-master/common/common.py | from argparse import ArgumentParser
def parse_args(default=False):
"""Command-line argument parser for training."""
parser = ArgumentParser(description='Pytorch implementation of CSI')
parser.add_argument('--dataset', help='Dataset',
choices=['cifar10', 'cifar100', 'imagenet'], t... | 4,678 | 50.988889 | 113 | py |
CSI | CSI-master/common/eval.py | from copy import deepcopy
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from common.common import parse_args
import models.classifier as C
from datasets import get_dataset, get_superclass_list, get_subclass_dataset
P = parse_args()
### Set torch device ###
P.n_gpus = torch.cuda.device_... | 2,909 | 34.487805 | 117 | py |
CSI | CSI-master/common/train.py | from copy import deepcopy
import torch
import torch.nn as nn
import torch.optim as optim
import torch.optim.lr_scheduler as lr_scheduler
from torch.utils.data import DataLoader
from common.common import parse_args
import models.classifier as C
from datasets import get_dataset, get_superclass_list, get_subclass_datase... | 5,490 | 35.852349 | 118 | py |
CSI | CSI-master/training/contrastive_loss.py | import torch
import torch.distributed as dist
import diffdist.functional as distops
def get_similarity_matrix(outputs, chunk=2, multi_gpu=False):
'''
Compute similarity matrix
- outputs: (B', d) tensor for B' = B * chunk
- sim_matrix: (B', B') tensor
'''
if multi_gpu:
outp... | 2,615 | 31.7 | 102 | py |
CSI | CSI-master/training/scheduler.py | from torch.optim.lr_scheduler import _LRScheduler
from torch.optim.lr_scheduler import ReduceLROnPlateau
class GradualWarmupScheduler(_LRScheduler):
""" Gradually warm-up(increasing) learning rate in optimizer.
Proposed in 'Accurate, Large Minibatch SGD: Training ImageNet in 1 Hour'.
Args:
optimi... | 3,069 | 46.96875 | 152 | py |
CSI | CSI-master/training/__init__.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def update_learning_rate(P, optimizer, cur_epoch, n, n_total):
cur_epoch = cur_epoch - 1
lr = P.lr_init
if P.optimizer == 'sgd' or 'lars':
DECAY_RATIO = 0.1
elif P.optimizer == 'adam':
DECAY_RATIO = 0.3
else:
... | 2,719 | 27.041237 | 75 | py |
CSI | CSI-master/training/unsup/simclr.py | import time
import torch.optim
import models.transform_layers as TL
from training.contrastive_loss import get_similarity_matrix, NT_xent
from utils.utils import AverageMeter, normalize
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hflip = TL.HorizontalFlipLayer().to(device)
def train(P, epo... | 3,305 | 31.411765 | 80 | py |
CSI | CSI-master/training/unsup/simclr_CSI.py | import time
import torch.optim
import models.transform_layers as TL
from training.contrastive_loss import get_similarity_matrix, NT_xent
from utils.utils import AverageMeter, normalize
device = torch.device(f"cuda" if torch.cuda.is_available() else "cpu")
hflip = TL.HorizontalFlipLayer().to(device)
def train(P, ep... | 4,221 | 36.035088 | 103 | py |
CSI | CSI-master/training/sup/sup_CSI_linear.py | import time
import torch.optim
import torch.optim.lr_scheduler as lr_scheduler
import models.transform_layers as TL
from utils.utils import AverageMeter, normalize
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hflip = TL.HorizontalFlipLayer().to(device)
def train(P, epoch, model, criterion,... | 4,852 | 36.045802 | 109 | py |
CSI | CSI-master/training/sup/sup_linear.py | import time
import torch.optim
import torch.optim.lr_scheduler as lr_scheduler
import models.transform_layers as TL
from utils.utils import AverageMeter, normalize
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hflip = TL.HorizontalFlipLayer().to(device)
def train(P, epoch, model, criterion,... | 2,909 | 30.630435 | 103 | py |
CSI | CSI-master/training/sup/sup_simclr_CSI.py | import time
import torch.optim
import models.transform_layers as TL
from training.contrastive_loss import get_similarity_matrix, Supervised_NT_xent
from utils.utils import AverageMeter, normalize
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hflip = TL.HorizontalFlipLayer().to(device)
def t... | 3,970 | 34.774775 | 96 | py |
CSI | CSI-master/training/sup/sup_simclr.py | import time
import torch.optim
import models.transform_layers as TL
from training.contrastive_loss import get_similarity_matrix, Supervised_NT_xent
from utils.utils import AverageMeter, normalize
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hflip = TL.HorizontalFlipLayer().to(device)
def t... | 3,643 | 33.704762 | 120 | py |
CSI | CSI-master/models/resnet_imagenet.py | import torch
import torch.nn as nn
from models.base_model import BaseModel
from models.transform_layers import NormalizeLayer
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
... | 8,640 | 36.24569 | 107 | py |
CSI | CSI-master/models/base_model.py | from abc import *
import torch.nn as nn
class BaseModel(nn.Module, metaclass=ABCMeta):
def __init__(self, last_dim, num_classes=10, simclr_dim=128):
super(BaseModel, self).__init__()
self.linear = nn.Linear(last_dim, num_classes)
self.simclr_layer = nn.Sequential(
nn.Linear(las... | 1,372 | 27.020408 | 89 | py |
CSI | CSI-master/models/resnet.py | '''ResNet in PyTorch.
BasicBlock and Bottleneck module is from the original ResNet paper:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
PreActBlock and PreActBottleneck module is from the later paper:
[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren,... | 6,617 | 34.015873 | 102 | py |
CSI | CSI-master/models/classifier.py | import torch.nn as nn
from models.resnet import ResNet18, ResNet34, ResNet50
from models.resnet_imagenet import resnet18, resnet50
import models.transform_layers as TL
def get_simclr_augmentation(P, image_size):
# parameter for resizecrop
resize_scale = (P.resize_factor, 1.0) # resize scaling factor
if ... | 2,140 | 26.805195 | 100 | py |
CSI | CSI-master/models/transform_layers.py | import math
import numbers
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Function
if torch.__version__ >= '1.4.0':
kwargs = {'align_corners': False}
else:
kwargs = {}
def rgb2hsv(rgb):
"""Convert a 4-d RGB tensor to the HSV counterpart.
... | 13,870 | 31.333333 | 103 | py |
CSI | CSI-master/evals/ood_pre.py | import os
from copy import deepcopy
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import models.transform_layers as TL
from utils.utils import set_random_seed, normalize
from evals.evals import get_auroc
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
hfl... | 8,649 | 34.892116 | 114 | py |
CSI | CSI-master/evals/evals.py | import time
import itertools
import diffdist.functional as distops
import numpy as np
import torch
import torch.distributed as dist
import torch.nn as nn
import torch.nn.functional as F
from sklearn.metrics import roc_auc_score
import models.transform_layers as TL
from utils.temperature_scaling import _ECELoss
from u... | 6,450 | 30.935644 | 105 | py |
CSI | CSI-master/datasets/imagenet_fix_preprocess.py | import os
import time
import random
import cv2
import numpy as np
import torch
import torch.nn.functional as F
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torchvision.utils import save_image
from datasets import get_subclass_dataset
def set_random_seed(seed):
random... | 1,779 | 25.567164 | 105 | py |
CSI | CSI-master/datasets/datasets.py | import os
import numpy as np
import torch
from torch.utils.data.dataset import Subset
from torchvision import datasets, transforms
from utils.utils import set_random_seed
DATA_PATH = '~/data/'
IMAGENET_PATH = '~/data/ImageNet'
CIFAR10_SUPERCLASS = list(range(10)) # one class
IMAGENET_SUPERCLASS = list(range(30)) ... | 9,723 | 33.119298 | 111 | py |
CSI | CSI-master/datasets/lsun_fix_preprocess.py | import os
import time
import random
import numpy as np
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torchvision.utils import save_image
def set_random_seed(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual... | 1,697 | 26.387097 | 101 | py |
CSI | CSI-master/utils/utils.py | import os
import pickle
import random
import shutil
import sys
from datetime import datetime
import numpy as np
import torch
from matplotlib import pyplot as plt
from tensorboardX import SummaryWriter
class Logger(object):
"""Reference: https://gist.github.com/gyglim/1f8dfb1b5c82627ae3efcfbbadb9f514"""
def ... | 6,511 | 30.61165 | 119 | py |
CSI | CSI-master/utils/temperature_scaling.py | import torch
from torch import nn, optim
from torch.nn import functional as F
class ModelWithTemperature(nn.Module):
"""
A thin decorator, which wraps a model with temperature scaling
model (nn.Module):
A classification neural network
NB: Output of the neural network should be the classifi... | 4,728 | 38.408333 | 109 | py |
kuaizi | kuaizi-master/diezi/scarlet_modeling/script/paper_figure.py | # Make figures for the paper
import numpy as np
import matplotlib.pyplot as plt
from astropy.table import Table, Column, Row, vstack, hstack
from sample_cuts import moving_binned_statistic
import pickle
# def plot_size_distribution(udg_cat, fake_udg_cat, udg_area, fake_udg_area, fake_udg_repeats=10 * 20, name='UDG',
... | 47,740 | 44.904808 | 177 | py |
AdvBCT | AdvBCT-main/test.py | import argparse
import os
from datetime import timedelta
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
from data_loaders import build_test_dataloader
from models import build_bct_models
from logger.logger import create_logger
from utils.util import cudalize
from evaluate.eval impo... | 3,930 | 40.378947 | 117 | py |
AdvBCT | AdvBCT-main/extract_feat.py | import torch
import os
import argparse
import json
import numpy as np
from collections import defaultdict
from models import build_bct_models
from configs import get_config
from data_loaders import build_train_dataloader
import math
def main(config):
_, model = build_bct_models("base_model", configs=config, debug... | 6,098 | 39.390728 | 138 | py |
AdvBCT | AdvBCT-main/train.py | import os
import argparse
import torch
import torch.backends.cudnn as cudnn
import torch.distributed as dist
import torch.nn as nn
from configs import get_config
from logger.logger import create_logger
from data_loaders import build_train_dataloader, build_test_dataloader, build_reid_dataloader
from models import bui... | 10,781 | 50.836538 | 130 | py |
AdvBCT | AdvBCT-main/trainer/reid_trainer.py | import os
from pathlib import Path
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
# from evaluate.evaluate import evaluate_func
from evaluate import evaluate_func
from models.margin_softmax import large_margin_module
from utils.util import AverageMeter, t... | 19,313 | 42.995444 | 125 | py |
AdvBCT | AdvBCT-main/trainer/trainer.py | import os
from pathlib import Path
import time
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.distributed as dist
from evaluate import evaluate_func
from models.margin_softmax import large_margin_module
from utils.util import AverageMeter, tensor_to_float
from torch.utils.te... | 32,808 | 48.937595 | 172 | py |
AdvBCT | AdvBCT-main/solver/lr_scheduler.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from bisect import bisect_right
import torch
# FIXME ideally this would be achieved with a CombinedLRScheduler,
# separating MultiStepLR with WarmupLR
# but the current LRScheduler design doesn't allow it
class WarmupMultiStepLR(torch.... | 1,862 | 31.684211 | 80 | py |
AdvBCT | AdvBCT-main/solver/cosine_lr.py | """ Cosine Scheduler
Cosine LR schedule with warmup, cycle/restarts, noise.
Hacked together by / Copyright 2020 Ross Wightman
"""
import logging
import math
import torch
from .scheduler import Scheduler
_logger = logging.getLogger(__name__)
class CosineLRScheduler(Scheduler):
"""
Cosine decay with restar... | 3,958 | 33.12931 | 121 | py |
AdvBCT | AdvBCT-main/solver/scheduler.py | from typing import Dict, Any
import torch
class Scheduler:
""" Parameter Scheduler Base Class
A scheduler base class that can be used to schedule any optimizer parameter groups.
Unlike the builtin PyTorch schedulers, this is intended to be consistently called
* At the END of each epoch, before incre... | 4,750 | 43.820755 | 112 | py |
AdvBCT | AdvBCT-main/solver/make_optimizer.py | import torch
def make_optimizer(cfg, model, center_criterion):
params = []
for key, value in model.named_parameters():
if not value.requires_grad:
continue
lr = cfg.SOLVER.BASE_LR
weight_decay = cfg.SOLVER.WEIGHT_DECAY
if "bias" in key:
lr = cfg.SOLVER.B... | 1,215 | 39.533333 | 106 | py |
AdvBCT | AdvBCT-main/models/base_model.py | import timm
import torch.nn as nn
import torch
import os.path as osp
from loss.reid.metric_learning import Arcface, Cosface, AMSoftmax, CircleLoss
from models.modules import MLP,ReverseLayerF,Transformation,ElasticBoundary
class CreateBaseModel(nn.Module):
def __init__(self,configs):
'''
:param args... | 8,480 | 42.943005 | 150 | py |
AdvBCT | AdvBCT-main/models/test.py | import torch
from models import build_bct_models
_,new_model=build_bct_models("base_model",debug=True)
x=torch.zeros((3,3,224,224))
new_model.train()
feature,y = new_model(x)
print(feature.shape)
print(y) | 205 | 21.888889 | 53 | py |
AdvBCT | AdvBCT-main/models/margin_softmax.py | import torch
def large_margin_module(name, cosine, label, s, m):
if name == "arcface":
return arcface(cosine, label, s, m)
elif name == "cosface":
return cosface(cosine, label, s, m)
else:
raise NotImplementedError
def cosface(cosine, label, s, m):
index = torch.where(label !... | 809 | 26.931034 | 80 | py |
AdvBCT | AdvBCT-main/models/modules.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from torch.autograd import Function
class ReverseLayerF(Function):
@staticmethod
def forward(ctx, x, alpha):
ctx.alpha = alpha
return x.view_as(x)
@staticmethod
def backward(ctx, grad_output):
output = grad_out... | 2,416 | 28.839506 | 90 | py |
AdvBCT | AdvBCT-main/models/loss.py | import torch
from torch import nn
import torch.nn.functional as F
import torch.distributed as dist
from pytorch_metric_learning.utils import common_functions as c_f
from pytorch_metric_learning.losses import CrossBatchMemory
from pytorch_metric_learning.utils.module_with_records import ModuleWithRecords
from pytorch_me... | 27,552 | 42.254317 | 165 | py |
AdvBCT | AdvBCT-main/logger/logger.py | import os
import sys
import json
import logging
import logging.config
from pathlib import Path
from collections import OrderedDict
import functools
from termcolor import colored
import torch.distributed as dist
@functools.lru_cache()
def create_logger(output_dir, dist_rank=0, name=''):
if not os.path.exists(output... | 1,461 | 32.227273 | 102 | py |
AdvBCT | AdvBCT-main/loss/reid/metric_learning.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd
from torch.nn import Parameter
import math
class ContrastiveLoss(nn.Module):
def __init__(self, margin=0.3, **kwargs):
super(ContrastiveLoss, self).__init__()
self.margin = margin
def forward(self, inputs... | 7,001 | 36.047619 | 121 | py |
AdvBCT | AdvBCT-main/loss/reid/softmax_loss.py | import torch
import torch.nn as nn
from torch.nn import functional as F
class CrossEntropyLabelSmooth(nn.Module):
"""Cross entropy loss with label smoothing regularizer.
Reference:
Szegedy et al. Rethinking the Inception Architecture for Computer Vision. CVPR 2016.
Equation: y = (1 - epsilon) * y + eps... | 2,037 | 35.392857 | 95 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.