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 |
|---|---|---|---|---|---|---|
robust_object_detection | robust_object_detection-main/src/models/adet/modeling/backbone/fpn.py | from torch import nn
import torch.nn.functional as F
import fvcore.nn.weight_init as weight_init
from detectron2.modeling.backbone import FPN, build_resnet_backbone
from detectron2.layers import ShapeSpec
from detectron2.modeling.backbone.build import BACKBONE_REGISTRY
from .resnet_lpf import build_resnet_lpf_backbon... | 2,848 | 31.747126 | 86 | py |
robust_object_detection | robust_object_detection-main/src/models/adet/modeling/backbone/mobilenet.py | # taken from https://github.com/tonylins/pytorch-mobilenet-v2/
# Published by Ji Lin, tonylins
# licensed under the Apache License, Version 2.0, January 2004
from torch import nn
from torch.nn import BatchNorm2d
#from detectron2.layers.batch_norm import NaiveSyncBatchNorm as BatchNorm2d
from detectron2.layers import ... | 5,384 | 33.967532 | 97 | py |
robust_object_detection | robust_object_detection-main/src/models/adet/modeling/backbone/resnet_lpf.py | # This code is built from the PyTorch examples repository: https://github.com/pytorch/vision/tree/master/torchvision/models.
# Copyright (c) 2017 Torch Contributors.
# The Pytorch examples are available under the BSD 3-Clause License.
#
# =================================================================================... | 12,201 | 41.075862 | 136 | py |
robust_object_detection | robust_object_detection-main/src/models/adet/modeling/fcos/fcos.py | import math
from typing import List, Dict
import torch
from torch import nn
from torch.nn import functional as F
from detectron2.layers import ShapeSpec, NaiveSyncBatchNorm
from detectron2.modeling.proposal_generator.build import PROPOSAL_GENERATOR_REGISTRY
from src.models.adet.layers import DFConv2d, NaiveGroupNorm
... | 8,973 | 37.515021 | 97 | py |
robust_object_detection | robust_object_detection-main/src/models/adet/modeling/fcos/fcos_outputs.py | import logging
import torch
from torch import nn
import torch.nn.functional as F
from detectron2.layers import cat
from detectron2.structures import Instances, Boxes
from detectron2.utils.comm import get_world_size
from fvcore.nn import sigmoid_focal_loss_jit
from src.models.adet.utils.comm import reduce_sum, reduce_... | 22,149 | 39.867159 | 150 | py |
robust_object_detection | robust_object_detection-main/src/datasets/noise.py | import torch
from copy import deepcopy
from detectron2.config.config import CfgNode
from ..utils.misc import get_random_generator
def load_noisy_instances(dicts, transform=lambda x:x['annotations']):
'''
Adds noisy instances to the instances in dicts usingthe provided transform.
'''
for d in dicts:
... | 3,529 | 30.517857 | 98 | py |
robust_object_detection | robust_object_detection-main/src/engine/train_teacher_student.py | import os
import numpy as np
import torch
from copy import deepcopy
from typing import OrderedDict
from detectron2.solver import build_lr_scheduler, build_optimizer
from detectron2.evaluation import inference_on_dataset
from detectron2.utils.events import CommonMetricPrinter, EventStorage
from detectron2.engine import... | 7,203 | 41.128655 | 121 | py |
robust_object_detection | robust_object_detection-main/src/engine/train_standard.py | import os
import numpy as np
import torch
from detectron2.solver import build_lr_scheduler, build_optimizer
from detectron2.evaluation import inference_on_dataset
from detectron2.utils.events import CommonMetricPrinter, EventStorage
from detectron2.engine import default_writers
from detectron2.utils.logger import setu... | 4,734 | 39.470085 | 121 | py |
robust_object_detection | robust_object_detection-main/src/utils/checkpoint.py | import os
import torch
def save_checkpoint(model, optim, scheduler, iteration, output_dir, teacher_model=None):
checkpoint_dir = os.path.join(output_dir, 'checkpoints')
os.makedirs(checkpoint_dir, exist_ok=True)
checkpoint = dict(iteration=iteration,
model=model.state_dict(),
... | 1,174 | 39.517241 | 108 | py |
robust_object_detection | robust_object_detection-main/src/utils/misc.py | import torch
import hashlib
assert torch.rand(1, generator=torch.Generator().manual_seed(0)).item() == 0.49625658988952637,\
'Random seeding is different on this machine compared to our experiments'
def to_numpy(x):
if isinstance(x, torch.Tensor):
return x.detach().cpu().numpy()
else:
... | 741 | 32.727273 | 108 | py |
robust_object_detection | robust_object_detection-main/src/utils/boxutils.py | from torchvision.ops import box_iou
import torch
import numpy as np
def box_iou_distance(boxes1, boxes2):
'''
Returned values are 1 - IoU, i.e. values in [0,1].
'''
if isinstance(boxes1, np.ndarray):
boxes1 = torch.from_numpy(boxes1)
if isinstance(boxes2, np.ndarray):
boxes2 = torch... | 1,332 | 37.085714 | 92 | py |
robust_object_detection | robust_object_detection-main/src/correction/correction_module.py | import torch
from torchvision.ops import nms, box_iou
from detectron2.config.config import configurable
from detectron2.structures import Instances, Boxes
from ..utils.boxutils import box_iou_distance, box_center_distance
class CorrectionModule:
@configurable
def __init__(self,
num_classes,
... | 12,431 | 40.578595 | 126 | py |
robust_object_detection | robust_object_detection-main/src/correction/augmentation.py | import numpy as np
import torch
from copy import deepcopy
from detectron2.config.config import configurable
from detectron2.data.transforms.augmentation import AugInput, Augmentation
from detectron2.data import transforms as T
from fvcore.transforms.transform import Transform, NoOpTransform
from scipy.ndimage.filters i... | 6,421 | 33.159574 | 107 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/main.py | #encoding=utf-8
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'
import glob
import yaml
import torch
import random
import argparse
import numpy as np
from shutil import copyfile
from argparse import Namespace
from m2p_runner import Runner
from dataset import SupervisedDataset, DAEDataset
from torch.utils.dat... | 4,774 | 42.409091 | 133 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/m2p_finetune.py | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
import re
import time
import yaml
import random
import pickle
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from functools import reduce
from sklearn.metrics import accuracy_score, f1_score
import torch
import torch.nn as nn
import tor... | 17,247 | 44.87234 | 143 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/m2p_optimization.py | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# 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/LICEN... | 19,763 | 43.918182 | 139 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/modules.py | import os
import sys
import torch
import torch.nn as nn
from torch.nn import CrossEntropyLoss
from transformers import RobertaConfig
from transformers.models.roberta.modeling_roberta import RobertaEncoder, RobertaPooler
from transformers.models.albert.modeling_albert import AlbertEmbeddings
from transformers.models.ro... | 28,915 | 42.548193 | 213 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/m2p_mask.py | import copy
import torch
import random
import numpy as np
############
# CONSTANT #
############
DR = 1
HIDDEN_SIZE = 768
MASK_PROPORTION = 0.15
MASK_CONSECUTIVE = 7
MASK_BUCKET_RATIO = 1.2
MASK_FREQUENCY = 8
NOISE_PROPORTION = 0.15
MAX_SEQLEN = 3000
def mask_tokens(inputs, mlm_probability, tokenizer, special_tokens... | 14,349 | 46.993311 | 136 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/dataset.py | #encoding=utf-8
import os
import torch
import random
import numpy as np
import pandas as pd
from torch.nn.utils.rnn import pad_sequence
from torch.utils.data.dataset import Dataset
from m2p_mask import process_train_MAM_data, mask_tokens
HALF_BATCHSIZE_TIME = 2000
HALF_BATCHSIZE_FRAMES = HALF_BATCHSIZE_TIME / 1
clas... | 20,181 | 42.589633 | 136 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/m2p_runner.py | import os
import gc
import math
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from tqdm import tqdm
from tensorboardX import SummaryWriter
from transformers import RobertaConfig
from models import EncoderDecoder
from dataset import Speech2TextDTDataset, Text2SpeechDTDa... | 35,630 | 49.828816 | 149 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/calculate_eer.py | #encoding=utf-8
import os
import random
from tqdm import tqdm
import numpy as np
import torch
import torch.nn.functional as F
# The codes are forked from GE2E's implementation: https://github.com/HarryVolek/PyTorch_Speaker_Verification/blob/master/train_speech_embedder.py#L92
def get_centroids(embeddings):
centro... | 6,158 | 36.785276 | 154 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/models.py | #encoding=utf-8
import torch.nn.functional as F
from modules import *
class EncoderDecoder(nn.Module):
def __init__(self, encoder_config, decoder_config, modality):
super().__init__()
self.encoder_config = encoder_config
self.decoder_config = decoder_config
self.return_dict = (se... | 16,230 | 37.371158 | 126 | py |
Low-Resource-Multimodal-Pre-training | Low-Resource-Multimodal-Pre-training-master/models_for_downstream.py | #encoding=utf-8
import torch.nn.functional as F
from modules import *
class EncoderDecoder(nn.Module):
def __init__(self, encoder_config, decoder_config, modality):
super().__init__()
self.encoder_config = encoder_config
self.decoder_config = decoder_config
self.return_dict = (se... | 11,499 | 42.071161 | 126 | py |
pyzx | pyzx-master/pyzx/utils.py | # PyZX - Python library for quantum circuit rewriting
# and optimization using the ZX-calculus
# Copyright (C) 2018 - Aleks Kissinger and John van de Wetering
# 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 c... | 6,185 | 32.080214 | 118 | py |
pyzx | pyzx-master/doc/conf.py | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... | 5,137 | 28.872093 | 79 | py |
hiera | hiera-main/setup.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
from setuptools import find_packages, setup
setup(
name="h... | 811 | 37.666667 | 79 | py |
hiera | hiera-main/hubconf.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
dependencies = ["torch", "timm"]
from hiera import (
hiera... | 690 | 22.827586 | 61 | py |
hiera | hiera-main/hiera/benchmarking.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
import time
from typing import List, Tuple, Union
import torch... | 2,328 | 28.858974 | 88 | py |
hiera | hiera-main/hiera/hiera_utils.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
#
# Hiera: A Hierarchical Vision Transformer without the Bells-a... | 10,719 | 36.879859 | 128 | py |
hiera | hiera-main/hiera/hiera.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
#
# Hiera: A Hierarchical Vision Transformer without the Bells-a... | 17,326 | 32.385356 | 120 | py |
hiera | hiera-main/hiera/hiera_mae.py | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# --------------------------------------------------------
# References:
# mae: https://github.com/facebookresearch/mae
# s... | 10,425 | 32.309904 | 88 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/datasets/shape_completion_dataset.py | import torch
import torch.utils.data as data
import numpy as np
import os
import utils.general as utils
class ShapeCompletionDataset(data.Dataset):
def __init__(self, dataset_path, split, points_batch=16384, d_in=3, with_gt=False, with_normals=False):
base_dir = os.path.abspath(dataset_path)
sel... | 2,217 | 35.360656 | 122 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/datasets/shape_completion_dataset_offline.py | import torch
import torch.utils.data as data
import numpy as np
import os
import utils.general as utils
class ShapeCompletionDataset(data.Dataset):
def __init__(self, dataset_path, split, points_batch=16384, d_in=3, with_gt=False, with_normals=False):
base_dir = os.path.abspath(dataset_path)
sel... | 2,630 | 37.130435 | 122 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/datasets/shape_completion_dataset_train.py | import torch
import torch.utils.data as data
import numpy as np
import os
import utils.general as utils
class ShapeCompletionDatasetTrain(data.Dataset):
def __init__(self, dataset_path, split, points_batch=16384, d_in=3, with_gt=False, with_normals=False):
base_dir = os.path.abspath(dataset_path)
... | 2,452 | 35.073529 | 122 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/shapespace/eval.py | import argparse
import os
import sys
project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(project_dir)
os.chdir(project_dir)
import json
import utils.general as utils
import torch
from pyhocon import ConfigFactory
import utils.plots as plt
from shapespace.latent_optimizer im... | 8,954 | 31.922794 | 173 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/shapespace/latent_optimizer.py | import os
import sys
project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(project_dir)
os.chdir(project_dir)
import torch
from model.network import gradient
from model.sample import Sampler
import utils.plots as plt
def adjust_learning_rate(initial_lr, optimizer, iter):
... | 4,631 | 39.631579 | 181 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/shapespace/train.py | import os
import sys
project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(project_dir)
os.chdir(project_dir)
from datetime import datetime
from pyhocon import ConfigFactory
from time import time
import argparse
import json
import torch
import utils.general as utils
from mode... | 16,130 | 38.731527 | 160 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/shapespace/interpolate.py | import os
import sys
project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(project_dir)
os.chdir(project_dir)
import argparse
import json
import utils.general as utils
import torch
import numpy as np
import utils.plots as plt
from pyhocon import ConfigFactory
from shapespace.... | 5,654 | 28.920635 | 173 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/reconstruction/run.py | import os
import sys
project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir))
sys.path.append(project_dir)
os.chdir(project_dir)
from datetime import datetime
from pyhocon import ConfigFactory
import numpy as np
import argparse
import GPUtil
import torch
import utils.general as utils
from model... | 12,827 | 35.862069 | 124 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/utils/plots.py | import plotly.graph_objs as go
import plotly.offline as offline
import torch
import numpy as np
from skimage import measure
import os
import utils.general as utils
from pymeshfix import _meshfix
def get_threed_scatter_trace(points,caption = None,colorscale = None,color = None):
if (type(points) == list):
... | 15,023 | 43.714286 | 189 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/utils/general.py | import os
import numpy as np
import torch
import trimesh
def mkdir_ifnotexists(directory):
if not os.path.exists(directory):
os.makedirs(directory)
def as_mesh(scene_or_mesh):
"""
Convert a possible scene to a mesh.
If conversion occurs, the returned mesh has only vertex and face data.
... | 1,921 | 23.961039 | 91 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/model/sample.py | import torch
import utils.general as utils
import abc
class Sampler(metaclass=abc.ABCMeta):
@abc.abstractmethod
def get_points(self,pc_input):
pass
@staticmethod
def get_sampler(sampler_type):
return utils.get_class("model.sample.{0}".format(sampler_type))
class NormalPerPoint(Sam... | 1,096 | 29.472222 | 142 | py |
visuo-haptic-shape-completion | visuo-haptic-shape-completion-main/IGR/code/model/network.py | import numpy as np
import torch.nn as nn
import torch
from torch.autograd import grad
def gradient(inputs, outputs):
d_points = torch.ones_like(outputs, requires_grad=False, device=outputs.device)
points_grad = grad(
outputs=outputs,
inputs=inputs,
grad_outputs=d_points,
create... | 2,147 | 24.270588 | 110 | py |
EMLight | EMLight-master/Needlets/mat_gen2.py | from PIL import Image
import numpy as np
import torch
from sphere_needlets import spneedlet_eval, SNvertex, visualize
from utils import tonemapping, getSolidAngleMap
import utils
import imageio
imageio.plugins.freeimage.download()
handle = utils.PanoramaHandler()
jmax = 3
B = 2.0
h, w = 128, 256
nm = 'test2.exr'
im =... | 2,127 | 27 | 75 | py |
EMLight | EMLight-master/Needlets/gt_gen_j2.py | import os
from PIL import Image
import numpy as np
import torch
from sphere_needlets import spneedlet_eval, SNvertex, visualize
from utils import tonemapping, getSolidAngleMap
import utils
jmax = 2
B = 2.0
h, w = 128, 256
bs_dir = '/home/fangneng.zfn/datasets/LavalIndoor/'
exr_dir = bs_dir + 'marc/warpedHDROutputs/'
c... | 2,330 | 28.884615 | 79 | py |
EMLight | EMLight-master/Needlets/utils.py | import numpy as np
import OpenEXR
import cv2
import Imath
import math
from scipy import interpolate
# import torch
import healpy as hp
def convert_to_panorama(dirs, sizes, colors):
grid_latitude, grid_longitude = torch.meshgrid(
[torch.arange(128, dtype=torch.float), torch.arange(2 * 128, dtype=torch.float... | 9,498 | 35.394636 | 116 | py |
EMLight | EMLight-master/Needlets/sphere_needlets.py | import numpy as np
from scipy.integrate import quad
from scipy.special import lpmn
import math
import healpy as hp
from sphere_harmonics import spharmonic_eval
from PIL import Image
import utils
def compute_f2(u):
return quad(lambda x: np.exp(-1 / (1 - x ** 2)), -1, u + 1e-10)[0] / \
quad(lambda x: np.e... | 10,842 | 35.385906 | 119 | py |
EMLight | EMLight-master/Needlets/gt_gen_j3.py | import os
from PIL import Image
import numpy as np
import torch
from sphere_needlets import spneedlet_eval, SNvertex, visualize
from utils import tonemapping, getSolidAngleMap
import utils
jmax = 3
B = 2.0
h, w = 128, 256
bs_dir = '/home/fangneng.zfn/datasets/LavalIndoor/'
exr_dir = bs_dir + 'marc/warpedHDROutputs/'
c... | 2,163 | 31.298507 | 85 | py |
EMLight | EMLight-master/RegressionNetwork/test.py | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import data
from torch.optim import lr_scheduler
import numpy as np
import pickle
from util import PanoramaHandler, TonemapHDR, tonemapping
from PIL import Image
import util
import DenseNet
from... | 3,669 | 33.299065 | 102 | py |
EMLight | EMLight-master/RegressionNetwork/data.py | import os
import os.path
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import numpy as np
import util
from PIL import Image
<<<<<<< HEAD
=======
os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1"
>>>>>>> 2e87aa6 (update)
import cv2
import pickle
import imageio
imageio.plugins.... | 2,655 | 29.181818 | 102 | py |
EMLight | EMLight-master/RegressionNetwork/panorama.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from torch.optim import lr_scheduler
import matplotlib.pyplot as plt
import numpy as np
import cv2
from PIL import Image
im... | 17,819 | 40.154734 | 139 | py |
EMLight | EMLight-master/RegressionNetwork/DenseNet.py | # https://github.com/pytorch/vision/blob/master/torchvision/models/densenet.py
# https://github.com/felixgwu/img_classification_pk_pytorch/blob/master/models/densenet.py
import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
#from torchvision.models.densenet import _Tran... | 6,684 | 41.310127 | 109 | py |
EMLight | EMLight-master/RegressionNetwork/util.py | import torch
import numpy as np
import OpenEXR
import Imath
<<<<<<< HEAD
import cv2
from scipy import interpolate
import vtk
from vtk.util import numpy_support
=======
import os
os.environ["OPENCV_IO_ENABLE_OPENEXR"]="1"
import cv2
from scipy import interpolate
>>>>>>> 2e87aa6 (update)
import imageio
imageio.plugins.fr... | 12,716 | 34.72191 | 116 | py |
EMLight | EMLight-master/RegressionNetwork/train.py | import os
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import data
from torch.optim import lr_scheduler
import numpy as np
from util import PanoramaHandler, TonemapHDR, tonemapping
from PIL import Image
import util
import DenseNet
from g... | 6,233 | 36.107143 | 137 | py |
EMLight | EMLight-master/RegressionNetwork/geomloss/samples_loss.py | # coding=utf-8
import torch
from torch.nn import Module
from functools import partial
import warnings
import numpy as np
from .utils import squared_distances, distance
from .sinkhorn_divergence import scaling_parameters, log_weights, sinkhorn_cost, sinkhorn_loop
class SamplesLoss(Module):
"""Creates a criterion ... | 3,639 | 38.139785 | 112 | py |
EMLight | EMLight-master/RegressionNetwork/geomloss/utils.py | # coding=utf-8
import torch
import numpy as np
def scal(α, f):
# if batch:
B = α.shape[0]
return (α.view(B, -1) * f.view(B, -1)).sum(1)
# else:
# return torch.dot(α.view(-1), f.view(-1))
class Sqrt0(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
result = in... | 2,800 | 26.194175 | 81 | py |
EMLight | EMLight-master/RegressionNetwork/geomloss/sinkhorn_divergence.py | # coding=utf-8
"""Implements the (unbiased) Sinkhorn divergence between abstract measures.
"""
import numpy as np
import torch
from .utils import scal
def max_diameter(x, y):
mins = torch.stack((x.min(dim=0)[0], y.min(dim=0)[0])).min(dim=0)[0]
maxs = torch.stack((x.max(dim=0)[0], y.max(dim=0)[0])).max(dim=0)[... | 3,687 | 32.527273 | 105 | py |
EMLight | EMLight-master/RegressionNetwork/gmloss/samples_loss.py | # coding=utf-8
import torch
from torch.nn import Module
from functools import partial
import warnings
import numpy as np
from .utils import squared_distances, distance
from .sinkhorn_divergence import scaling_parameters, log_weights, sinkhorn_cost, sinkhorn_loop
class SamplesLoss(Module):
"""Creates a criterion ... | 3,321 | 38.082353 | 115 | py |
EMLight | EMLight-master/RegressionNetwork/gmloss/utils.py | # coding=utf-8
import torch
import numpy as np
def scal(α, f):
# if batch:
B = α.shape[0]
return (α.view(B, -1) * f.view(B, -1)).sum(1)
# else:
# return torch.dot(α.view(-1), f.view(-1))
class Sqrt0(torch.autograd.Function):
@staticmethod
def forward(ctx, input):
result = in... | 3,143 | 27.071429 | 81 | py |
EMLight | EMLight-master/RegressionNetwork/gmloss/sinkhorn_divergence.py | # coding=utf-8
"""Implements the (unbiased) Sinkhorn divergence between abstract measures.
"""
import numpy as np
import torch
from .utils import scal
def max_diameter(x, y):
mins = torch.stack((x.min(dim=0)[0], y.min(dim=0)[0])).min(dim=0)[0]
maxs = torch.stack((x.max(dim=0)[0], y.max(dim=0)[0])).max(dim=0)[... | 3,687 | 32.527273 | 105 | py |
EMLight | EMLight-master/RegressionNetwork/representation/intensity_modify.py | import cv2
import numpy as np
from scipy import ndimage
from PIL import Image
import pickle
import os.path
import imageio
import time
import vtk
from vtk.util import numpy_support
import detect_util
import util
imageio.plugins.freeimage.download()
from torch.utils.data import Dataset, DataLoader
from torchvision impo... | 4,156 | 28.06993 | 101 | py |
EMLight | EMLight-master/RegressionNetwork/representation/distribution_representation.py | import cv2
import numpy as np
from PIL import Image
import pickle
import os.path
import imageio
import vtk
from vtk.util import numpy_support
import torch
import detect_util
import util
imageio.plugins.freeimage.download()
def rgb_to_intenisty(rgb):
intensity = 0.3 * rgb[..., 0] + 0.59 * rgb[..., 1] + 0.11 * rgb... | 6,368 | 33.803279 | 102 | py |
EMLight | EMLight-master/RegressionNetwork/representation/util.py | import numpy as np
import OpenEXR
import Imath
import cv2
from scipy import interpolate
import torch
class TonemapHDR(object):
"""
Tonemap HDR image globally. First, we find alpha that maps the (max(numpy_img) * percentile) to max_mapping.
Then, we calculate I_out = alpha * I_in ^ (1/gamma)
... | 8,647 | 35.489451 | 116 | py |
EMLight | EMLight-master/GenProjector/data.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import os
import importlib
import torch.utils.data
import numpy as np
import pickle
import cv2
from PIL import Image
import util
class LavalInd... | 4,431 | 34.174603 | 105 | py |
EMLight | EMLight-master/GenProjector/util.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import re
import importlib
import torch
from argparse import Namespace
import numpy as np
from PIL import Image
import argparse
import dill as p... | 17,707 | 33.119461 | 132 | py |
EMLight | EMLight-master/GenProjector/model_trainer.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
from models.networks.sync_batchnorm import DataParallelWithCallback
from models.pix2pix_model import Pix2PixModel
import torch.nn as nn
class T... | 3,172 | 34.651685 | 105 | py |
EMLight | EMLight-master/GenProjector/tools/util.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import re
import importlib
import torch
from argparse import Namespace
import numpy as np
from PIL import Image
import argparse
import dill as p... | 20,584 | 33.365609 | 132 | py |
EMLight | EMLight-master/GenProjector/options/base_options.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import sys
import argparse
import os
import util
import torch
import models
import data
import pickle
class BaseOptions():
def __init__(se... | 8,953 | 49.587571 | 278 | py |
EMLight | EMLight-master/GenProjector/models/pix2pix_model.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch
import models.networks as networks
import util
import torch.nn.functional as F
class Pix2PixModel(torch.nn.Module):
@staticme... | 7,606 | 39.248677 | 123 | py |
EMLight | EMLight-master/GenProjector/models/__init__.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import importlib
import torch
def find_model_using_name(model_name):
# Given the option --model [modelname],
# the file "models/modeln... | 1,417 | 30.511111 | 156 | py |
EMLight | EMLight-master/GenProjector/models/networks/architecture.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torch.nn.utils.spectral_norm as spectral_norm
from ... | 4,440 | 35.105691 | 105 | py |
EMLight | EMLight-master/GenProjector/models/networks/discriminator.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from models.networks.base_network import BaseNetwork
from models.networ... | 4,536 | 35.007937 | 106 | py |
EMLight | EMLight-master/GenProjector/models/networks/loss.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.architecture import VGG19
# Defines the GAN loss which... | 4,783 | 38.53719 | 105 | py |
EMLight | EMLight-master/GenProjector/models/networks/encoder.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from models.networks.base_network import BaseNetwork
from models.networ... | 1,929 | 34.090909 | 105 | py |
EMLight | EMLight-master/GenProjector/models/networks/__init__.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch
from models.networks.base_network import BaseNetwork
from models.networks.loss import *
from models.networks.discriminator import *... | 1,960 | 29.640625 | 105 | py |
EMLight | EMLight-master/GenProjector/models/networks/generator.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.base_network import BaseNetwork
from m... | 4,627 | 35.730159 | 189 | py |
EMLight | EMLight-master/GenProjector/models/networks/normalization.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import re
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.networks.sync_batchnorm import SynchronizedBatchNorm2d
... | 4,765 | 40.086207 | 105 | py |
EMLight | EMLight-master/GenProjector/models/networks/base_network.py | """
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
"""
import torch.nn as nn
from torch.nn import init
class BaseNetwork(nn.Module):
def __init__(self):
super(BaseNetwork, self).__init_... | 2,466 | 40.116667 | 107 | py |
EMLight | EMLight-master/GenProjector/models/networks/sync_batchnorm/replicate.py | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | 3,226 | 32.968421 | 115 | py |
EMLight | EMLight-master/GenProjector/models/networks/sync_batchnorm/unittest.py | # -*- coding: utf-8 -*-
# File : unittest.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import unittest
import torch
class TorchTes... | 746 | 23.9 | 59 | py |
EMLight | EMLight-master/GenProjector/models/networks/sync_batchnorm/batchnorm.py | # -*- coding: utf-8 -*-
# File : batchnorm.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import collections
import contextlib
import... | 15,829 | 39.075949 | 116 | py |
EMLight | EMLight-master/GenProjector/models/networks/sync_batchnorm/batchnorm_reimpl.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : batchnorm_reimpl.py
# Author : acgtyrant
# Date : 11/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import torch
import torch.nn as nn
import torch... | 2,385 | 30.813333 | 95 | py |
EMLight | EMLight-master/GenProjector/models/networks/spherenet/dataset.py | # Mathematical
import numpy as np
from scipy.ndimage.interpolation import map_coordinates
# Pytorch
import torch
from torch.utils import data
from torchvision import datasets
# Misc
from functools import lru_cache
def genuv(h, w):
u, v = np.meshgrid(np.arange(w), np.arange(h))
u = (u + 0.5) * 2 * np.pi / w ... | 7,232 | 32.486111 | 92 | py |
EMLight | EMLight-master/GenProjector/models/networks/spherenet/sphere_cnn.py | import numpy as np
from numpy import sin, cos, tan, pi, arcsin, arctan
from functools import lru_cache
import torch
from torch import nn
from torch.nn.parameter import Parameter
# Calculate kernels of SphereCNN
@lru_cache(None)
def get_xy(delta_phi, delta_theta):
return np.array([
[
(-tan(delt... | 6,050 | 32.065574 | 102 | py |
CEMNet | CEMNet-main/train_model.py | import numpy as np, torch, os, pdb
from utils.options import opts
from utils.transform_pc import transform_pc_torch
from utils.euler2mat import euler2mat_torch
from utils.recorder import Recorder
from utils.test import test
from utils.losses import CDLoss, GMLoss
from datasets.get_dataset import get_dataset
from cems.g... | 3,068 | 37.3625 | 153 | py |
CEMNet | CEMNet-main/test_model.py | import numpy as np, torch, time
from datasets.get_dataset import get_dataset
from utils.options import opts
from utils.recorder import Recorder
from utils.attr_dict import AttrDict
from cems.guided_cem import GuidedCEM
from tqdm import tqdm
np.random.seed(opts.seed)
torch.manual_seed(opts.seed)
torch.cuda.manual_seed_... | 4,443 | 35.42623 | 179 | py |
CEMNet | CEMNet-main/modules/dgcnn.py | import torch.nn as nn, torch.nn.functional as F, torch
from modules.commons import get_graph_feature
class DGCNN(nn.Module):
def __init__(self, emb_dims=512):
super(DGCNN, self).__init__()
self.conv1 = nn.Conv2d(6, 64, kernel_size=1, bias=False)
self.conv2 = nn.Conv2d(64, 64, kernel_size=1,... | 1,343 | 42.354839 | 76 | py |
CEMNet | CEMNet-main/modules/commons.py | import copy, torch.nn as nn, torch, math, torch.nn.functional as F
def knn(x, k):
inner = -2 * torch.matmul(x.transpose(2, 1).contiguous(), x)
xx = torch.sum(x ** 2, dim=1, keepdim=True)
pairwise_distance = -xx - inner - xx.transpose(2, 1).contiguous()
idx = pairwise_distance.topk(k=k, dim=-1)[1] # (... | 6,076 | 40.623288 | 180 | py |
CEMNet | CEMNet-main/modules/dcp_net.py | import torch.nn as nn, torch
from modules.dgcnn import DGCNN
from utils.mat2euler import mat2euler
def pairwise_distance_batch(x,y):
xx = torch.sum(torch.mul(x,x), 1, keepdim = True)#[b,1,n]
yy = torch.sum(torch.mul(y,y),1, keepdim = True) #[b,1,n]
inner = -2*torch.matmul(x.transpose(2,1),y) #[b,n,n]
p... | 3,482 | 46.067568 | 123 | py |
CEMNet | CEMNet-main/modules/sparsemax.py | import torch, torch.nn as nn
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Sparsemax(nn.Module):
"""Sparsemax function."""
def __init__(self, dim=None):
"""Initialize sparsemax activation
Args:
dim (int, optional): The dimension over which to apply t... | 3,139 | 31.371134 | 117 | py |
CEMNet | CEMNet-main/datasets/get_dataset.py | from torch.utils.data import DataLoader
from datasets.dataset import DB_ModelNet40, DB_7Scene, DB_ICL_NUIM
def get_dataset(opts, db_nm, partition, batch_size, shuffle, drop_last, is_normal=False, cls_idx=-1, n_cores=1):
loader, db = None, None
if db_nm == "modelnet40":
db = DB_ModelNet40(opts, partitio... | 907 | 55.75 | 113 | py |
CEMNet | CEMNet-main/datasets/base_dataset.py | from torch.utils.data import Dataset
from scipy.spatial.transform import Rotation
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import minkowski
import numpy as np, pdb, pickle
def load_data(path):
file = open(path, "rb")
data = pickle.load(file)
file.close()
return data
c... | 3,320 | 40 | 115 | py |
CEMNet | CEMNet-main/datasets/process_dataset.py | import h5py, sys, os, glob, numpy as np, pdb
sys.path.insert(0, "..")
from datasets.utils.gen_normal import gen_normal
from datasets.utils.commons import save_data
import datasets.se_math.mesh as mesh, datasets.se_math.transforms as transforms, torchvision, torch
# ============ ModelNet40 ==============
def process_mo... | 4,521 | 47.106383 | 99 | py |
CEMNet | CEMNet-main/datasets/se_math/so3.py | """ 3-d rotation group and corresponding Lie algebra """
import torch
from . import sinc
from .sinc import sinc1, sinc2, sinc3
def cross_prod(x, y):
z = torch.cross(x.view(-1, 3), y.view(-1, 3), dim=1).view_as(x)
return z
def liebracket(x, y):
return cross_prod(x, y)
def mat(x):
# size: [*, 3] -> ... | 5,229 | 22.039648 | 84 | py |
CEMNet | CEMNet-main/datasets/se_math/invmat.py | """ inverse matrix """
import torch
def batch_inverse(x):
""" M(n) -> M(n); x -> x^-1 """
batch_size, h, w = x.size()
assert h == w
y = torch.zeros_like(x)
for i in range(batch_size):
y[i, :, :] = x[i, :, :].inverse()
return y
def batch_inverse_dx(y):
""" backward """
# Let ... | 4,203 | 29.686131 | 88 | py |
CEMNet | CEMNet-main/datasets/se_math/se3.py | """ 3-d rigid body transfomation group and corresponding Lie algebra. """
import torch
from .sinc import sinc1, sinc2, sinc3
from . import so3
def twist_prod(x, y):
x_ = x.view(-1, 6)
y_ = y.view(-1, 6)
xw, xv = x_[:, 0:3], x_[:, 3:6]
yw, yv = y_[:, 0:3], y_[:, 3:6]
zw = so3.cross_prod(xw, yw)
... | 3,962 | 22.589286 | 79 | py |
CEMNet | CEMNet-main/datasets/se_math/sinc.py | """ sinc(t) := sin(t) / t """
import torch
from torch import sin, cos
def sinc1(t):
""" sinc1: t -> sin(t)/t """
e = 0.01
r = torch.zeros_like(t)
a = torch.abs(t)
s = a < e
c = (s == 0)
t2 = t[s] ** 2
r[s] = 1 - t2 / 6 * (1 - t2 / 20 * (1 - t2 / 42)) # Taylor series O(t^8)
r[c] =... | 5,466 | 21.497942 | 114 | py |
CEMNet | CEMNet-main/datasets/se_math/transforms.py | """ gives some transform methods for 3d points """
import math
import torch
import torch.utils.data
from . import so3
from . import se3
class Mesh2Points:
def __init__(self):
pass
def __call__(self, mesh):
mesh = mesh.clone()
v = mesh.vertex_array
return torch.from_numpy(v).... | 4,906 | 24.035714 | 86 | py |
CEMNet | CEMNet-main/datasets/utils/db_icl_nuim.py | '''
Copyright (c) 2020 NVIDIA
Author: Wentao Yuan
'''
import h5py
import numpy as np
import os
import torch
from scipy.spatial import cKDTree
from torch.utils.data import Dataset
from sklearn.neighbors import NearestNeighbors
from scipy.spatial.distance import minkowski
import open3d
def jitter_pcd(pcd, sigma=0.01, cl... | 6,579 | 41.727273 | 128 | py |
CEMNet | CEMNet-main/cems/guided_cem.py | from cems.base_cem import BaseCEM
from modules.dcp_net import DCPNet
from modules.sparsemax import Sparsemax
from utils.commons import stack_transforms_seq
import pdb, torch
class VanillaCEM(BaseCEM):
def __init__(self, opts):
super(VanillaCEM, self).__init__(opts)
self.opts = opts
class GuidedCE... | 2,282 | 42.075472 | 161 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.