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 |
|---|---|---|---|---|---|---|
HDN | HDN-master/training_dataset/coco/pycocotools/__init__.py | __author__ = 'tylin'
| 21 | 10 | 20 | py |
HDN | HDN-master/training_dataset/coco/pycocotools/coco.py | __author__ = 'tylin'
__version__ = '2.0'
# Interface for accessing the Microsoft COCO dataset.
# Microsoft COCO is a large image dataset designed for object detection,
# segmentation, and caption generation. pycocotools is a Python API that
# assists in loading, parsing and visualizing the annotations in COCO.
# Pleas... | 18,476 | 40.993182 | 128 | py |
HDN | HDN-master/training_dataset/coco/pycocotools/mask.py | __author__ = 'tsungyi'
#import pycocotools._mask as _mask
from . import _mask
# Interface for manipulating masks stored in RLE format.
#
# RLE is a simple yet efficient format for storing binary masks. RLE
# first divides a vector (or vectorized image) into a series of piecewise
# constant regions and then for each p... | 4,613 | 42.942857 | 100 | py |
HDN | HDN-master/training_dataset/vid/gen_json.py | from os.path import join
from os import listdir
import json
import numpy as np
print('load json (raw vid info), please wait 20 seconds~')
vid = json.load(open('vid.json', 'r'))
def check_size(frame_sz, bbox):
min_ratio = 0.1
max_ratio = 0.75
# only accept objects >10% and <75% of the total frame
area... | 3,320 | 35.9 | 94 | py |
HDN | HDN-master/training_dataset/vid/parse_vid.py | from os.path import join
from os import listdir
import json
import glob
import xml.etree.ElementTree as ET
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
img_base_path = join(VID_base_path, 'Data/VID/train/')
sub_sets = sorted({'a', 'b', 'c', 'd', 'e'})
vid = []
for sub_s... | 2,001 | 37.5 | 90 | py |
HDN | HDN-master/training_dataset/vid/par_crop.py | from os.path import join, isdir
from os import listdir, mkdir, makedirs
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
from concurrent import futures
import sys
import time
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
sub_sets = sorted({'a',... | 4,948 | 40.588235 | 112 | py |
HDN | HDN-master/training_dataset/vid/visual.py | from os.path import join
from os import listdir
import cv2
import numpy as np
import glob
import xml.etree.ElementTree as ET
visual = True
color_bar = np.random.randint(0, 255, (90, 3))
VID_base_path = './ILSVRC2015'
ann_base_path = join(VID_base_path, 'Annotations/VID/train/')
img_base_path = join(VID_base_path, 'Da... | 1,755 | 38.022222 | 90 | py |
HDN | HDN-master/homo_estimator/__init__.py | 0 | 0 | 0 | py | |
HDN | HDN-master/homo_estimator/Deep_homography/__init__.py | 0 | 0 | 0 | py | |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/resnet.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch, imageio
from homo_estimator.Deep_homography.Oneline_DLTv1.utils import transform, DLT_solve
import matplotlib.pyplot as plt
criterion_l2 = nn.MSELoss(reduce=True, size_average=True)
triplet_loss = nn.TripletMarginLoss(margin=1.0, p=1, reduce=... | 16,688 | 36.672686 | 118 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/utils.py | import torch
import numpy as np
import cv2
import subprocess
import psutil
def DLT_solve(src_p, off_set):
# src_p: shape=(bs, n, 4, 2)
# off_set: shape=(bs, n, 4, 2)
# can be used to compute mesh points (multi-H)
bs, _ = src_p.shape
divide = int(np.sqrt(len(src_p[0])/2)-1)
row_num = (divide+1)*... | 12,962 | 33.293651 | 136 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/dataset.py | from torch.utils.data import Dataset
import numpy as np
import cv2, torch
import os
"""
Train_dataset+test_dataset. [Deep_Homography](https://github.com/JirongZhang/DeepHomography)provided dataset,
for training two homography estimation for two images we do not use this
"""
def make_mesh(patch_w,patch_h):
x_flat... | 6,550 | 36.221591 | 115 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/__init__.py | 0 | 0 | 0 | py | |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/backbone/resnet.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch, imageio
# from utils import transform, DLT_solve
import matplotlib.pyplot as plt
"""
homo-estimator's backbone, reconstruction of the original Deephomography
"""
criterion_l2 = nn.MSELoss(reduce=True, size_average=True)
triplet_loss = nn.T... | 8,165 | 30.774319 | 115 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/backbone/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from torch import nn
import homo_estimator.Deep_homography.Oneline_DLTv1.backbone.resnet as resnet
import torch.utils.model_zoo as model_zoo
# from test_ideas.net.unet imp... | 2,249 | 38.473684 | 93 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/tools/get_img_info.py | # coding: utf-8
import argparse
from homo_estimator.Deep_homography.Oneline_DLTv1.dataset import *
import numpy as np
"""
In order to get template and search images info as input of homo-estiamtor network.
"""
def get_template_info(template):
"""
In order to preserve time, we separate the procedure of obtaining... | 6,470 | 36.842105 | 104 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/models/homo_model_builder.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import torch.nn as nn
import torch.nn.functional as F
import imageio
from hdn.core.config import cfg
from homo_estimator.Deep_homography.Oneline_DLTv1.backbone import get... | 8,336 | 37.243119 | 118 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/preprocess/__init__.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
# from hdn.models.head.ban import UPChannelBAN, DepthwiseBAN, MultiBAN
# from hdn.models.head.ban_lp import DepthwiseCircBAN, MultiCircBAN
# from homo_estimator.Deep_homo... | 978 | 33.964286 | 108 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/preprocess/input_mask_generator.py | import torch.nn as nn
class MaskGenerator(nn.Module):
def __init__(self, ):
super(MaskGenerator, self).__init__()
self.genMask = nn.Sequential(
nn.Conv2d(1, 4, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(4),
nn.ReLU(inplace=True),
nn.Conv2d... | 1,164 | 30.486486 | 68 | py |
HDN | HDN-master/homo_estimator/Deep_homography/Oneline_DLTv1/preprocess/input_feature_extractor.py | import torch.nn as nn
class PreShareFeature(nn.Module):
def __init__(self, ):
super(PreShareFeature, self).__init__()
self.ShareFeature = nn.Sequential(
nn.Conv2d(1, 4, kernel_size=3, padding=1, bias=False),
nn.BatchNorm2d(4),
nn.ReLU(inplace=True),
... | 982 | 29.71875 | 66 | py |
SIGIR2021 | SIGIR2021-master/src/test.py | import os
import random
from argparse import ArgumentParser
from multiprocessing import Pool
from src.parameters import DEFAULT_DATA_DIR, DEVICE
from src.utils import print_message, create_directory
from src.evaluation.loaders import load_colbert, load_topK, load_qrels
from src.evaluation.ranking import evaluate
fro... | 2,412 | 36.703125 | 118 | py |
SIGIR2021 | SIGIR2021-master/src/utils2.py | import string
STOPLIST = ["a", "about", "also", "am", "an", "and", "another", "any", "anyone", "are", "aren't", "as", "at", "be",
"been", "being", "but", "by", "despite", "did", "didn't", "do", "does", "doesn't", "doing", "done", "don't",
"each", "etc", "every", "everyone", "for", "from", "furt... | 4,155 | 46.770115 | 120 | py |
SIGIR2021 | SIGIR2021-master/src/utils.py | import os
import torch
import datetime
def print_message(*s):
s = ' '.join([str(x) for x in s])
print("[{}] {}".format(datetime.datetime.utcnow().strftime("%b %d, %H:%M:%S"), s), flush=True)
def save_checkpoint(path, epoch_idx, mb_idx, model, optimizer):
print("#> Saving a checkpoint..")
checkpoint... | 1,309 | 24.686275 | 98 | py |
SIGIR2021 | SIGIR2021-master/src/model.py | import torch
import torch.nn as nn
from nltk.stem import PorterStemmer
from random import sample, shuffle, randint
from itertools import accumulate
from transformers import *
import re
from src.parameters import DEVICE
from src.utils2 import cleanQ, cleanD
stem = PorterStemmer().stem
MAX_LENGTH = 300
def unique(s... | 6,377 | 37.421687 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/model_multibert.py | import torch
import torch.nn as nn
from nltk.stem import PorterStemmer
from random import sample, shuffle, randint
from transformers import *
import re
from itertools import accumulate
from src.parameters import DEVICE
from src.utils2 import cleanQ, cleanD
stem = PorterStemmer().stem
MAX_LENGTH = 300
def unique(seq... | 4,114 | 38.951456 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/retrieve.py | # To be released soon. | 22 | 22 | 22 | py |
SIGIR2021 | SIGIR2021-master/src/parameters.py | import torch
DEVICE = torch.device("cuda:0")
DEFAULT_DATA_DIR = './data_download/'
SAVED_CHECKPOINTS = [32*1000, 100*1000, 150*1000, 200*1000, 300*1000, 400*1000]
| 166 | 19.875 | 79 | py |
SIGIR2021 | SIGIR2021-master/src/__init__.py | 0 | 0 | 0 | py | |
SIGIR2021 | SIGIR2021-master/src/rerank.py | import os
import random
from argparse import ArgumentParser
from src.parameters import DEFAULT_DATA_DIR, DEVICE
from src.utils import print_message, create_directory
from src.evaluation.loaders import load_colbert, load_topK, load_qrels
from src.indexing.loaders import load_document_encodings
from src.evaluation.ran... | 2,391 | 36.375 | 117 | py |
SIGIR2021 | SIGIR2021-master/src/train.py | import os
import random
import torch
from argparse import ArgumentParser
from src.training.data_reader import train
from src.utils import print_message, create_directory
def main():
random.seed(12345)
torch.manual_seed(1)
parser = ArgumentParser(description='Training ColBERT with <query, positive passa... | 1,761 | 34.959184 | 128 | py |
SIGIR2021 | SIGIR2021-master/src/index.py | import random
import datetime
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from time import time
from math import ceil
from src.model_multibert import *
from multiprocessing import Pool
from src.evaluation.loaders import load_checkpoint
MB_SIZE = 1024
def print_message(*s):
s... | 3,047 | 29.787879 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/evaluation/loaders.py | from src.parameters import DEVICE
from src.model import MultiBERT
from src.utils import print_message, load_checkpoint
def load_qrels(qrels_path):
if qrels_path is None:
return None
print_message("#> Loading qrels from", qrels_path, "...")
qrels = {}
with open(qrels_path, mode='r', encoding=... | 2,112 | 29.623188 | 89 | py |
SIGIR2021 | SIGIR2021-master/src/evaluation/metrics.py | class Metrics:
def __init__(self, mrr_depths: dict, recall_depths: dict, total_queries=None):
self.results = {}
self.mrr_sums = {depth: 0.0 for depth in mrr_depths}
self.recall_sums = {depth: 0.0 for depth in recall_depths}
self.total_queries = total_queries
def add(self, query_... | 1,868 | 39.630435 | 114 | py |
SIGIR2021 | SIGIR2021-master/src/evaluation/__init__.py | 0 | 0 | 0 | py | |
SIGIR2021 | SIGIR2021-master/src/evaluation/ranking.py | import os
import random
import time
import torch
from src.utils import print_message, load_checkpoint, batch
from src.evaluation.metrics import Metrics
def rerank(args, query, pids, passages, index=None):
colbert = args.colbert
#tokenized_passages = list(args.pool.map(colbert.tokenizer.tokenize, passages))
... | 2,777 | 38.126761 | 116 | py |
SIGIR2021 | SIGIR2021-master/src/training/data_reader.py | import os
import random
import torch
import torch.nn as nn
from argparse import ArgumentParser
from transformers import AdamW
from src.parameters import DEVICE, SAVED_CHECKPOINTS
from src.model import MultiBERT
from src.utils import print_message, save_checkpoint
import re
import datetime
class TrainReader:
def ... | 2,567 | 31.923077 | 119 | py |
SIGIR2021 | SIGIR2021-master/src/training/__init__.py | 0 | 0 | 0 | py | |
pessto | pessto-master/Ptkplot.py | import os
from tkinter import _default_root
from tkinter import TclError, Canvas
from . import wutil
# XBM file for cursor is in same directory as this module
_blankcursor = 'blankcursor.xbm'
dirname = os.path.dirname(__file__)
if os.path.isabs(dirname):
_blankcursor = os.path.join(dirname, _blankcursor)
else:
... | 10,581 | 31.863354 | 79 | py |
pessto | pessto-master/fix_cursor_macos.py | import os
import shutil
import requests
# importing pyraf might fail due to a pickle protocol issue
# this is solved with fix_pickle_macos.py
import pyraf
pyraf_path = pyraf.__path__[0]
# ---------------------------
# this fixes the cursor issue
fixed_file_url = 'https://raw.githubusercontent.com/svalenti/pessto/maste... | 569 | 27.5 | 86 | py |
pessto | pessto-master/fix_pickle_macos.py | import os
import importlib
init_file = importlib.util.find_spec("pyraf")
pyraf_path = os.path.dirname(init_file.origin)
# -------------------
# this fixes the pickle protocol issue
file2fix = os.path.join(pyraf_path, 'sqliteshelve.py')
# read the file and add the fix
with open(file2fix, "rt") as file:
data = file... | 575 | 29.315789 | 68 | py |
pessto | pessto-master/trunk/setup.py | from setuptools import setup, find_packages
from distutils.command.install import INSTALL_SCHEMES
from os import sys, path
import os
import shutil
import re
from glob import glob
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
from imp import find_module
try:
find_module('numpy')
ex... | 2,779 | 32.493976 | 125 | py |
pessto | pessto-master/trunk/passtobin/fillexel.py | #!/usr/bin/env python
import os
import sys
import string
import re
import glob
import ntt
from pyfits import open as popen
from ntt.util import readkey3, readhdr, readspectrum, delete
import datetime
import time
from optparse import OptionParser
description = "> filling exelfile "
usage = "%prog \t listframes [option... | 3,373 | 35.673913 | 133 | py |
pessto | pessto-master/trunk/passtobin/testheaderlist.py | #!/usr/bin/env python
import os,sys,string,re,glob
import ntt
from pyfits import open as popen
from ntt.util import readkey3, readhdr, readspectrum, delete, correctcard
import datetime
import time
keyword={}
keyword['efosc']={}
keyword['sofi']={}
keyword['efosc']['image']={'ABMAGLIM':'R','ABMAGSAT':'R','PSF_FWHM':'R'... | 5,256 | 52.642857 | 141 | py |
pessto | pessto-master/trunk/src/ntt/sofispec1Ddef.py |
def findaperture(img, _interactive=False):
# print "LOGX:: Entering `findaperture` method/function in %(__file__)s" %
# globals()
import re
import string
import os
from pyraf import iraf
import ntt
iraf.noao(_doprint=0, Stdout=0)
iraf.imred(_doprint=0, Stdout=0)
iraf.specred(_do... | 37,542 | 51.877465 | 137 | py |
pessto | pessto-master/trunk/src/ntt/sofiphotredudef.py | def pesstocombine(imglist, _combine, _rejection, outputimage):
# print "LOGX:: Entering `pesstocombine` method/function in %(__file__)s"
# % globals()
import ntt
from pyraf import iraf
from numpy import compress, array, round, median, std, isnan, sqrt, argmin, argsort
import string
import os... | 64,227 | 46.191771 | 139 | py |
pessto | pessto-master/trunk/src/ntt/_version.py | __version__ = "3.0.1"
| 22 | 10.5 | 21 | py |
pessto | pessto-master/trunk/src/ntt/cosmics.py | # cosmic correction
# lacosmic iraf modules rewritten in pyraf
#
#
import os
import numpy as np
import math
try: from astropy.io import fits as pyfits
except: import pyfits
# We define the laplacian kernel to be used
laplkernel = np.array([[0.0, -1.0, 0.0], [-1.0, 4.0, -1.0], [0.0, -1.0, 0.0]])
# Other k... | 20,057 | 39.851324 | 191 | py |
pessto | pessto-master/trunk/src/ntt/sqlcl.py | #!/usr/bin/python2
""">> sqlcl << command line query tool by Tamas Budavari <budavari@jhu.edu>
Usage: sqlcl [options] sqlfile(s)
Options:
-s url : URL with the ASP interface (default: pha)
-f fmt : set output format (html,xml,csv - default: csv)
-q query : specify query on the command ... | 3,706 | 27.083333 | 78 | py |
pessto | pessto-master/trunk/src/ntt/util.py | try: from astropy.io import fits as pyfits
except: import pyfits
def ReadAscii2(ascifile):
import string
f = open(ascifile, 'r')
ss = f.readlines()
f.close()
vec1, vec2 = [], []
for line in ss:
if line[0] != '#':
vec1.append(float(line.split()[0]))
vec2.... | 51,054 | 34.603208 | 144 | py |
pessto | pessto-master/trunk/src/ntt/efoscfastspecdef.py |
def efoscfastredu(imglist, _listsens, _listarc, _ext_trace, _dispersionline, _cosmic, _interactive):
# print "LOGX:: Entering `efoscfastredu` method/function in %(__file__)s"
# % globals()
import string
import os
import re
import sys
os.environ["PYRAF_BETA_STATUS"] = "1"
try: from ... | 11,404 | 49.915179 | 119 | py |
pessto | pessto-master/trunk/src/ntt/soficalibdef.py | def makeflat(lista):
# print "LOGX:: Entering `makeflat` method/function in %(__file__)s" %
# globals()
flat = ''
import datetime
import glob
import os
import ntt
from ntt.util import readhdr, readkey3, delete, name_duplicate, updateheader, correctcard
from pyraf import iraf
iraf... | 18,793 | 46.821883 | 160 | py |
pessto | pessto-master/trunk/src/ntt/efoscspec2Ddef.py | def aperture(img):
from astropy.io import fits as pyfits
import re
import os
hdr = pyfits.open(img)[0].header
xmax = hdr['NAXIS1']
center = float(xmax) / 2.
xmin = -500
img2 = re.sub('.fits', '', img)
line = "# Sun 13:10:40 16-Jun-2013\nbegin aperture " + img2 + " 1 " + str(center)... | 52,209 | 49.444444 | 122 | py |
pessto | pessto-master/trunk/src/ntt/__init__.py | from .util import *
from .efoscphotredudef import *
from .efoscfastspecdef import *
from .sofiphotredudef import *
from .efoscspec1Ddef import *
from .efoscspec2Ddef import *
from .sofispec1Ddef import *
from .sofispec2Ddef import *
from .efoscastrodef import *
from .sqlcl import *
from .efosccalibdef import *
from .so... | 559 | 25.666667 | 100 | py |
pessto | pessto-master/trunk/src/ntt/efosccalibdef.py | def makefringingmask(listimg, _output, _interactive, _combine='average', _rejection='avsigclip'):
# print "LOGX:: Entering `makefringingmask` method/function in
# %(__file__)s" % globals()
import ntt
from ntt.util import readhdr, readkey3, delete, updateheader
import glob
import os
import sy... | 6,555 | 39.469136 | 135 | py |
pessto | pessto-master/trunk/src/ntt/sofispec2Ddef.py | def skysofifrom2d(fitsfile, skyfile):
# print "LOGX:: Entering `skysofifrom2d` method/function in %(__file__)s"
# % globals()
import ntt
from ntt.util import readhdr, readkey3, delete
from numpy import mean, arange, compress
try:
from astropy.io import fits as pyfits
except:
... | 43,947 | 51.07109 | 137 | py |
pessto | pessto-master/trunk/src/ntt/efoscspec1Ddef.py | def telluric_atmo(imgstd):
import numpy as np
import ntt
from pyraf import iraf
try: import pyfits
except: from astropy.io import fits as pyfits
iraf.images(_doprint=0, Stdout=0)
iraf.noao(_doprint=0, Stdout=0)
iraf.twodspec(_doprint=0, Stdout=0)
iraf.longslit(_doprint=... | 33,012 | 45.043236 | 126 | py |
pessto | pessto-master/trunk/src/ntt/efoscastrodef.py | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('TKAgg')
def xpa(arg):
# print "LOGX:: Entering `xpa` method/function in %(__file__)s" % globals()
import subprocess
subproc = subprocess.Popen('xpaset -p ds9 ' + arg, shell=True)
subproc.communicate()
def vizq(_ra, ... | 84,518 | 42.792228 | 138 | py |
pessto | pessto-master/trunk/src/ntt/efoscphotredudef.py | try:
from astropy.io import fits as pyfits
except:
import pyfits
def efoscreduction(imglist, _interactive, _doflat, _dobias, listflat, listbias, _dobadpixel, badpixelmask,
fringingmask, _archive, typefile, filenameobjects, _system, _cosmic, _verbose=False, method='iraf'):
# print "LOGX:... | 46,690 | 46.40203 | 132 | py |
LoGo | LoGo-main/main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import os
import sys
import json
import random
import copy
import pickle
import numpy as np
import pandas as pd
import medmnist
from medmnist import INFO
import torch
import torch.nn.functional as F
from torchvision import datasets, transforms
from ... | 10,805 | 47.457399 | 148 | py |
LoGo | LoGo-main/models/resnet.py | import torch
import torch.nn as nn
__all__ = ['resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'wide_resnet50_2', 'wide_resnet101_2']
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out... | 9,005 | 37.323404 | 109 | py |
LoGo | LoGo-main/models/__init__.py | from .cnn4conv import CNN4Conv
from .mobilenet import MobileNetCifar
from .resnet import *
def get_model(args):
if args.model == 'cnn4conv':
net_glob = CNN4Conv(in_channels=args.in_channels, num_classes=args.num_classes, args=args).to(args.device)
elif args.model == 'mobilenet':
net_gl... | 788 | 40.526316 | 114 | py |
LoGo | LoGo-main/models/mobilenet.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import torch
from torch import nn
import torch.nn.functional as F
'''MobileNet in PyTorch.
See the paper "MobileNets: Efficient Convolutional Neural Networks for Mobile Vision Applications"
for more details.
'''
class Block(nn.Module):
'''Depth... | 2,277 | 35.15873 | 123 | py |
LoGo | LoGo-main/models/cnn4conv.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import torch
from torch import nn
def conv3x3(in_channels, out_channels, **kwargs):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1, **kwargs),
nn.BatchNorm2d(out_channels, track_running_stats=... | 1,416 | 27.34 | 81 | py |
LoGo | LoGo-main/util/longtail_dataset.py | import numpy as np
from PIL import Image
from torchvision import datasets, transforms
class IMBALANCECIFAR10(datasets.CIFAR10):
cls_num = 10
def __init__(self, phase, imbalance_ratio, root='data/cifar10_lt/', imb_type='exp', train_aug=True):
train = True if phase == 'train' else False
super(... | 4,753 | 34.214815 | 113 | py |
LoGo | LoGo-main/util/args.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import argparse
import medmnist
from medmnist import INFO
def args_parser():
parser = argparse.ArgumentParser()
# basic arguments
parser.add_argument('--gpu', type=int, default=0, help="GPU ID, -1 for CPU")
parser.add_argument('-... | 6,210 | 45.350746 | 112 | py |
LoGo | LoGo-main/util/misc.py | import numpy as np
from torch.utils.data import Dataset
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(self):
return len(self.idxs)
def __getitem__(self, item):
image, label = self.dataset[self.id... | 696 | 21.483871 | 52 | py |
LoGo | LoGo-main/util/path.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import os
import pickle
import numpy as np
def set_result_dir(args):
dataset = args.dataset if 'lt' not in args.dataset else args.dataset + '_{}'.format(args.imb_ratio)
if "shard" in args.partition:
args.result_dir = '{}... | 3,559 | 31.962963 | 137 | py |
LoGo | LoGo-main/util/__init__.py | from .args import *
from .path import *
from .data_simulator import *
from .longtail_dataset import *
from .misc import * | 121 | 23.4 | 31 | py |
LoGo | LoGo-main/util/data_simulator.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Python version: 3.9
import os
import math
import pickle
import random
import numpy as np
import torch
def shard_balance(dataset, args):
K = args.num_classes
y_train_dict = {i: [] for i in range(K)}
for idx, d in enumerate(dataset):
if args.dat... | 6,082 | 34.782353 | 119 | py |
LoGo | LoGo-main/fl_methods/base.py | import copy
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from util.misc import DatasetSplit
class FederatedLearning:
def __init__(self, args, dict_users_train_label=None):
self.args = args
self.dict_users_train_label = dict_users_train_label
self.loss_func =... | 2,247 | 32.058824 | 115 | py |
LoGo | LoGo-main/fl_methods/__init__.py | from .fedavg import FedAvg
from .fedprox import FedProx
from .scaffold import SCAFFOLD
_method_class_map = {
'fedavg': FedAvg,
'fedprox': FedProx,
'scaffold': SCAFFOLD
}
def get_fl_method_class(key):
if key in _method_class_map:
return _method_class_map[key]
else:
raise ValueError... | 355 | 19.941176 | 58 | py |
LoGo | LoGo-main/fl_methods/fedprox.py | import copy
import torch
from .base import FederatedLearning
class FedProx(FederatedLearning):
def __init__(self, args, dict_users_train_label=None):
super().__init__(args, dict_users_train_label)
def train(self, net, user_idx=None, lr=0.01, momentum=0.9, weight_decay=0.00001):
net.train()
... | 1,709 | 33.897959 | 109 | py |
LoGo | LoGo-main/fl_methods/fedavg.py | import torch
from .base import FederatedLearning
class FedAvg(FederatedLearning):
def __init__(self, args, dict_users_train_label=None):
super().__init__(args, dict_users_train_label)
def train(self, net, user_idx=None, lr=0.01, momentum=0.9, weight_decay=0.00001):
net.train()
# tra... | 1,393 | 33.85 | 109 | py |
LoGo | LoGo-main/fl_methods/scaffold.py | import copy
import torch
from .base import FederatedLearning
class SCAFFOLD(FederatedLearning):
def __init__(self, args, dict_users_train_label=None):
super().__init__(args, dict_users_train_label)
def init_c_nets(self, net_glob):
self.c_nets = {}
for i in range(self.args.num_users)... | 3,530 | 37.380435 | 132 | py |
LoGo | LoGo-main/query_strategies/least_confidence.py | import copy
import numpy as np
from .strategy import Strategy
class LeastConfidence(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
if self.args.query_model_mode == "global":
probs = self.predict_prob(unlabel_... | 604 | 32.611111 | 69 | py |
LoGo | LoGo-main/query_strategies/margin_sampling.py | import copy
import numpy as np
import torch
import torch.nn as nn
from .strategy import Strategy
class MarginSampling(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
if self.args.query_model_mode == "global":
... | 753 | 26.925926 | 69 | py |
LoGo | LoGo-main/query_strategies/dbal.py | import copy
import numpy as np
from tqdm import tqdm
from sklearn.cluster import KMeans
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from .strategy import Strategy
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
... | 1,679 | 30.111111 | 90 | py |
LoGo | LoGo-main/query_strategies/alfa_mix.py | import copy
import math
import numpy as np
from select import select
from sklearn.cluster import KMeans
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from torch.autograd import Variable
from .strategy import Strategy, DatasetSplit
class ALFAMix(Strategy):
def __in... | 10,525 | 39.484615 | 151 | py |
LoGo | LoGo-main/query_strategies/core_set.py | import copy
import numpy as np
from sklearn.metrics import pairwise_distances
from .strategy import Strategy
class CoreSet(Strategy):
def furthest_first(self, X, X_set, n):
m = np.shape(X)[0]
if np.shape(X_set)[0] == 0:
min_dist = np.tile(float("inf"), m)
else:
dis... | 1,430 | 31.522727 | 113 | py |
LoGo | LoGo-main/query_strategies/egl.py | import copy
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
from .strategy import Strategy
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(self):
return l... | 1,812 | 31.963636 | 94 | py |
LoGo | LoGo-main/query_strategies/badge_sampling.py | import pdb
import copy
import numpy as np
from scipy import stats
from sklearn.metrics import pairwise_distances
from .strategy import Strategy
# kmeans ++ initialization
def init_centers(X, K):
ind = np.argmax([np.linalg.norm(s, 2) for s in X])
mu = [X[ind]]
indsAll = [ind]
centInds = [0.] * len(X)
... | 1,829 | 32.888889 | 88 | py |
LoGo | LoGo-main/query_strategies/entropy_sampling.py | import copy
import numpy as np
import torch
from .strategy import Strategy
class EntropySampling(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
if self.args.query_model_mode == "global":
probs = self.predict... | 766 | 28.5 | 69 | py |
LoGo | LoGo-main/query_strategies/strategy.py | import copy
import numpy as np
from copy import deepcopy
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data import DataLoader, Dataset
class DatasetSplit(Dataset):
def __init__(self... | 6,979 | 36.326203 | 123 | py |
LoGo | LoGo-main/query_strategies/gcnal.py | import math
import numpy as np
from tqdm import tqdm
from sklearn.metrics import pairwise_distances
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.utils.data import Dataset
from torch.nn.parameter import Parameter
from .strategy import Strategy
class GCNAL(... | 6,451 | 31.918367 | 117 | py |
LoGo | LoGo-main/query_strategies/__init__.py | import os
import sys
import copy
import pickle
import random
import datetime
import numpy as np
import torch
from models import get_model
from .random_sampling import RandomSampling
from .least_confidence import LeastConfidence
from .margin_sampling import MarginSampling
from .entropy_sampling import EntropySampling
... | 5,878 | 40.695035 | 149 | py |
LoGo | LoGo-main/query_strategies/adversial_deepfool.py | import copy
import numpy as np
from tqdm import tqdm
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset
from .strategy import Strategy
class DatasetSplit(Dataset):
def __init__(self, dataset, idxs):
self.dataset = dataset
self.idxs = list(idxs)
def __len__(sel... | 2,570 | 27.566667 | 90 | py |
LoGo | LoGo-main/query_strategies/random_sampling.py | import random
from .strategy import Strategy
class RandomSampling(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
return random.sample(unlabel_idxs, n_query) | 201 | 24.25 | 69 | py |
LoGo | LoGo-main/query_strategies/fal/ensemble_logit.py | import pdb
import copy
import numpy as np
from scipy import stats
from sklearn.metrics import pairwise_distances
import torch
from ..strategy import Strategy
class EnsLogitConf(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
... | 4,828 | 30.769737 | 113 | py |
LoGo | LoGo-main/query_strategies/fal/logo.py | import copy
import math
import numpy as np
from copy import deepcopy
from sklearn.cluster import KMeans
import torch
import torch.nn as nn
from ..strategy import Strategy
class LoGo(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(unlabel_idxs)
... | 3,718 | 37.340206 | 101 | py |
LoGo | LoGo-main/query_strategies/fal/__init__.py | from .ensemble_logit import EnsLogitEntropy, EnsLogitBadge
from .ensemble_rank import EnsRankEntropy, EnsRankBadge
from .finetuning import FTEntropy, FTBadge
from .logo import LoGo | 180 | 44.25 | 58 | py |
LoGo | LoGo-main/query_strategies/fal/ensemble_rank.py | import pdb
import copy
import numpy as np
from enum import unique
from scipy import stats
from sklearn.metrics import pairwise_distances
import torch
from ..strategy import Strategy
class EnsRankEntropy(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unlabel_idxs = np.array(... | 3,720 | 32.522523 | 117 | py |
LoGo | LoGo-main/query_strategies/fal/finetuning.py | import pdb
import copy
import numpy as np
from enum import unique
from scipy import stats
from copy import deepcopy
from sklearn.metrics import pairwise_distances
import torch
from ..strategy import Strategy
class FTEntropy(Strategy):
def query(self, user_idx, label_idxs, unlabel_idxs, n_query=100):
unl... | 2,217 | 30.239437 | 88 | py |
castor | castor-main/castor/runner.py | import comet_ml # noqa
import hydra
from omegaconf import DictConfig
from vital.runner import VitalRunner
class CastorRunner(VitalRunner):
"""Entry-point for a `VitalRunner` that adds the `castor` config dir to the Hydra search path."""
@staticmethod
@hydra.main(version_base=None, config_path="config", ... | 548 | 22.869565 | 101 | py |
castor | castor-main/castor/__init__.py | 0 | 0 | 0 | py | |
castor | castor-main/castor/config/__init__.py | 0 | 0 | 0 | py | |
castor | castor-main/castor/config/experiment/__init__.py | 0 | 0 | 0 | py | |
castor | castor-main/castor/results/__init__.py | 0 | 0 | 0 | py | |
castor | castor-main/castor/results/camus/image_temporal_metrics.py | from vital import get_vital_root
from castor.results.camus.utils.image_attributes import ImageAttributesMixin
from castor.results.camus.utils.temporal_metrics import TemporalMetrics
class ImageTemporalMetrics(ImageAttributesMixin, TemporalMetrics):
"""Class that computes temporal coherence metrics on sequences o... | 609 | 28.047619 | 103 | py |
castor | castor-main/castor/results/camus/segmentation_metrics_plots.py | import logging
from argparse import ArgumentParser
from pathlib import Path
from typing import Mapping, Sequence, Tuple
import medpy.metric as metric
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
from seaborn import JointGrid
from vital.data.camus.config import Camus... | 11,131 | 45.577406 | 120 | py |
castor | castor-main/castor/results/camus/__init__.py | 0 | 0 | 0 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.