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 |
|---|---|---|---|---|---|---|
EIGNN | EIGNN-main/layers.py | import math
import numpy as np
import torch
import torch.sparse
import torch.nn as nn
from torch.nn import Parameter
from torch.nn import Module
import scipy
import scipy.sparse as sp
import torch.nn.functional as F
from torch.autograd import Function
from utils import projection_norm_inf, projection_norm_inf_and_1, S... | 3,464 | 35.09375 | 115 | py |
EIGNN | EIGNN-main/normalization.py | import numpy as np
import scipy.sparse as sp
import torch
def aug_normalized_adjacency(adj, need_orig=False):
if not need_orig:
adj = adj + sp.eye(adj.shape[0])
adj = sp.coo_matrix(adj)
row_sum = np.array(adj.sum(1))
d_inv_sqrt = np.power(row_sum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] ... | 907 | 29.266667 | 94 | py |
EIGNN | EIGNN-main/eval_EIGNN_heterophilic.py | from __future__ import division
from __future__ import print_function
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import time
import argparse
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import ipdb
from utils import accuracy... | 5,273 | 35.881119 | 117 | py |
coyo-dataset | coyo-dataset-main/examples/webdataset_tf.py | import webdataset as wds
import torch
from torchvision import transforms
def identity(x):
return x
class tf_webdataset:
def __init__(self, batch_size):
# num of your tar files
url = "/COYO-700M/{000000..008191}.tar"
preproc = transforms.Compose([
transforms.ToTenso... | 1,573 | 23.59375 | 110 | py |
coyo-dataset | coyo-dataset-main/examples/webdataset_torch.py | import webdataset as wds
import torch
from torchvision import transforms
def identity(x):
return x
def dataloader_test():
# num of your tar files
url = "/COYO-700M/{000000..008191}.tar"
preproc = transforms.Compose([
transforms.ToTensor(),
transforms.Resize(384),
transforms.Cen... | 866 | 19.162791 | 62 | py |
MIRTorch | MIRTorch-master/setup.py | from setuptools import setup, find_packages
REQUIRED_PACKAGES = ['torch >= 1.13',
'numpy',
'scipy',
'torchvision>=0.8',
'dominate>=2.5.1',
'torchkbnufft >= 1.4.0',
'scipy>=1.6.0',
... | 1,525 | 32.911111 | 98 | py |
MIRTorch | MIRTorch-master/tests/spect_tests.py | # spect_tests.py
"""
Adjoint tests for SPECT forward-backward projector
Author: Zongyu Li, zonyul@umich.edu
"""
import unittest
import sys, os
path = os.path.dirname(os.path.abspath(__file__))
path = path[:path.rfind('/')]
sys.path.insert(0, path)
from mirtorch.linear.spect import SPECT
import torch
import numpy as np... | 1,457 | 26.509434 | 73 | py |
MIRTorch | MIRTorch-master/tests/prox_tests.py | import unittest
import sys, os
path = os.path.dirname(os.path.abspath(__file__))
path = path[:path.rfind('/')]
sys.path.insert(0, path)
import torch
import numpy as np
import numpy.testing as npt
import mirtorch
class TestProx(unittest.TestCase):
def test_l1(self):
lambd = np.random.random()
pro... | 4,816 | 35.492424 | 77 | py |
MIRTorch | MIRTorch-master/tests/basics_tests.py | import unittest
import sys, os
path = os.path.dirname(os.path.abspath(__file__))
path = path[:path.rfind('/')]
sys.path.insert(0, path)
from mirtorch.linear import basics
from mirtorch.linear import wavelets
import torch
import torch.nn.functional as F
from .utils import conv1D, conv2D
class TestBasic(unittest.TestC... | 8,616 | 37.297778 | 119 | py |
MIRTorch | MIRTorch-master/docs/conf.py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... | 2,134 | 36.45614 | 121 | py |
MIRTorch | MIRTorch-master/mirtorch/__init__.py | from mirtorch import prox
from mirtorch import linear
from mirtorch import alg
from mirtorch import dic
__all__ = ['linear', 'prox', 'alg', 'dic']
| 148 | 20.285714 | 42 | py |
MIRTorch | MIRTorch-master/mirtorch/alg/cg.py | import torch
class CG_func(torch.autograd.Function):
@staticmethod
def forward(ctx, b, A, max_iter, tol, alert, x0, eval_func, P):
ctx.save_for_backward(b)
ctx.A = A
ctx.max_iter = max_iter
ctx.tol = tol
ctx.alert = alert
ctx.eval_func = eval_func
ctx.P ... | 4,083 | 31.15748 | 135 | py |
MIRTorch | MIRTorch-master/mirtorch/alg/pogm.py | import numpy as np
from typing import Callable
import torch
from mirtorch.prox import Prox
class POGM():
r"""
Optimized Proximal Gradient Method (POGM)
Ref: D. Kim and J. A. Fessler. “Adaptive restart of the optimized gradient method for convex optimization”.
In: J. Optim. Theory Appl. 178.1 (July 20... | 2,837 | 30.533333 | 111 | py |
MIRTorch | MIRTorch-master/mirtorch/alg/fista.py | from mirtorch.prox import Prox
import numpy as np
import torch
from typing import Callable
class FISTA():
r"""
Fast Iterative Soft Thresholding Algorithm (FISTA) / Fast Proximal Gradient Method (FPGM)
.. math::
arg \min_x f(x) + g(x)
where grad(f(x)) is L-Lipschitz continuous and g is proxim... | 2,327 | 28.846154 | 93 | py |
MIRTorch | MIRTorch-master/mirtorch/alg/spectral.py | import torch
@torch.no_grad()
def power_iter(A, x0, max_iter=100, tol=1e-6, alert=True):
r"""
Use power iteration to calculate the spectral norm of a LinearMap.
Args:
A: a LinearMap
max_iter: maximum number of iterations
tol: stopping tolerance
x0: i... | 1,042 | 29.676471 | 106 | py |
MIRTorch | MIRTorch-master/mirtorch/alg/fbpd.py | import numpy as np
from typing import Callable
import torch
from mirtorch.prox import Prox, Conj
from mirtorch.linear import LinearMap
class FBPD():
r"""Forward-backward primal dual (FBPD) algorithm.
Ref:
L. Condat, A primal dual splitting method for convex optimization involving
Lipschitzian, proxi... | 2,923 | 31.488889 | 113 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/spect.py | # spect.py
"""
SPECT forward-backward projector with parallel beam collimator.
2023-06, Zongyu Li, University of Michigan
"""
from typing import Sequence
import torch
from torch import Tensor
from .util import imrotate, fft_conv, fft_conv_adj
from .linearmaps import LinearMap
class SPECT(LinearMap):
"""
Forwa... | 4,236 | 37.87156 | 142 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/basics.py | """
Basic linear operators, including diagonal matrix, convolution and first-order finite difference.
More on the way ...
2021-02. Guanhua Wang and Keyue Zhu, University of Michigan
"""
import torch
import torch.nn.functional as F
import copy
import numpy as np
from .linearmaps import LinearMap
from typing import Sequ... | 16,079 | 37.377088 | 136 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/mri.py | """
Discrete-to-discreate system matrices for MRI.
2021-02. Guanhua Wang, University of Michigan
"""
import numpy as np
import torch
from torch import Tensor
from torch.fft import fftn, ifftn
from .linearmaps import LinearMap
from typing import Union, Sequence
import torchkbnufft as tkbn
from .util import fftshift, if... | 24,923 | 43.666667 | 177 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/linearmaps.py | import torch
from torch import Tensor
import numpy as np
from typing import Union, Sequence, TypeVar
FloatLike = Union[float, torch.FloatTensor]
def check_device(x, y):
r"""
check if two tensors are on the same device
"""
assert x.device == y.device, "Tensors should be on the same device"
T = TypeV... | 10,269 | 29.656716 | 147 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/wavelets.py | from .linearmaps import LinearMap
import torch
from torch import Tensor
from pytorch_wavelets import DWTForward, DWTInverse
from typing import Union, Sequence
import sys
# TODO: 3d wavelets
def coeffs_to_tensor(yl: Tensor,
yh: Sequence[Tensor]):
"""
Assemble 2D DWT array into a tensor
... | 6,799 | 41.236025 | 119 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/util.py | import torch
import torch.nn as nn
from torch import Tensor
from typing import Union, Sequence
import torchvision
import numpy as np
from xitorch.interpolate import Interp1D
def finitediff(x: Tensor, dim: int = -1, mode='reflexive'):
"""
Apply finite difference operator on a certain dim
Args:
x: te... | 8,106 | 25.755776 | 120 | py |
MIRTorch | MIRTorch-master/mirtorch/linear/bdd2d.py | # bdd2d.py
"""
2D branchless distance-driven projection and backprojection (bdd_2d)
for fan-beam CT geometries with a "flat" detector.
2023-06, Sonia Minseo Kim, University of Michigan
"""
import torch
from .linearmaps import LinearMap
import numpy as np
from util import map2x, map2y, integrate1D, inter1d
class bd... | 6,934 | 38.628571 | 132 | py |
MIRTorch | MIRTorch-master/mirtorch/dic/soup.py | import numpy as np
import scipy as sc
import scipy.sparse as sp
import numpy.random as random
import time
def soup(Y, D0, X0, lambd, numiter, rnd=False, only_sp=False, alert=False):
r"""
Efficient patch-based dictionary learning algorithm according to:
Ravishankar, S., Nadakuditi, R. R., & Fessler, J. A. ... | 4,763 | 40.426087 | 127 | py |
MIRTorch | MIRTorch-master/mirtorch/prox/prox.py | """ Proximal operators, such as soft-thresholding, box-constraint and L2 norm.
Prox() class includes the common proximal operators used in iterative optimization.
2021-02. Neel Shah and Guanhua Wang, University of Michigan
"""
from mirtorch.linear import LinearMap
import torch
from typing import Union
FloatLike = U... | 9,238 | 28.803226 | 116 | py |
braai | braai-master/braai/braai.py | import os
# os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
# os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import json
import argparse
import tensorflow as tf
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split
import datetime
import numpy as np
def vgg6(input_shape=(63, 6... | 34,108 | 43.998681 | 118 | py |
protoclip | protoclip-main/src/training/main.py | import logging
import os
import random
from datetime import datetime
import numpy as np
import torch
from torch import optim
from torch.cuda.amp import GradScaler
import time
try:
import wandb
except ImportError:
wandb = None
try:
import torch.utils.tensorboard as tensorboard
except ImportError:
tenso... | 23,415 | 45.552684 | 183 | py |
protoclip | protoclip-main/src/training/pretrained_transformers.py | import torch
from pytorch_transformers import RobertaModel, RobertaTokenizer
def get_pretrained_text_encoder_and_tokenizer(name):
# TODO: get the width of other models
MODELS = [
# (BertModel, BertTokenizer, 'bert-base-uncased', ?),
# (OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt... | 2,125 | 47.318182 | 212 | py |
protoclip | protoclip-main/src/training/loss.py |
import torch
import torch.nn as nn
import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
try:
import horovod.torch as hvd
except ImportError:
hvd = None
def gather_features(
image_features,
text_features,
local_l... | 5,145 | 37.402985 | 128 | py |
protoclip | protoclip-main/src/training/data.py |
import logging
from dataclasses import dataclass
import numpy as np
import pandas as pd
from PIL import Image
from torchvision.transforms import Compose, Normalize
import torch
from torch.utils.data import Dataset, DataLoader
from torch.utils.data.distributed import DistributedSampler
try:
import horovod.torch ... | 4,227 | 31.775194 | 138 | py |
protoclip | protoclip-main/src/training/clustering.py | import logging
import torch
import numpy as np
import faiss
import os
from PIL import Image
try:
import wandb
except ImportError:
wandb = None
from utils.plot_pairs import plot_pairs
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from openTSNE import TSNE
from training.distributed impo... | 11,859 | 46.250996 | 173 | py |
protoclip | protoclip-main/src/training/distributed.py | import os
import torch
try:
import horovod.torch as hvd
except ImportError:
hvd = None
import torch.distributed as dist
def get_gathered_item(item, args):
if args.distributed:
world_size = dist.get_world_size()
gathered_item = [torch.zeros_like(item) for _ in range(world_size)]
d... | 4,195 | 31.78125 | 113 | py |
protoclip | protoclip-main/src/training/params.py | import argparse
def get_default_params(model_name):
# Params from paper (https://arxiv.org/pdf/2103.00020.pdf)
model_name = model_name.lower()
if "vit" in model_name:
return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.98, "eps": 1.0e-6}
else:
return {"lr": 5.0e-4, "beta1": 0.9, "beta2": 0.... | 14,204 | 33.562044 | 169 | py |
protoclip | protoclip-main/src/training/train.py | import json
import logging
import math
import os
import time
from contextlib import suppress
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
try:
import wandb
except ImportError:
wandb = None
#from open_clip import ClipLoss
from training.loss import gather_features, Clip... | 15,645 | 44.748538 | 159 | py |
protoclip | protoclip-main/src/training/evaluations/coco_retrieval.py | import torch
import logging
import numpy as np
import tqdm
import os
from torchvision.datasets.coco import CocoCaptions
from torch.utils.data import Dataset, DataLoader
from open_clip import tokenize as clip_tokenizer
from PIL import Image
class CocoDataset(Dataset):
# modeified from https://github.com/uta-smile/... | 7,304 | 39.137363 | 116 | py |
protoclip | protoclip-main/src/training/evaluations/analyze_features.py | import numpy as np
import torch
from sklearn.metrics.pairwise import cosine_similarity
def analyze_features(all_image_features, all_text_features, args):
if all_image_features is None or all_text_features is None:
return {}
image_avg_sim = get_self_cosine_similarity(all_image_features)
text_avg_si... | 1,484 | 36.125 | 91 | py |
protoclip | protoclip-main/src/training/evaluations/linear_eval.py |
import torch
import torch.nn as nn
import numpy as np
from sklearn.linear_model import LogisticRegression as sklearnLogisticRegression
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10, CIFAR100, STL10, ImageFolder
from tqdm import tqdm
import logging
def logistic_regression_pytorch(tr... | 7,970 | 38.26601 | 120 | py |
protoclip | protoclip-main/src/training/evaluations/zero_shot.py |
import logging
import tqdm
import numpy as np
import faiss
import torch
import torch.nn.functional as F
import torchvision
from torchvision.datasets import CIFAR10, CIFAR100, STL10
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.metrics import adjusted_mutual_info_score
from open_clip import tok... | 73,060 | 67.090401 | 120 | py |
protoclip | protoclip-main/src/utils/RoBERTa.py | import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import numpy as np
import pandas as pd
import tqdm
import logging
import faiss
class TextDataset():
def __init__(self, input_filename, tokenizer, caption_key='title', sep="\t") -> None:
df = pd.read_csv(... | 2,286 | 31.211268 | 103 | py |
protoclip | protoclip-main/src/utils/evaluate_checkpoints.py | import os
import time
import pandas as pd
import torch
from training.params import parse_args
import argparse
from training.evaluations.evaluation import evaluate
from open_clip import create_model_and_transforms
import logging
import matplotlib.pyplot as plt
#from openTSNE import TSNE
from training.pretrained_transfor... | 5,078 | 37.770992 | 142 | py |
protoclip | protoclip-main/src/open_clip/openai.py | """ OpenAI pretrained model functions
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
import os
import warnings
from typing import Union, List
import torch
from .model import build_model_from_openai_state_dict
from .pretrained import get_pretrained_url, list_pretr... | 4,503 | 34.464567 | 117 | py |
protoclip | protoclip-main/src/open_clip/transform.py | from torchvision.transforms import Normalize, Compose, RandomResizedCrop, InterpolationMode, ToTensor, Resize, \
CenterCrop
import numpy as np
import torch
from torch import nn
from torchvision.transforms import transforms
def _convert_to_rgb(image):
return image.convert('RGB')
def image_transform(
... | 1,814 | 33.245283 | 115 | py |
protoclip | protoclip-main/src/open_clip/loss.py | import torch
import torch.distributed.nn
from torch import distributed as dist, nn as nn
from torch.nn import functional as F
try:
import horovod.torch as hvd
except ImportError:
hvd = None
def gather_features(
image_features,
text_features,
local_loss=False,
gather_with_grad=... | 4,658 | 39.513043 | 101 | py |
protoclip | protoclip-main/src/open_clip/utils.py | from torch import nn as nn
from torchvision.ops.misc import FrozenBatchNorm2d
def freeze_batch_norm_2d(module, module_match={}, name=''):
"""
Converts all `BatchNorm2d` and `SyncBatchNorm` layers of provided module into `FrozenBatchNorm2d`. If `module` is
itself an instance of either `BatchNorm2d` or `Syn... | 1,850 | 44.146341 | 131 | py |
protoclip | protoclip-main/src/open_clip/model.py | """ CLIP Model
Adapted from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
from collections import OrderedDict
from dataclasses import dataclass
from typing import Tuple, Union, Callable, Optional
import copy
import numpy as np
import torch
import torch.nn.functional as F
from ... | 25,390 | 39.496013 | 149 | py |
protoclip | protoclip-main/src/open_clip/factory.py | import json
import logging
import os
import pathlib
import re
from copy import deepcopy
from pathlib import Path
import torch
from .model import CLIP, convert_weights_to_fp16
from .openai import load_openai_model
from .pretrained import get_pretrained_url, download_pretrained
from .transform import image_transform
... | 5,733 | 34.8375 | 110 | py |
protoclip | protoclip-main/src/open_clip/tokenizer.py | """ CLIP tokenizer
Copied from https://github.com/openai/CLIP. Originally MIT License, Copyright (c) 2021 OpenAI.
"""
import gzip
import html
import os
from functools import lru_cache
from typing import Union, List
import ftfy
import regex as re
import torch
@lru_cache()
def default_bpe():
return os.path.join(o... | 6,200 | 33.259669 | 121 | py |
protoclip | protoclip-main/src/open_clip/timm_model.py | """ timm model adapter
Wraps timm (https://github.com/rwightman/pytorch-image-models) models for use as a vision tower in CLIP model.
"""
from collections import OrderedDict
import torch.nn as nn
try:
import timm
from timm.models.layers import Mlp, to_2tuple
from timm.models.layers.attention_pool2d impor... | 4,300 | 39.196262 | 119 | py |
rankedCUCB | rankedCUCB-main/get_domain.py | """ setup the three domains used for experiments
Lily Xu
September 2021 """
from adversary import EffortAdversary, RealEffortAdversary
import numpy as np
import pickle
import torch
import math
def get_wildlife(N, G, VERBOSE):
raise Exception('cannot share wildlife domain in publicly released code due to sensitiv... | 3,108 | 32.793478 | 133 | py |
FlowNetPytorch | FlowNetPytorch-master/main.py | import argparse
import os
import time
import torch
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import flow_transforms
import models
import datasets
from multiscaleloss import multisc... | 13,358 | 39.978528 | 136 | py |
FlowNetPytorch | FlowNetPytorch-master/run_inference.py | import argparse
from path import Path
import torch
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import models
from tqdm import tqdm
import torchvision.transforms as transforms
import flow_transforms
from imageio import imread, imwrite
import numpy as np
from util import flow2rgb
model_names =... | 5,323 | 43.739496 | 138 | py |
FlowNetPytorch | FlowNetPytorch-master/flow_transforms.py | from __future__ import division
import torch
import random
import numpy as np
import numbers
import types
import scipy.ndimage as ndimage
'''Set of tranform random routines that takes both input and target as arguments,
in order to have random but coherent transformations.
inputs are PIL Image pairs and targets are nd... | 8,765 | 32.84556 | 107 | py |
FlowNetPytorch | FlowNetPytorch-master/util.py | import os
import numpy as np
import shutil
import torch
def save_checkpoint(state, is_best, save_path, filename='checkpoint.pth.tar'):
torch.save(state, os.path.join(save_path,filename))
if is_best:
shutil.copyfile(os.path.join(save_path,filename), os.path.join(save_path,'model_best.pth.tar'))
class... | 1,388 | 28.553191 | 103 | py |
FlowNetPytorch | FlowNetPytorch-master/multiscaleloss.py | import torch
import torch.nn.functional as F
def EPE(input_flow, target_flow, sparse=False, mean=True):
EPE_map = torch.norm(target_flow-input_flow,2,1)
batch_size = EPE_map.size(0)
if sparse:
# invalid flow is defined with both flow coordinates to be exactly 0
mask = (target_flow[:,0] == ... | 2,158 | 34.393443 | 107 | py |
FlowNetPytorch | FlowNetPytorch-master/models/FlowNetC.py | import torch
import torch.nn as nn
from torch.nn.init import kaiming_normal_, constant_
from .util import conv, predict_flow, deconv, crop_like, correlate
__all__ = [
'flownetc', 'flownetc_bn'
]
class FlowNetC(nn.Module):
expansion = 1
def __init__(self,batchNorm=True):
super(FlowNetC,self).__in... | 5,156 | 36.919118 | 96 | py |
FlowNetPytorch | FlowNetPytorch-master/models/util.py | import torch.nn as nn
import torch.nn.functional as F
try:
from spatial_correlation_sampler import spatial_correlation_sample
except ImportError as e:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("default", category=ImportWarning)
warnings.warn("failed to load cus... | 2,092 | 34.474576 | 125 | py |
FlowNetPytorch | FlowNetPytorch-master/models/FlowNetS.py | import torch
import torch.nn as nn
from torch.nn.init import kaiming_normal_, constant_
from .util import conv, predict_flow, deconv, crop_like
__all__ = [
'flownets', 'flownets_bn'
]
class FlowNetS(nn.Module):
expansion = 1
def __init__(self,batchNorm=True):
super(FlowNetS,self).__init__()
... | 4,626 | 37.882353 | 96 | py |
FlowNetPytorch | FlowNetPytorch-master/datasets/listdataset.py | import torch.utils.data as data
import os
import os.path
from imageio import imread
import numpy as np
def load_flo(path):
with open(path, 'rb') as f:
magic = np.fromfile(f, np.float32, count=1)
assert(202021.25 == magic),'Magic number incorrect. Invalid .flo file'
h = np.fromfile(f, np.in... | 1,741 | 32.5 | 78 | py |
FreeYOLO | FreeYOLO-master/engine.py | import torch
import torch.distributed as dist
import time
import os
import numpy as np
from utils import distributed_utils
def rescale_image_targets(images, targets, new_img_size):
"""
Deployed for Multi scale trick.
"""
# During training phase, the shape of input image is square.
old_img_si... | 8,764 | 31.827715 | 100 | py |
FreeYOLO | FreeYOLO-master/test.py | import argparse
import cv2
import os
import time
import numpy as np
from copy import deepcopy
import torch
# load transform
from dataset.transforms import ValTransforms
# load some utils
from utils.misc import build_dataset, load_weight
from utils.com_flops_params import FLOPs_and_Params
from utils import fuse_conv_b... | 8,378 | 33.767635 | 106 | py |
FreeYOLO | FreeYOLO-master/benchmark.py | import argparse
import numpy as np
import time
import os
import torch
from dataset.transforms import ValTransforms
from dataset.coco import COCODataset, coco_class_index, coco_class_labels
from utils.com_flops_params import FLOPs_and_Params
from utils import fuse_conv_bn
from utils.misc import load_weight
from config... | 4,289 | 28.791667 | 80 | py |
FreeYOLO | FreeYOLO-master/demo.py | import argparse
from ast import arg
import cv2
import os
import time
import numpy as np
import torch
import torch.backends.cudnn as cudnn
from dataset.transforms import ValTransforms
from utils.misc import load_weight
from utils.vis_tools import visualize
from config import build_config
from models import build_model... | 8,692 | 35.52521 | 90 | py |
FreeYOLO | FreeYOLO-master/eval.py | import argparse
import os
from copy import deepcopy
import torch
from evaluator.voc_evaluator import VOCAPIEvaluator
from evaluator.coco_evaluator import COCOAPIEvaluator
from evaluator.crowdhuman_evaluator import CrowdHumanEvaluator
from evaluator.widerface_evaluator import WiderFaceEvaluator
from evaluator.ourdatas... | 6,464 | 31.00495 | 79 | py |
FreeYOLO | FreeYOLO-master/train.py | from __future__ import division
import os
import math
import argparse
from copy import deepcopy
import torch
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
from utils import distributed_utils
from utils.com_flops_params import FLOPs_and_Params
from utils.misc import Mod... | 10,907 | 37.13986 | 95 | py |
FreeYOLO | FreeYOLO-master/tools/export_onnx.py | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
# Copyright (c) Megvii, Inc. and its affiliates.
# Thanks to YOLOX: https://github.com/Megvii-BaseDetection/YOLOX/blob/main/tools/export_onnx.py
import argparse
import os
from loguru import logger
import sys
sys.path.append('..')
import torch
from torch import nn
from mo... | 5,272 | 36.935252 | 95 | py |
FreeYOLO | FreeYOLO-master/dataset/voc.py | """VOC Dataset Classes
Original author: Francisco Massa
https://github.com/fmassa/vision/blob/voc_dataset/torchvision/datasets/voc.py
Updated by: Ellis Brown, Max deGroot
"""
import os.path as osp
import torch
import torch.utils.data as data
import cv2
import numpy as np
import random
import xml.etree.ElementTree as ET... | 10,634 | 32.761905 | 101 | py |
FreeYOLO | FreeYOLO-master/dataset/crowdhuman.py | import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset
import cv2
try:
from pycocotools.coco import COCO
except:
print("It seems that the COCOAPI is not installed.")
try:
from .transforms import mosaic_x4_augment, mosaic_x9_augment, mixup_augment
except:
from tra... | 9,175 | 31.309859 | 104 | py |
FreeYOLO | FreeYOLO-master/dataset/ourdataset.py | import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset
import cv2
try:
from pycocotools.coco import COCO
except:
print("It seems that the COCOAPI is not installed.")
try:
from .transforms import mosaic_x4_augment, mosaic_x9_augment, mixup_augment
except:
from tra... | 9,224 | 31.142857 | 104 | py |
FreeYOLO | FreeYOLO-master/dataset/mot17.py | import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset
import cv2
try:
from pycocotools.coco import COCO
except:
print("It seems that the COCOAPI is not installed.")
try:
from .transforms import mosaic_x4_augment, mosaic_x9_augment, mixup_augment
except:
from tra... | 9,151 | 31 | 104 | py |
FreeYOLO | FreeYOLO-master/dataset/widerface.py | import os
import cv2
import random
import numpy as np
from torch.utils.data import Dataset
try:
from pycocotools.coco import COCO
except:
print("It seems that the COCOAPI is not installed.")
try:
from .transforms import mosaic_x4_augment, mosaic_x9_augment, mixup_augment
except:
from transforms impor... | 9,144 | 31.429078 | 104 | py |
FreeYOLO | FreeYOLO-master/dataset/coco.py | import os
import random
import numpy as np
import time
import torch
from torch.utils.data import Dataset
import cv2
try:
from pycocotools.coco import COCO
except:
print("It seems that the COCOAPI is not installed.")
try:
from .transforms import mosaic_x4_augment, mosaic_x9_augment, mixup_augment
except:
... | 11,630 | 35.233645 | 104 | py |
FreeYOLO | FreeYOLO-master/dataset/mot20.py | import os
import random
import numpy as np
import torch
from torch.utils.data import Dataset
import cv2
try:
from pycocotools.coco import COCO
except:
print("It seems that the COCOAPI is not installed.")
try:
from .transforms import mosaic_x4_augment, mosaic_x9_augment, mixup_augment
except:
from tra... | 9,151 | 31 | 104 | py |
FreeYOLO | FreeYOLO-master/dataset/transforms.py | import random
import cv2
import math
import numpy as np
import torch
import torchvision.transforms.functional as F
import time
def refine_targets(target, img_size, min_box_size):
# check target
valid_bboxes = []
valid_labels = []
target_bboxes = target['boxes'].copy()
target_labels = target['label... | 16,838 | 33.791322 | 117 | py |
FreeYOLO | FreeYOLO-master/models/__init__.py | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import torch
from .yolo_free.build import build_yolo_free
# build object detector
def build_model(args,
cfg,
device,
num_classes=80,
trainable=False):
print('==============================')
print... | 2,062 | 33.383333 | 76 | py |
FreeYOLO | FreeYOLO-master/models/yolo_free/matcher.py | import torch
import torch.nn.functional as F
from utils.box_ops import *
# YOLOX SimOTA
class SimOTA(object):
def __init__(self,
num_classes,
center_sampling_radius,
topk_candidate
) -> None:
self.num_classes = num_classes
self.... | 7,053 | 33.748768 | 96 | py |
FreeYOLO | FreeYOLO-master/models/yolo_free/loss.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .matcher import SimOTA
from utils.box_ops import get_ious
from utils.distributed_utils import get_world_size, is_dist_avail_and_initialized
class Criterion(object):
def __init__(self,
cfg,
device,
... | 5,610 | 34.967949 | 83 | py |
FreeYOLO | FreeYOLO-master/models/yolo_free/yolo_free.py | import torch
import torch.nn as nn
from ..backbone import build_backbone
from ..neck import build_neck, build_fpn
from ..head import build_head
from utils.nms import multiclass_nms
# Anchor-free YOLO
class FreeYOLO(nn.Module):
def __init__(self,
cfg,
device,
... | 10,715 | 34.601329 | 127 | py |
FreeYOLO | FreeYOLO-master/models/yolo_free/build.py | #!/usr/bin/env python3
# -*- coding:utf-8 -*-
import torch
from .loss import build_criterion
from .yolo_free import FreeYOLO
# build object detector
def build_yolo_free(args, cfg, device, num_classes=80, trainable=False):
print('==============================')
print('Build {} ...'.format(args.version.upper(... | 855 | 24.939394 | 72 | py |
FreeYOLO | FreeYOLO-master/models/backbone/shufflenetv2.py | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
model_urls = {
'shufflenetv2_0.5x': 'https://download.pytorch.org/models/shufflenetv2_x0.5-f707e7126e.pth',
'shufflenetv2_1.0x': 'https://download.pytorch.org/models/shufflenetv2_x1-5666bf0f80.pth',
'shufflenetv2_1.5x': None,
... | 7,716 | 34.237443 | 112 | py |
FreeYOLO | FreeYOLO-master/models/backbone/elannet.py | import torch
import torch.nn as nn
model_urls = {
"elannet_nano": "https://github.com/yjh0410/image_classification_pytorch/releases/download/weight/yolov7_elannet_nano.pth",
"elannet_tiny": "https://github.com/yjh0410/image_classification_pytorch/releases/download/weight/yolov7_elannet_tiny.pth",
"elannet... | 14,361 | 35.637755 | 129 | py |
FreeYOLO | FreeYOLO-master/models/neck/spp.py | import torch
import torch.nn as nn
from ..basic.conv import Conv
# Spatial Pyramid Pooling
class SPP(nn.Module):
"""
Spatial Pyramid Pooling
"""
def __init__(self, in_dim, out_dim, expand_ratio=0.5, pooling_size=[5, 9, 13], norm_type='BN', act_type='relu'):
super(SPP, self).__init__()
... | 3,086 | 32.193548 | 116 | py |
FreeYOLO | FreeYOLO-master/models/neck/elan_pafpn.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..basic.conv import Conv
class ELANBlock(nn.Module):
"""
ELAN BLock of YOLOv7's head
"""
def __init__(self, in_dim, out_dim, size='large', depthwise=False, act_type='silu', norm_type='BN'):
super(ELANBlock, self).__init__(... | 9,909 | 38.482072 | 131 | py |
FreeYOLO | FreeYOLO-master/models/head/decoupled_head.py | import torch
import torch.nn as nn
from ..basic.conv import Conv
class DecoupledHead(nn.Module):
def __init__(self, in_dim, cfg):
super().__init__()
print('==============================')
print('Head: Decoupled Head')
self.in_dim = in_dim
self.num_cls_head=cfg['num_cls_h... | 1,519 | 37 | 114 | py |
FreeYOLO | FreeYOLO-master/models/basic/bottleneck_csp.py | import torch
import torch.nn as nn
from .conv import Conv
class Bottleneck(nn.Module):
# Standard bottleneck
def __init__(self, c1, c2, shortcut=True, d=1, e=0.5, depthwise=False, norm_type='BN', act_type='lrelu'):
super(Bottleneck, self).__init__()
c_ = int(c2 * e) # hidden channels ... | 1,426 | 45.032258 | 109 | py |
FreeYOLO | FreeYOLO-master/models/basic/repconv.py | import torch
import torch.nn as nn
import numpy as np
def autopad(k, p=None): # kernel, padding
# Pad to 'same'
if p is None:
p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
return p
class RepConv(nn.Module):
# Represented convolution
# https://arxiv.org/abs/2101.0... | 7,609 | 38.430052 | 128 | py |
FreeYOLO | FreeYOLO-master/models/basic/conv.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class SiLU(nn.Module):
"""export-friendly version of nn.SiLU()"""
@staticmethod
def forward(x):
return x * torch.sigmoid(x)
def get_conv2d(c1, c2, k, p, s, d, g, padding_mode='ZERO', bias=False):
if padding_mode ... | 5,938 | 34.993939 | 112 | py |
FreeYOLO | FreeYOLO-master/evaluator/crowdhuman_evaluator.py | import json
import tempfile
import torch
from dataset.crowdhuman import CrowdHumanDataset
try:
from pycocotools.cocoeval import COCOeval
except:
print("It seems that the COCOAPI is not installed.")
class CrowdHumanEvaluator():
"""
COCO AP Evaluation class.
All the data in the val2017 dataset are ... | 4,057 | 31.99187 | 109 | py |
FreeYOLO | FreeYOLO-master/evaluator/mot_evaluator.py | import json
import tempfile
import torch
from dataset.mot17 import MOT17Dataset
from dataset.mot20 import MOT20Dataset
try:
from pycocotools.cocoeval import COCOeval
except:
print("It seems that the COCOAPI is not installed.")
class MOTEvaluator():
"""
COCO AP Evaluation class.
All the data in th... | 4,520 | 32.242647 | 109 | py |
FreeYOLO | FreeYOLO-master/evaluator/ourdataset_evaluator.py | import json
import tempfile
import torch
from dataset.ourdataset import OurDataset
try:
from pycocotools.cocoeval import COCOeval
except:
print("It seems that the COCOAPI is not installed.")
class OurDatasetEvaluator():
"""
COCO AP Evaluation class.
All the data in the val2017 dataset are process... | 4,043 | 31.878049 | 109 | py |
FreeYOLO | FreeYOLO-master/evaluator/voc_evaluator.py | """Adapted from:
@longcw faster_rcnn_pytorch: https://github.com/longcw/faster_rcnn_pytorch
@rbgirshick py-faster-rcnn https://github.com/rbgirshick/py-faster-rcnn
Licensed under The MIT License [see LICENSE for details]
"""
from dataset.voc import VOCDetection, VOC_CLASSES
import os
import time
import num... | 13,294 | 37.536232 | 97 | py |
FreeYOLO | FreeYOLO-master/evaluator/widerface_evaluator.py | import json
import tempfile
import torch
from dataset.widerface import WiderFaceDataset
try:
from pycocotools.cocoeval import COCOeval
except:
print("It seems that the COCOAPI is not installed.")
class WiderFaceEvaluator():
"""
COCO AP Evaluation class.
All the data in the val2017 dataset are pro... | 4,053 | 31.95935 | 109 | py |
FreeYOLO | FreeYOLO-master/evaluator/coco_evaluator.py | import json
import tempfile
import torch
from dataset.coco import *
try:
from pycocotools.cocoeval import COCOeval
except:
print("It seems that the COCOAPI is not installed.")
class COCOAPIEvaluator():
"""
COCO AP Evaluation class.
All the data in the val2017 dataset are processed \
and evalu... | 4,631 | 32.085714 | 109 | py |
FreeYOLO | FreeYOLO-master/utils/com_flops_params.py | import torch
from thop import profile
def FLOPs_and_Params(model, img_size, device):
x = torch.randn(1, 3, img_size, img_size).to(device)
print('==============================')
flops, params = profile(model, inputs=(x, ), verbose=False)
print('GFLOPs : {:.2f}'.format(flops / 1e9 * 2))
print('Para... | 395 | 25.4 | 63 | py |
FreeYOLO | FreeYOLO-master/utils/weight_init.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import torch.nn as nn
def constant_init(module, val, bias=0):
nn.init.constant_(module.weight, val)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias)
... | 3,756 | 32.846847 | 79 | py |
FreeYOLO | FreeYOLO-master/utils/fuse_conv_bn.py | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
def _fuse_conv_bn(conv, bn):
"""Fuse conv and bn into one module.
Args:
conv (nn.Module): Conv to be fused.
bn (nn.Module): BN to be fused.
Returns:
nn.Module: Fused module.
"""
conv_w = conv... | 1,875 | 33.740741 | 77 | py |
FreeYOLO | FreeYOLO-master/utils/misc.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, DistributedSampler
import os
import math
from copy import deepcopy
from evaluator.coco_evaluator import COCOAPIEvaluator
from evaluator.voc_evaluator import VOCAPIEvaluator
from evaluator.crowdhuman_evaluator i... | 13,888 | 29.592511 | 109 | py |
FreeYOLO | FreeYOLO-master/utils/distributed_utils.py | # from github: https://github.com/ruinmessi/ASFF/blob/master/utils/distributed_util.py
import torch
import torch.distributed as dist
import os
import subprocess
import pickle
def all_gather(data):
"""
Run all_gather on arbitrary picklable data (not necessarily tensors)
Args:
data: any picklable o... | 5,065 | 29.335329 | 94 | py |
FreeYOLO | FreeYOLO-master/utils/box_ops.py | import torch
from torchvision.ops.boxes import box_area
def box_cxcywh_to_xyxy(x):
x_c, y_c, w, h = x.unbind(-1)
b = [(x_c - 0.5 * w), (y_c - 0.5 * h),
(x_c + 0.5 * w), (y_c + 0.5 * h)]
return torch.stack(b, dim=-1)
def box_xyxy_to_cxcywh(x):
x0, y0, x1, y1 = x.unbind(-1)
b = [(x0 + x1)... | 4,095 | 30.507692 | 79 | py |
FreeYOLO | FreeYOLO-master/utils/solver/optimizer.py | import torch
import torch.nn as nn
from torch import optim
def build_optimizer(cfg, model, base_lr=0.0, resume=None):
print('==============================')
print('Optimizer: {}'.format(cfg['optimizer']))
print('--base_lr: {}'.format(base_lr))
print('--momentum: {}'.format(cfg['momentum']))
print... | 1,875 | 38.083333 | 108 | py |
specdb | specdb-master/docs/conf.py | # -*- coding: utf-8 -*-
#
# specdb documentation build configuration file, created by
# sphinx-quickstart on Fri Nov 13 13:39:35 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... | 10,043 | 30.987261 | 80 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.