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 |
|---|---|---|---|---|---|---|
FeatureRE | FeatureRE-main/unet_model.py | """
A PyTorch Implementation of a U-Net.
Supports 2D (https://arxiv.org/abs/1505.04597) and 3D(https://arxiv.org/abs/1606.06650) variants
Author: Ishaan Bhat
Email: ishaan@isi.uu.nl
"""
from unet_blocks import *
from math import pow
class UNet(nn.Module):
"""
PyTorch class definition for the U-Net architectu... | 10,176 | 49.381188 | 162 | py |
FeatureRE | FeatureRE-main/dataloader.py | import torch.utils.data as data
import torch
import torchvision
import torchvision.transforms as transforms
import os
import csv
import random
import numpy as np
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import Dataset
from io import BytesIO
def get_transform(opt... | 8,265 | 37.990566 | 142 | py |
FeatureRE | FeatureRE-main/config.py | import argparse
def get_argument():
parser = argparse.ArgumentParser()
# Directory option
parser.add_argument("--checkpoints", type=str, default="../../checkpoints/")
parser.add_argument("--data_root", type=str, default="../../data/")
parser.add_argument("--device", type=str, default="cuda")
... | 1,827 | 39.622222 | 80 | py |
FeatureRE | FeatureRE-main/models.py | import torch
import torch.nn.functional as F
import torchvision
from torch import nn
from torch.nn import Module
from torchvision import transforms
from .blocks import *
class Normalize:
def __init__(self, opt, expected_values, variance):
self.n_channels = opt.input_channel
self.expected_values =... | 4,338 | 32.898438 | 106 | py |
FeatureRE | FeatureRE-main/resnet_nole.py | import torch.nn as nn
import math
def conv3x3(in_planes, out_planes, stride=1):
# 3x3 convolution with padding
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, downsa... | 5,495 | 29.703911 | 109 | py |
FeatureRE | FeatureRE-main/detection.py | from reverse_engineering import *
from config import get_argument
from dataloader import get_dataloader_label_remove, get_dataloader_partial_split
import time
def main():
start_time = time.time()
opt = get_argument().parse_args()
if opt.dataset == "cifar10":
opt.input_height = 32
opt.input... | 4,155 | 36.107143 | 140 | py |
FeatureRE | FeatureRE-main/mitigation.py | from reverse_engineering import *
from config import get_argument
from dataloader import get_dataloader_label_remove, get_dataloader_partial_split
import time
def main():
start_time = time.time()
opt = get_argument().parse_args()
if opt.dataset == "cifar10":
opt.input_height = 32
opt.input... | 3,433 | 35.924731 | 140 | py |
FeatureRE | FeatureRE-main/train_models/dataloader.py | import torch.utils.data as data
import torch
import torchvision
import torchvision.transforms as transforms
import os
import csv
import kornia.augmentation as A
import random
import numpy as np
from PIL import Image
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import Dataset
from natsort im... | 6,855 | 36.26087 | 119 | py |
FeatureRE | FeatureRE-main/train_models/train_model.py | import json
import os
import shutil
from time import time
import config
import numpy as np
import torch
import torch.nn.functional as F
import torchvision
from torch import nn
from torch.utils.tensorboard import SummaryWriter
from torchvision.transforms import RandomErasing
from dataloader import PostTensorTransform, ... | 16,640 | 34.107595 | 125 | py |
FeatureRE | FeatureRE-main/train_models/config.py | import argparse
def get_arguments():
parser = argparse.ArgumentParser()
parser.add_argument("--data_root", type=str, default="./data/")
parser.add_argument("--checkpoints", type=str, default="./checkpoints")
parser.add_argument("--temps", type=str, default="./temps")
parser.add_argument("--device... | 1,966 | 42.711111 | 103 | py |
FeatureRE | FeatureRE-main/train_models/resnet_nole.py | import torch.nn as nn
import math
def conv3x3(in_planes, out_planes, stride=1):
# 3x3 convolution with padding
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
'''class BasicBlock(nn.Module):
expansion = 1
def __init__(self, inplanes, planes, stride=1, do... | 26,787 | 28.21265 | 109 | py |
FeatureRE | FeatureRE-main/models/meta_classifier_cifar10_model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class MetaClassifierCifar10Model(nn.Module):
def __init__(self):
super(MetaClassifierCifar10Model, self).__init__()
#self.gpu = gpu
self.conv1 = nn.Conv2d(3, 32, kernel_size=3, padding=1)
self.con... | 2,441 | 31.131579 | 70 | py |
FeatureRE | FeatureRE-main/models/preact_resnet.py | """Pre-activation ResNet in PyTorch.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Identity Mappings in Deep Residual Networks. arXiv:1603.05027
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class PreActBlock(nn.Module):
"""Pre-activation version of the BasicBlock.... | 7,366 | 29.316872 | 103 | py |
FeatureRE | FeatureRE-main/models/ULP_model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
#from utils.stn import STN
class CNN_classifier(nn.Module):
""" MNIST Encoder from Original Paper's Keras based Implementation.
Args:
init_num_filters (int): initial number of filters from encoder image channels
lrel... | 2,934 | 36.628205 | 121 | py |
FeatureRE | FeatureRE-main/models/lenet.py | # This part is borrowed from https://github.com/huawei-noah/Data-Efficient-Model-Compression
import torch.nn as nn
class LeNet5(nn.Module):
def __init__(self,in_channels=1):
super(LeNet5, self).__init__()
self.conv1 = nn.Conv2d(in_channels, 6, kernel_size=(5, 5))
self.relu1 = nn.ReLU()
... | 4,665 | 31.859155 | 102 | py |
FeatureRE | FeatureRE-main/models/__init__.py | 0 | 0 | 0 | py | |
MRL-CQA | MRL-CQA-master/S2SRL/train_scst_nsm.py | #!/usr/bin/env python3
import os
import sys
import random
import argparse
import logging
import numpy as np
from tensorboardX import SummaryWriter
from libbots import data, model, utils
import torch
import torch.optim as optim
import torch.nn.functional as F
import time
import ptan
SAVES_DIR = "../data/saves"
BATCH_... | 27,125 | 57.461207 | 153 | py |
MRL-CQA | MRL-CQA-master/S2SRL/data_test_maml.py | # !/usr/bin/env python3
# The file is used to predict the action sequences for full-data test dataset.
import argparse
import logging
import sys
from libbots import data, model, utils, metalearner
import torch
log = logging.getLogger("data_test")
DIC_PATH = '../data/auto_QA_data/share.question'
TRAIN_944K_QUESTION_A... | 8,582 | 58.193103 | 211 | py |
MRL-CQA | MRL-CQA-master/S2SRL/train_reptile_maml_true_reward.py | #!/usr/bin/env python3
import os
import sys
import random
import argparse
import logging
import numpy as np
from tensorboardX import SummaryWriter
from libbots import data, model, utils, metalearner
import torch
import time
import ptan
SAVES_DIR = "../data/saves"
MAX_EPOCHES = 30
MAX_TOKENS = 40
TRAIN_RATIO = 0.985
... | 15,550 | 59.984314 | 436 | py |
MRL-CQA | MRL-CQA-master/S2SRL/__init__.py | # -*- coding: utf-8 -*-
# @Time : 2019/8/31 05:18 AM
# To set the root path fot import class from other packages.
import os
import sys
sys.path.append(os.path.realpath(os.getcwd()))
| 185 | 25.571429 | 60 | py |
MRL-CQA | MRL-CQA-master/S2SRL/SymbolicExecutor/transform_util.py | # -*- coding: utf-8 -*-
# @Time : 2019/9/1 23:36
# Function : transforming.
# Transform boolean results into string format.
def transformBooleanToString(list):
temp_set = set()
if len(list) == 0:
return ''
else:
for i, item in enumerate(list):
if item == True:
... | 4,018 | 33.646552 | 165 | py |
MRL-CQA | MRL-CQA-master/S2SRL/SymbolicExecutor/calculate_sample_test_dataset.py | # -*- coding: utf-8 -*-
# @Time : 2019/4/8 21:02
# @Author : Yaoleo
# @Blog : yaoleo.github.io
# coding:utf-8
'''Get all questions, annotated actions, entities, relations, types together in JSON format.
'''
import json
from symbolics import Symbolics
from transform_util import transformBooleanToString, list2di... | 21,453 | 54.293814 | 183 | py |
MRL-CQA | MRL-CQA-master/S2SRL/SymbolicExecutor/symbolics_webqsp_novar.py | # -*- coding: utf-8 -*-
import json
import datetime
import re
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
import requests
def get_id(idx):
return int(idx[1:])
from flask import Flask, request, jsonify
app = Flask(__name__)
# Remote Server
# post_url = "http... | 29,035 | 38.184885 | 113 | py |
MRL-CQA | MRL-CQA-master/S2SRL/SymbolicExecutor/symbolics_webqsp.py | # -*- coding: utf-8 -*-
import json
import re
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
import requests
def get_id(idx):
return int(idx[1:])
from flask import Flask, request, jsonify
app = Flask(__name__)
# Remote Server
# post_url = "http://10.201.34.3:5... | 24,628 | 37.422777 | 113 | py |
MRL-CQA | MRL-CQA-master/S2SRL/SymbolicExecutor/__init__.py | # -*- coding: utf-8 -*-
# @Time : 2019/1/18 15:40
| 55 | 10.2 | 28 | py |
MRL-CQA | MRL-CQA-master/S2SRL/SymbolicExecutor/symbolics.py | # -*- coding: utf-8 -*-
# @Time : 2019/1/18 14:52
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
import pickle
import requests
def get_id(idx):
return int(idx[1:])
class Symbolics():
def __init__(self, seq, mode='online'):
if mode != 'online':
... | 25,278 | 37.831029 | 113 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/adabound.py | import math
import torch
from torch.optim import Optimizer
class AdaBound(Optimizer):
"""Implements AdaBound algorithm.
It has been proposed in `Adaptive Gradient Methods with Dynamic Bound of Learning Rate`_.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
... | 11,340 | 47.465812 | 101 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/reparam_module.py | import torch
import torch.nn as nn
import warnings
import types
from collections import namedtuple
from contextlib import contextmanager
# A module is a container from which layers, model subparts (e.g. BasicBlock in resnet in torchvision) and models should inherit.
# Why should they? Because the inheritance from nn.M... | 12,442 | 53.336245 | 152 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/beam_search_node.py | class BeamSearchNode(object):
def __init__(self, hiddenstate, previousNode, wordId, logProb, length, logits):
'''
:param hiddenstate:
:param previousNode:
:param wordId:
:param logProb:
:param length:
'''
self.h = hiddenstate
self.prevNode = pr... | 796 | 30.88 | 83 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/retriever.py | # -*- coding: utf-8 -*-
import json
import string
import os
from functools import cmp_to_key
import random
class Retriever():
def __init__(self, dict944k, dict944k_weak):
self.dict944k = dict944k
self.dict944k_weak = dict944k_weak
self.typelist = ['Simple Question (Direct)_',
'V... | 11,662 | 45.098814 | 118 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/bert_model.py | import numpy as np
import operator
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
import torch.nn.functional as F
from transformers import BertModel, BertTokenizer, AdamW, get_linear_schedule_with_warmup
from . import utils
from . import attention
from . import beam_search_node
from queue im... | 23,511 | 46.595142 | 177 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/utils.py | import string
import nltk
from nltk.translate import bleu_score
from nltk.tokenize import TweetTokenizer
from SymbolicExecutor.symbolics import Symbolics
from SymbolicExecutor.symbolics_webqsp import Symbolics_WebQSP
from SymbolicExecutor.symbolics_webqsp_novar import Symbolics_WebQSP_novar
from SymbolicExecutor.transf... | 19,246 | 41.394273 | 200 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/model.py | import numpy as np
import operator
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
import torch.nn.functional as F
from collections import OrderedDict
from . import utils
from . import attention
from . import beam_search_node
from queue import PriorityQueue
HIDDEN_STATE_SIZE = 128
EMBEDDING_... | 22,030 | 47.10262 | 177 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/data.py | import collections
import os
import sys
import logging
import itertools
import pickle
import json
import torch
from . import cornell
UNKNOWN_TOKEN = '#UNK'
BEGIN_TOKEN = "#BEG"
END_TOKEN = "#END"
MAX_TOKENS = 30
MIN_TOKEN_FEQ = 1
SHUFFLE_SEED = 1987
LINE_SIZE = 50000
EMB_DICT_NAME = "emb_dict.dat"
EMB_NAME = "emb.np... | 21,655 | 35.705085 | 257 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/metalearner.py | import torch
from torch.nn.utils.convert_parameters import (vector_to_parameters,
parameters_to_vector)
from . import data, model, utils, retriever, reparam_module, adabound
import torch.optim as optim
import torch.nn.functional as F
import random
import logging
from torch... | 91,609 | 58.603123 | 328 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/__init__.py | from .adabound import AdaBound | 30 | 30 | 30 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/cornell.py | """
Cornel Movies Dialogs Corpus
https://www.cs.cornell.edu/~cristian/Cornell_Movie-Dialogs_Corpus.html
"""
import os
import logging
from . import utils
log = logging.getLogger("cornell")
DATA_DIR = "data/cornell"
SEPARATOR = "+++$+++"
def load_dialogues(data_dir=DATA_DIR, genre_filter=''):
"""
Load dialogu... | 2,447 | 29.222222 | 80 | py |
MRL-CQA | MRL-CQA-master/S2SRL/libbots/attention.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.utils.rnn as rnn_utils
class Attention(nn.Module):
r"""
Applies an attention mechanism on the output features from the decoder.
.. math::
\begin{array}{ll}
x = context*output \\
attn = ex... | 4,204 | 45.722222 | 191 | py |
MRL-CQA | MRL-CQA-master/BFS/test.py | # -*- coding: utf-8 -*-
# @Time : 2019/2/25 21:50
import json
import pickle
from urllib.parse import urlencode
import requests
from tqdm import tqdm
# def get_id(idx):
# return int(idx[1:])
#
# entity_items = json.load(open('/data/zjy/csqa_data/wikidata_dir'+'/items_wikidata_n.json'))
# # pickle.dump(entity_it... | 1,751 | 29.206897 | 93 | py |
MRL-CQA | MRL-CQA-master/BFS/server.py | import os
import json
import pickle
from flask import Flask, request, jsonify
app = Flask(__name__)
def get_id(idx):
return int(idx[1:])
def select(e,r,t):
if r.startswith("-") and 'obj' in graph[get_id(e)] and r[1:] in graph[get_id(e)]['obj']:
return [ee for ee in graph[get_id(e)]['obj'][r[1:]] if t ... | 3,326 | 34.021053 | 92 | py |
MRL-CQA | MRL-CQA-master/BFS/agent.py | import os
import requests
from urllib import request
import pickle
import json
def get_id(idx):
return int(idx[1:])
class KB(object):
def __init__(self,mode='online'):
if mode!='online':
print("loading knowledge base...")
self.graph=pickle.load(open('/data/zjy/wikidata.pkl','r... | 5,487 | 34.636364 | 105 | py |
MRL-CQA | MRL-CQA-master/BFS/preprocess.py | import os
import requests
from urllib import request
import pickle
import json
from tqdm import tqdm
def get_id(idx):
return int(idx[1:])
def create_kb():
entity_items=json.load(open('/data/zjy/csqa_data/wikidata_dir/items_wikidata_n.json'))
max_id=0
for idx in tqdm(entity_items,total=len(entity_items... | 3,114 | 32.138298 | 94 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/main.py | """
Implementation of ECCV 2018 paper "Graph R-CNN for Scene Graph Generation".
Author: Jianwei Yang, Jiasen Lu, Stefan Lee, Dhruv Batra, Devi Parikh
Contact: jw2yang@gatech.edu
"""
import os
import pprint
import argparse
import numpy as np
import torch
import datetime
from lib.config import cfg
from lib.model import... | 3,200 | 33.419355 | 87 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/demo/webcam.py | 0 | 0 | 0 | py | |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/demo/predict.py | 0 | 0 | 0 | py | |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/model.py | import os
import datetime
import logging
import time
import numpy as np
import torch
import cv2
from .data.build import build_data_loader
from .scene_parser.parser import build_scene_parser
from .scene_parser.parser import build_scene_parser_optimizer
from .scene_parser.rcnn.utils.metric_logger import MetricLogger
from... | 13,581 | 43.097403 | 132 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/config/defaults.py | import os
import os.path as osp
import numpy as np
from yacs.config import CfgNode as CN
from easydict import EasyDict as edict
_C = CN()
""""======================================="""
_C.DATASET = CN()
_C.DATASET.NAME = "vg"
_C.DATASET.MODE = "benchmark" # dataset mode, benchmark | 1600-400-400 | ... | 15,656 | 38.339196 | 153 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/config/__init__.py | from .defaults import _C as cfg
| 32 | 15.5 | 31 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/config/paths_catalog.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
class DatasetCatalog(object):
DATA_DIR = "datasets"
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/annotations/instances_trai... | 7,876 | 39.394872 | 121 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/parser.py | """
Main code of scene parser
"""
import os
import logging
import torch
import copy
import torch.nn as nn
from .rcnn.modeling.detector.generalized_rcnn import GeneralizedRCNN
from .rcnn.solver import make_lr_scheduler
from .rcnn.solver import make_optimizer
from .rcnn.utils.checkpoint import SceneParserCheckpointer
fr... | 8,133 | 40.28934 | 119 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/__init__.py | 0 | 0 | 0 | py | |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/setup.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
#!/usr/bin/env python
import glob
import os
import torch
from setuptools import find_packages
from setuptools import setup
from torch.utils.cpp_extension import CUDA_HOME
from torch.utils.cpp_extension import CppExtension
from torch.utils.cpp_ext... | 2,027 | 27.971429 | 100 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
| 72 | 35.5 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/solver/lr_scheduler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
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.optim.lr_s... | 1,817 | 33.301887 | 80 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/solver/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .build import make_optimizer
from .build import make_lr_scheduler
from .lr_scheduler import WarmupMultiStepLR
| 187 | 36.6 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/solver/build.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .lr_scheduler import WarmupMultiStepLR
def make_optimizer(cfg, model):
params = []
lr = cfg.SOLVER.BASE_LR
for key, value in model.named_parameters():
if not value.requires_grad:
continue
... | 972 | 29.40625 | 79 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/config/defaults.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from yacs.config import CfgNode as CN
# -----------------------------------------------------------------------------
# Convention about Training / Test specific parameters
# ------------------------------------------------------------... | 18,404 | 36.948454 | 83 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/config/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .defaults import _C as cfg
| 104 | 34 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/config/paths_catalog.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""Centralized catalog of paths."""
import os
class DatasetCatalog(object):
DATA_DIR = "datasets"
DATASETS = {
"coco_2017_train": {
"img_dir": "coco/train2017",
"ann_file": "coco/annotations/instances_trai... | 7,876 | 39.394872 | 121 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/nms.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# from ._utils import _C
from lib.scene_parser.rcnn import _C
# from apex import amp
# Only valid with fp32 inputs - give AMP the hint
# nms = amp.float_function(_C.nms)
nms = _C.nms
# nms.__doc__ = """
# This function performs Non-maximum suppre... | 328 | 26.416667 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/batch_norm.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
class FrozenBatchNorm2d(nn.Module):
"""
BatchNorm2d where the batch statistics and the affine parameters
are fixed
"""
def __init__(self, n):
super(FrozenBatchNorm2d, self).__init__()... | 1,094 | 33.21875 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/roi_pool.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from lib.scene_parser.rcnn import _C
# from apex import amp
class _ROIPool(Fun... | 1,907 | 27.909091 | 74 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/roi_align.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from lib.scene_parser.rcnn import _C
# from apex import amp
class _ROIAlign(Fu... | 2,161 | 29.885714 | 85 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/smooth_l1_loss.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
# TODO maybe push this to nn?
def smooth_l1_loss(input, target, beta=1. / 9, size_average=True):
"""
very similar to the smooth_l1_loss from pytorch, but with
the extra beta parameter
"""
n = torch.abs(input - tar... | 481 | 27.352941 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/sigmoid_focal_loss.py | import torch
from torch import nn
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from lib.scene_parser.rcnn import _C
# TODO: Use JIT to replace CUDA implementation in the future.
class _SigmoidFocalLoss(Function):
@staticmethod
def forward(ctx, logits, targets, ga... | 2,345 | 29.467532 | 118 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/_utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import glob
import os.path
import torch
try:
from torch.utils.cpp_extension import load as load_ext
from torch.utils.cpp_extension import CUDA_HOME
except ImportError:
raise ImportError("The cpp layer extensions requires PyTorch 0.4 o... | 1,165 | 28.15 | 80 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/misc.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
helper class that supports empty tensors on some nn functions.
Ideally, add support directly in PyTorch to empty tensors in
those functions.
This can be removed once https://github.com/pytorch/pytorch/issues/12013
is implemented
"""
import m... | 6,625 | 31.480392 | 88 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .batch_norm import FrozenBatchNorm2d
from .misc import Conv2d
from .misc import DFConv2d
from .misc import ConvTranspose2d
from .misc import BatchNorm2d
from .misc import interpolate
from .nms import nms
from .roi_align import RO... | 1,327 | 26.666667 | 105 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/dcn/deform_conv_func.py | import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from torch.nn.modules.utils import _pair
from lib.scene_parser.rcnn import _C
class DeformConvFunction(Function):
@staticmethod
def forward(
ctx,
input,
offset,
weight,
... | 8,312 | 30.608365 | 83 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/dcn/deform_pool_func.py | import torch
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from lib.scene_parser.rcnn import _C
class DeformRoIPoolingFunction(Function):
@staticmethod
def forward(
ctx,
data,
rois,
offset,
spatial_scale,
out_size,
... | 2,597 | 26.347368 | 99 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/dcn/deform_pool_module.py | from torch import nn
from .deform_pool_func import deform_roi_pooling
class DeformRoIPooling(nn.Module):
def __init__(self,
spatial_scale,
out_size,
out_channels,
no_trans,
group_size=1,
part_size=None,
... | 6,306 | 41.046667 | 79 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/dcn/__init__.py | #
# Copied From [mmdetection](https://github.com/open-mmlab/mmdetection/tree/master/mmdet/ops/dcn)
#
| 101 | 24.5 | 96 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/layers/dcn/deform_conv_module.py | import math
import torch
import torch.nn as nn
from torch.nn.modules.utils import _pair
from .deform_conv_func import deform_conv, modulated_deform_conv
class DeformConv(nn.Module):
def __init__(
self,
in_channels,
out_channels,
kernel_size,
stride=1,
padding=0,
... | 5,802 | 31.601124 | 78 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/engine/inference.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import time
import os
import torch
from tqdm import tqdm
from lib.config import cfg
from lib.data.datasets.evaluation import evaluate
from ..utils.comm import is_main_process, get_world_size
from ..utils.comm import all_gather
from... | 4,027 | 32.289256 | 96 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/engine/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
| 72 | 35.5 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/engine/bbox_aug.py | import torch
import torchvision.transforms as TT
from lib.config import cfg
from lib.data import transforms as T
from lib.scene_parser.rcnn.structures.image_list import to_image_list
from lib.scene_parser.rcnn.structures.bounding_box import BoxList
from lib.scene_parser.rcnn.modeling.roi_heads.box_head.inference impor... | 4,418 | 36.449153 | 99 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/engine/trainer.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import datetime
import logging
import time
import torch
import torch.distributed as dist
from lib.scene_parser.rcnn.utils.comm import get_world_size
from lib.scene_parser.rcnn.utils.metric_logger import MetricLogger
from apex import amp
def red... | 4,251 | 33.290323 | 146 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/c2_model_loading.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import pickle
from collections import OrderedDict
import torch
from .model_serialization import load_state_dict
from .registry import Registry
def _rename_basic_resnet_weights(layer_keys):
layer_keys = [k.replace("_", ".") fo... | 8,444 | 39.023697 | 129 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/metric_logger.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import defaultdict
from collections import deque
import torch
class SmoothedValue(object):
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __... | 1,862 | 26.80597 | 82 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/checkpoint.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import torch
from .model_serialization import load_state_dict
from .c2_model_loading import load_c2_format
from .imports import import_file
from .model_zoo import cache_url
class Checkpointer(object):
def __init__(
... | 6,815 | 34.5 | 108 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/timer.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import time
import datetime
class Timer(object):
def __init__(self):
self.reset()
@property
def average_time(self):
return self.total_time / self.calls if self.calls > 0 else 0.0
def tic(self):
# using ... | 1,127 | 23 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/comm.py | """
This file contains primitives for multi-gpu communication.
This is useful when doing distributed training.
"""
import pickle
import time
import torch
import torch.distributed as dist
def get_world_size():
if not dist.is_available():
return 1
if not dist.is_initialized():
return 1
ret... | 3,372 | 27.584746 | 84 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/registry.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
def _register_generic(module_dict, module_name, module):
assert module_name not in module_dict
module_dict[module_name] = module
class Registry(dict):
'''
A helper class for managing registering modules, it extends a dictionary
... | 1,385 | 29.130435 | 76 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/model_zoo.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
import sys
try:
from torch.hub import _download_url_to_file
from torch.hub import urlparse
from torch.hub import HASH_REGEX
except ImportError:
from torch.utils.model_zoo import _download_url_to_file
from torch.utils.... | 2,997 | 47.354839 | 135 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/logger.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import logging
import os
import sys
def setup_logger(name, save_dir, distributed_rank, filename="log.txt"):
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# don't log results for the non-master process
if distribu... | 787 | 29.307692 | 84 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/collect_env.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import PIL
from torch.utils.collect_env import get_pretty_env_info
def get_pil_version():
return "\n Pillow ({})".format(PIL.__version__)
def collect_env_info():
env_str = get_pretty_env_info()
env_str += get_pil_version()
... | 338 | 21.6 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/model_serialization.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from collections import OrderedDict
import logging
import torch
from .imports import import_file
def align_and_update_state_dicts(model_state_dict, loaded_state_dict):
"""
Strategy: suppose that the models that we will create will have ... | 3,683 | 42.857143 | 91 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/cv2_util.py | """
Module for cv2 utility functions and maintaining version compatibility
between 3.x and 4.x
"""
import cv2
def findContours(*args, **kwargs):
"""
Wraps cv2.findContours to maintain compatiblity between versions
3 and 4
Returns:
contours, hierarchy
"""
if cv2.__version__.startswith(... | 640 | 24.64 | 70 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/__init__.py | 0 | 0 | 0 | py | |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/miscellaneous.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import errno
import json
import logging
import os
from .comm import is_main_process
from datetime import datetime
def get_timestamp():
now = datetime.now()
timestamp = datetime.timestamp(now)
st = datetime.fromtimestamp(timestamp).strf... | 1,358 | 28.543478 | 116 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/visualize.py | import cv2
import torch
def select_top_predictions(predictions, confidence_threshold=0.2):
"""
Select only predictions which have a `score` > self.confidence_threshold,
and returns the predictions in descending order of score
Arguments:
predictions (BoxList): the result of the computation by th... | 3,482 | 35.663158 | 103 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/env.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import os
from .imports import import_file
def setup_environment():
"""Perform environment setup work. The default setup is a no-op, but this
function allows the user to specify a Python source file that performs
custom setup work th... | 1,225 | 31.263158 | 90 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/boxes.py | # Copyright (c) 2017-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | 13,683 | 37.985755 | 86 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/utils/imports.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
if torch._six.PY3:
import importlib
import importlib.util
import sys
# from https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path?utm_medium=organic&utm_source=google_rich_qa&utm_campai... | 843 | 34.166667 | 168 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/data/datasets/voc.py | import os
import torch
import torch.utils.data
from PIL import Image
import sys
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
from maskrcnn_benchmark.structures.bounding_box import BoxList
class PascalVOCDataset(torch.utils.data.Dataset):
CL... | 4,168 | 29.654412 | 118 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/data/datasets/concat_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import bisect
from torch.utils.data.dataset import ConcatDataset as _ConcatDataset
class ConcatDataset(_ConcatDataset):
"""
Same as torch.utils.data.dataset.ConcatDataset, but exposes an extra
method for querying the sizes of the ima... | 766 | 30.958333 | 72 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/data/datasets/__init__.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .coco import COCODataset
from .voc import PascalVOCDataset
from .concat_dataset import ConcatDataset
__all__ = ["COCODataset", "ConcatDataset", "PascalVOCDataset"]
| 242 | 33.714286 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/data/datasets/coco.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torchvision
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
from maskrcnn_benchmark.structures.keypoint import PersonKeypoints
min_ke... | 3,783 | 35.038095 | 85 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/data/datasets/list_dataset.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Simple dataset class that wraps a list of path names
"""
from PIL import Image
from maskrcnn_benchmark.structures.bounding_box import BoxList
class ListDataset(object):
def __init__(self, image_lists, transforms=None):
self.imag... | 943 | 24.513514 | 71 | py |
graph-rcnn.pytorch | graph-rcnn.pytorch-master/lib/scene_parser/rcnn/data/datasets/evaluation/__init__.py | from maskrcnn_benchmark.data import datasets
from .coco import coco_evaluation
from .voc import voc_evaluation
def evaluate(dataset, predictions, output_folder, **kwargs):
"""evaluate dataset using different methods based on dataset type.
Args:
dataset: Dataset object
predictions(list[BoxList... | 1,001 | 34.785714 | 87 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.