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 |
|---|---|---|---|---|---|---|
GrUMoDepth | GrUMoDepth-main/evaluate.py | #
# MIT License
#
# Copyright (c) 2020 Matteo Poggi m.poggi@unibo.it
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, c... | 8,739 | 37.502203 | 143 | py |
GrUMoDepth | GrUMoDepth-main/generate_maps.py | #
# MIT License
#
# Copyright (c) 2020 Matteo Poggi m.poggi@unibo.it
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, c... | 23,210 | 45.890909 | 127 | py |
GrUMoDepth | GrUMoDepth-main/trainer_supervised.py | # Monodepth2 to train in a supervised manner on NYU Depth V2
# Copyright Niantic 2019. Patent Pending. All rights reserved.
#
# This software is licensed under the terms of the Monodepth2 licence
# which allows for non-commercial use only, the full terms of which are made
# available in the LICENSE file.
"""
Source: mo... | 10,208 | 38.569767 | 117 | py |
GrUMoDepth | GrUMoDepth-main/evaluate_supervised.py | from __future__ import absolute_import, division, print_function
import warnings
import pickle
from torch.utils.data import DataLoader
from extended_options import *
import datasets as datasets
import monodepth2.networks as legacy
import networks as networks
import progressbar
import matplotlib.pyplot as plt
from gra... | 19,995 | 44.036036 | 120 | py |
GrUMoDepth | GrUMoDepth-main/gradients.py | import cv2
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import time
def squared_difference(prediction, ground_truth):
difference = torch.abs(prediction - ground_truth) ** 2
return difference
class Gradient_Analysis(nn.Module):
def __init__(self, model: nn.Module,... | 2,728 | 36.902778 | 100 | py |
GrUMoDepth | GrUMoDepth-main/networks/decoder_supervised.py | # # Monodepth2 extended to estimate depth and uncertainty
# #
# # This software is licensed under the terms of the Monodepth2 licence
# # which allows for non-commercial use only, the full terms of which are
# # available at https://github.com/nianticlabs/monodepth2/blob/master/LICENSE
# """
# Source: modified from htt... | 3,431 | 35.903226 | 131 | py |
GrUMoDepth | GrUMoDepth-main/networks/decoder.py | # # Monodepth2 extended to estimate depth and uncertainty
# #
# # This software is licensed under the terms of the Monodepth2 licence
# # which allows for non-commercial use only, the full terms of which are
# # available at https://github.com/nianticlabs/monodepth2/blob/master/LICENSE
# """
# Source: modified from htt... | 4,777 | 34.656716 | 119 | py |
GrUMoDepth | GrUMoDepth-main/datasets/nyu_dataset.py | # MIT License
#
# Copyright (c) 2019 Diana Wofk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... | 7,124 | 36.109375 | 114 | py |
GrUMoDepth | GrUMoDepth-main/datasets/transforms.py | # MIT License
#
# Copyright (c) 2019 Diana Wofk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, p... | 20,864 | 33.487603 | 107 | py |
ensembleKW | ensembleKW-main/examples/voting.py | import numpy as np
import argparse
import csv
import tensorflow as tf
from scriptify import scriptify
def readFile(count=2,
dir="evalData/l_inf/mnist_small_0_1/mnist_small_0_1",
data="test"):
file = dir + "_" + str(count) + "_" + str(data)
result = np.loadtxt(file)
y_pred = resu... | 10,245 | 33.267559 | 125 | py |
ensembleKW | ensembleKW-main/examples/primal.py | import setGPU
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from convex_adversarial import DualNetBounds, Affine, full_bias
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import setproctitle
impo... | 4,127 | 37.579439 | 110 | py |
ensembleKW | ensembleKW-main/examples/evaluate.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
cudnn.benchmark = True
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import random
import setproctitle
import ... | 4,081 | 27.545455 | 103 | py |
ensembleKW | ensembleKW-main/examples/mnist_epsilon.py | import waitGPU
waitGPU.wait(utilization=20, available_memory=10000, interval=10)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
from convex_adversarial import DualNetBounds
import torchvision.transforms as transforms
import torchvisi... | 4,604 | 37.057851 | 272 | py |
ensembleKW | ensembleKW-main/examples/har.py | # import waitGPU
# waitGPU.wait(utilization=20, interval=60)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import torch.utils.data as td
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import setp... | 2,605 | 39.092308 | 109 | py |
ensembleKW | ensembleKW-main/examples/runtime.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import gpustat
import numpy as np
from problems import Flatten
def gpu_mem():
stats = gpustat.GPUStatCollection.new_query()
for gpu in stats:
util = gpu.entry['memory.used']
break
return u... | 3,227 | 25.459016 | 82 | py |
ensembleKW | ensembleKW-main/examples/attack_ensemble.py | import random
import numpy as np
import setproctitle
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import tqdm
from absl import app
from ml_collections import config_flags
from torch.autograd import Variable
import problems as pblm
from convex_adversarial import RobustBounds, robust_loss, r... | 25,200 | 38.071318 | 114 | py |
ensembleKW | ensembleKW-main/examples/fashion_mnist.py | import waitGPU
waitGPU.wait(utilization=20)#, available_memory=11000, interval=10)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import cvxpy as cp
import torchvision.transforms as transforms
import torchvision.da... | 2,618 | 36.956522 | 116 | py |
ensembleKW | ensembleKW-main/examples/problems.py | # a hack to ensure scripts search cwd
import sys
sys.path.append('.')
import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import torch.nn.functional as F
import numpy as np
import torch.ut... | 15,454 | 32.524946 | 134 | py |
ensembleKW | ensembleKW-main/examples/svhn.py | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import setproctitle
import argparse
import problems as pblm
from trainer import *
if __name__ == "__m... | 2,423 | 38.737705 | 109 | py |
ensembleKW | ensembleKW-main/examples/ensemble.py | import torch
from evaluate import select_mnist_model, select_cifar_model
model_type = "small"
eps = "8px"
data = "cifar"
l = "inf"
if data == "mnist":
select_model = select_mnist_model
elif data == "cifar":
select_model = select_cifar_model
models = []
dir="./../models/seq_trained/l_"+str(l)+"/"
name_seq = st... | 1,006 | 26.972222 | 82 | py |
ensembleKW | ensembleKW-main/examples/cifar.py | # import waitGPU
# import setGPU
# waitGPU.wait(utilization=20, available_memory=10000, interval=60)
# waitGPU.wait(gpu_ids=[1,3], utilization=20, available_memory=10000, interval=60)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
impo... | 5,550 | 36.506757 | 90 | py |
ensembleKW | ensembleKW-main/examples/trainer.py |
import torch
import torch.nn as nn
from torch.autograd import Variable
from convex_adversarial import robust_loss, robust_loss_parallel
import torch.optim as optim
import numpy as np
import time
import gc
from attacks import _pgd
DEBUG = False
def train_robust(loader, model, opt, epsilon, epoch, log, verbose,
... | 18,991 | 34.235622 | 130 | py |
ensembleKW | ensembleKW-main/examples/attacks.py | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from convex_adversarial import robust_loss
class Flatten(nn.Module):
def forward(self, x):
return x.view(x.size(0), -1)
def... | 3,229 | 32.298969 | 119 | py |
ensembleKW | ensembleKW-main/examples/mnist.py | # import waitGPU
# import setGPU
# waitGPU.wait(utilization=50, available_memory=10000, interval=60)
# waitGPU.wait(gpu_ids=[1,3], utilization=20, available_memory=10000, interval=60)
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from torch.autograd import Variable
impo... | 5,878 | 38.993197 | 105 | py |
ensembleKW | ensembleKW-main/convex_adversarial/dual_network.py | import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
from .utils import Dense, DenseSequential
from .dual_inputs import select_input
from .dual_layers import select_layer
import warnings
class DualNetwork(nn.Module):
def __init__(self,
net,
... | 10,789 | 32.2 | 82 | py |
ensembleKW | ensembleKW-main/convex_adversarial/dual_layers.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .dual import DualLayer
from .utils import full_bias, Dense
def select_layer(layer, dual_net, X, proj, norm_type, in_f, out_f, zsi,
zl=None, zu=None):
if isinstance(layer, nn.Linear):
return DualLinear(layer, out_f)
... | 14,219 | 29.191083 | 138 | py |
ensembleKW | ensembleKW-main/convex_adversarial/dual_inputs.py | import torch
import torch.nn as nn
from .dual import DualObject
def select_input(X, epsilon, proj, norm, bounded_input, l=0,u=1):
if proj is not None and norm=='l1_median' and X[0].numel() > proj:
if bounded_input:
return InfBallProjBounded(X,epsilon,proj, l=l, u=u)
else:
... | 8,336 | 31.439689 | 92 | py |
ensembleKW | ensembleKW-main/convex_adversarial/dual.py | import torch.nn as nn
from abc import ABCMeta, abstractmethod
class DualObject(nn.Module, metaclass=ABCMeta):
def __init__(self):
""" Initialize a dual layer by initializing the variables needed to
compute this layer's contribution to the upper and lower bounds.
In the paper, if this o... | 1,722 | 34.163265 | 80 | py |
ensembleKW | ensembleKW-main/convex_adversarial/utils.py | import torch.nn as nn
###########################################
# Helper function to extract fully #
# shaped bias terms #
###########################################
def full_bias(l, n=None):
# expands the bias to the proper size. For convolutional layers, a full
# output dime... | 3,974 | 33.267241 | 98 | py |
PySR | PySR-master/pysr/sr.py | """Define the PySRRegressor scikit-learn interface."""
import copy
from io import StringIO
import os
import sys
import numpy as np
import pandas as pd
import sympy
from sympy import sympify
import re
import tempfile
import shutil
from pathlib import Path
import pickle as pkl
from datetime import datetime
import warning... | 98,031 | 39.643449 | 112 | py |
PySR | PySR-master/pysr/julia_helpers.py | """Functions for initializing the Julia environment and installing deps."""
import sys
import subprocess
import warnings
from pathlib import Path
import os
from julia.api import JuliaError
from .version import __version__, __symbolic_regression_jl_version__
juliainfo = None
julia_initialized = False
julia_kwargs_at_i... | 11,396 | 32.619469 | 290 | py |
PySR | PySR-master/pysr/export_torch.py | #####
# From https://github.com/patrick-kidger/sympytorch
# Copied here to allow PySR-specific tweaks
#####
import collections as co
import functools as ft
import sympy
def _reduce(fn):
def fn_(*args):
return ft.reduce(fn, args)
return fn_
torch_initialized = False
torch = None
SingleSymPyModule =... | 7,576 | 36.509901 | 93 | py |
PySR | PySR-master/pysr/__init__.py | from . import sklearn_monkeypatch
from .version import __version__
from .sr import (
pysr,
PySRRegressor,
best,
best_tex,
best_callable,
best_row,
)
from .julia_helpers import install
from .feynman_problems import Problem, FeynmanProblem
from .export_jax import sympy2jax
from .export_torch impor... | 334 | 21.333333 | 53 | py |
PySR | PySR-master/pysr/export_jax.py | import functools as ft
import sympy
import string
import random
# Special since need to reduce arguments.
MUL = 0
ADD = 1
_jnp_func_lookup = {
sympy.Mul: MUL,
sympy.Add: ADD,
sympy.div: "jnp.div",
sympy.Abs: "jnp.abs",
sympy.sign: "jnp.sign",
# Note: May raise error for ints.
sympy.ceiling... | 6,320 | 29.834146 | 86 | py |
PySR | PySR-master/pysr/test/test_jax.py | import unittest
import numpy as np
import pandas as pd
import sympy
from functools import partial
from .. import sympy2jax, PySRRegressor
class TestJAX(unittest.TestCase):
def setUp(self):
np.random.seed(0)
def test_sympy2jax(self):
from jax import numpy as jnp
from jax import random... | 4,049 | 30.153846 | 86 | py |
PySR | PySR-master/pysr/test/__main__.py | """CLI for running PySR's test suite."""
import argparse
import os
from . import *
if __name__ == "__main__":
# Get args:
parser = argparse.ArgumentParser()
parser.usage = "python -m pysr.test [tests...]"
parser.add_argument(
"test",
nargs="*",
help="Test to run. One or more of... | 1,157 | 25.318182 | 81 | py |
PySR | PySR-master/pysr/test/test.py | import os
import traceback
import inspect
import unittest
import numpy as np
from sklearn import model_selection
from sklearn.utils.estimator_checks import check_estimator
import sympy
import pandas as pd
import warnings
import pickle as pkl
import tempfile
from pathlib import Path
from .. import julia_helpers
from ..... | 36,285 | 38.228108 | 413 | py |
PySR | PySR-master/pysr/test/test_torch.py | import unittest
import numpy as np
import pandas as pd
import platform
import sympy
from .. import sympy2torch, PySRRegressor
# Need to initialize Julia before importing torch...
def _import_torch():
if platform.system() == "Darwin":
# Import PyJulia, then Torch
from ..julia_helpers import init_j... | 6,535 | 30.12381 | 87 | py |
PySR | PySR-master/pysr/test/__init__.py | from .test import runtests
from .test_env import runtests as runtests_env
from .test_jax import runtests as runtests_jax
from .test_torch import runtests as runtests_torch
from .test_cli import runtests as runtests_cli
| 219 | 35.666667 | 50 | py |
CongFu | CongFu-main/utils.py | import torch
from torch_geometric.data import Data
import pandas as pd
import numpy as np
from sklearn.metrics import precision_recall_curve, auc, roc_auc_score
from typing import Tuple
import json
from rdkit import Chem
from rdkit.Chem.rdchem import BondType as BT
from tqdm import tqdm
ATOM_LIST = list(range(1, 119)... | 3,984 | 33.95614 | 188 | py |
CongFu | CongFu-main/dataset.py | import torch
from torch.utils.data import Dataset
DRUG1_ID_COLUMN_NAME = "Drug1_ID"
DRUG2_ID_COLUMN_NAME= "Drug2_ID"
CELL_LINE_COLUMN_NAME = "Cell_Line_ID"
class DrugCombDataset(Dataset):
def __init__(self, drugcomb, cell_lines, mol_mapping, transform=None):
self.drugcomb = drugcomb
self.mol_mappi... | 1,279 | 33.594595 | 83 | py |
CongFu | CongFu-main/layers.py | import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.nn.conv import MessagePassing
from torch_geometric.data import Data
from torch_geometric.utils import add_self_loops
from typing import Union, Tuple
class ContextPropagation(nn.Module):
def __init__(self, context_input_d... | 6,180 | 38.369427 | 150 | py |
CongFu | CongFu-main/models.py | import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.nn import global_mean_pool
from torch_geometric.nn.conv import MessagePassing, GATConv
from torch_geometric.data import Data
from layers import CongFuLayer, BasicLayer, GINEConv, create_mlp
NUM_ATOM_TYPE = 119
NUM_CHIRALITY_T... | 4,072 | 41.427083 | 171 | py |
CongFu | CongFu-main/train.py | import torch
from torch import nn
from torch_geometric.loader import DataLoader
import wandb
from dataclasses import dataclass
from tqdm import tqdm
import argparse
from dataset import DrugCombDataset
from models import CongFuBasedModel
from utils import get_datasets, get_mol_dict, calculate_auprc, calculate_roc_auc
... | 5,447 | 34.376623 | 182 | py |
ilf | ilf-master/ilf/__main__.py | import sys
import numpy
import torch
import random
import argparse
import logging
from .fuzzers import Environment
from .fuzzers.random import PolicyRandom, ObsRandom
from .fuzzers.imitation import PolicyImitation, ObsImitation
from .fuzzers.symbolic import PolicySymbolic, ObsSymbolic
from .fuzzers.sym_plus import Pol... | 3,708 | 39.315217 | 132 | py |
ilf | ilf-master/ilf/fuzzers/environment.py | import random
import numpy
import torch
import logging
from ..execution import Execution, Tx
from ..ethereum import Method
from .random import PolicyRandom
from .symbolic import PolicySymbolic
from .sym_plus import PolicySymPlus
from .mix import PolicyMix, ObsMix
from .imitation import PolicyImitation
LOG = logging.... | 3,037 | 35.166667 | 121 | py |
ilf | ilf-master/ilf/fuzzers/imitation/layers.py | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/1609.02907
"""
def __init__(self, in_features, out... | 1,350 | 29.704545 | 77 | py |
ilf | ilf-master/ilf/fuzzers/imitation/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers import GraphConvolution
from .amounts import AMOUNTS
from .addr_map import ADDR_MAP
HIDDEN_PARAMS = 100
class ArgsNet(nn.Module):
def __init__(self, input_size, hidden_size):
super(ArgsNet, self).__init__()
self.hi... | 4,942 | 28.422619 | 112 | py |
ilf | ilf-master/ilf/fuzzers/imitation/policy_imitation.py | import time
import random
import numpy as np
import itertools
import pickle
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
from datetime import datetime
from torch.optim import Adam, SGD
from torch.optim.lr_scheduler import StepLR
from sklearn.preprocessing import StandardScaler
from skle... | 32,081 | 45.094828 | 141 | py |
speech-privacy | speech-privacy-main/src/main.py | """
Script to train adversary classifier
"""
import argparse
import numpy as np
import os
import pickle
import random
import time
import torch
import torch.nn as nn
import torch.optim as optim
from tensorboardX import SummaryWriter
from torch.utils.data import DataLoader
from data_utils import *
from model import *
... | 5,754 | 37.112583 | 145 | py |
speech-privacy | speech-privacy-main/src/model.py | """
Model definition
"""
import random
import torch
import torchaudio
import torch.nn as nn
import torch.nn.functional as F
class VGGVoxClf(nn.Module):
"""Based on https://github.com/zimmerrol/vggvox-pytorch"""
def __init__(self, nOut=1024, log_input=True):
super(VGGVoxClf, self).__init__()
s... | 2,424 | 30.907895 | 169 | py |
speech-privacy | speech-privacy-main/src/data_utils.py | """
Data loading utilities
"""
import glob
import math
import numpy as np
import os
import random
import soundfile as sf
import torch
from torch.utils.data import Dataset
def collate_1d_float(batch):
text_xs = []
text_ys = []
max_len_text = 0
for (text_x, _) in batch:
x_len = len(text_x)
... | 4,239 | 37.899083 | 180 | py |
neural-lpcfg | neural-lpcfg-master/flow.py | from __future__ import print_function
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import Normal
import numpy as np
import pdb
class ReLUNet(nn.Module):
def __init__(self, hidden_layers, hidden_units, in_features, out_features):
super(ReLUNet, s... | 4,206 | 34.058333 | 132 | py |
neural-lpcfg | neural-lpcfg-master/utils.py | #Norm!/usr/bin/env python3
import numpy as np
import itertools
import random
import torch
import nltk
import pickle
import pdb
def all_binary_trees(n):
#get all binary trees of length n
def is_tree(tree, n):
# shift = 0, reduce = 1
if sum(tree) != n-1:
return False
stack = 0
for a in tre... | 13,274 | 25.87247 | 248 | py |
neural-lpcfg | neural-lpcfg-master/data.py | #!/usr/bin/env python3
import numpy as np
import torch
import pickle
class Dataset(object):
def __init__(self, data_file, load_dep=False):
data = pickle.load(open(data_file, 'rb')) #get text data
self.sents = self._convert(data['source']).long()
self.other_data = data['other_data']
self.sent_lengths ... | 1,666 | 34.468085 | 77 | py |
neural-lpcfg | neural-lpcfg-master/lexicalizedPCFG.py | #!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import itertools
import random
from torch.cuda import memory_allocated
import pdb
class LexicalizedPCFG(nn.Module):
# Lexicalized PCFG:
# S → A[x] A ∈ N, x ∈ 𝚺
# A[x] → B[x] C[y] A, B, C ∈... | 14,743 | 42.880952 | 150 | py |
neural-lpcfg | neural-lpcfg-master/models.py | import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
from PCFG import PCFG
from lexicalizedPCFG import LexicalizedPCFG
from random import shuffle
from flow import FlowWordEmission
import pdb
class ResidualLayer(nn.Module):
def __init__(self, in_dim = 100,
out_dim = 100)... | 16,808 | 46.752841 | 116 | py |
neural-lpcfg | neural-lpcfg-master/train.py | #!/usr/bin/env python3
import sys
import os
import argparse
import json
import random
import shutil
import copy
from collections import defaultdict
import torch
from torch import cuda
import numpy as np
import time
import logging
from data import Dataset
from utils import *
from models import CompPCFG, LexicalizedCo... | 21,640 | 46.045652 | 145 | py |
neural-lpcfg | neural-lpcfg-master/PCFG.py | #!/usr/bin/env python3
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import itertools
import random
class PCFG(nn.Module):
def __init__(self, nt_states, t_states):
super(PCFG, self).__init__()
self.nt_states = nt_states
self.t_states = t_states
self.states =... | 6,435 | 39.734177 | 99 | py |
RPMG | RPMG-main/ModelNet_PC/model.py | import torch
import torch.nn as nn
import sys
import os
from os.path import join as pjoin
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0,pjoin(BASEPATH, '../..'))
import utils.tools as tools
from pointnets import PointNet2_cls
class Model(nn.Module):
def __init__(self, out_rotation_mode="Quaternion"):
... | 2,032 | 29.343284 | 84 | py |
RPMG | RPMG-main/ModelNet_PC/pointnet_utils.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from time import time
import numpy as np
def timeit(tag, t):
print("{}: {}s".format(tag, time() - t))
return time()
def square_distance(src, dst):
"""
Calculate Euclid distance between each two points.
src^T * dst = xn * xm + yn *... | 11,031 | 35.052288 | 104 | py |
RPMG | RPMG-main/ModelNet_PC/pointnets.py | import torch.nn as nn
import torch
import torch.nn.functional as F
import os
import sys
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0, BASEPATH)
from pointnet_utils import PointNetSetAbstractionMsg,PointNetSetAbstraction,PointNetFeaturePropagation
class PointNet2_seg(nn.Module):
def __init__(self, out_cha... | 4,523 | 36.7 | 139 | py |
RPMG | RPMG-main/ModelNet_PC/pointnet_lib/setup.py | from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='pointnet2',
ext_modules=[
CUDAExtension('pointnet2_cuda', [
'src/pointnet2_api.cpp',
'src/ball_query.cpp',
'src/ball_query_gpu.cu',
... | 679 | 27.333333 | 67 | py |
RPMG | RPMG-main/ModelNet_PC/pointnet_lib/pointnet2_utils.py | import torch
from torch.autograd import Variable
from torch.autograd import Function
import torch.nn as nn
from typing import Tuple
import pointnet2_cuda as pointnet2
class FurthestPointSampling(Function):
@staticmethod
def forward(ctx, xyz: torch.Tensor, npoint: int) -> torch.Tensor:
"""
Use... | 13,245 | 33.22739 | 151 | py |
RPMG | RPMG-main/ModelNet_PC/pointnet_lib/pointnet2_modules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import os
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0, BASEPATH)
CUDA = torch.cuda.is_available()
if CUDA:
import pointnet2_utils as futils
def knn_point(k, pos2, pos1):
'''
Input:
k: int32, number of k in k-... | 12,024 | 33.754335 | 124 | py |
RPMG | RPMG-main/ModelNet_PC/pointnet_lib/pytorch_utils.py | import torch.nn as nn
from typing import List, Tuple
class SharedMLP(nn.Sequential):
def __init__(
self,
args: List[int],
*,
bn: bool = False,
activation=nn.ReLU(inplace=True),
preact: bool = False,
first: bool = False,
... | 6,173 | 25.050633 | 95 | py |
RPMG | RPMG-main/ModelNet_PC/code/test.py | import torch
import numpy as np
import random
import os
from os.path import join as pjoin
import sys
import argparse
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0,pjoin(BASEPATH, '../..'))
sys.path.insert(0,pjoin(BASEPATH, '..'))
import config as Config
import utils.tools as tools
from model import Model
def... | 2,761 | 35.826667 | 104 | py |
RPMG | RPMG-main/ModelNet_PC/code/prepare_data.py | '''
from mesh to normalized pc
'''
import numpy as np
import torch
import os
from os.path import join as pjoin
import trimesh
import argparse
import sys
import tqdm
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0,pjoin(BASEPATH, '../..'))
import utils.tools as tools
def pc_normalize(pc):
centroid = (np.max... | 2,445 | 39.766667 | 137 | py |
RPMG | RPMG-main/ModelNet_PC/code/dataset.py | import torch
import os
import numpy as np
class ModelNetDataset(torch.utils.data.Dataset):
def __init__(self, data_folder,sample_num=1024):
super(ModelNetDataset, self).__init__()
self.paths = [os.path.join(data_folder, i) for i in os.listdir(data_folder)]
self.sample_num = sample_num
... | 647 | 31.4 | 84 | py |
RPMG | RPMG-main/ModelNet_PC/code/train.py | import torch
import numpy as np
import os
from os.path import join as pjoin
import argparse
import sys
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0,pjoin(BASEPATH, '../..'))
sys.path.insert(0,pjoin(BASEPATH, '..'))
import utils.tools as tools
import utils.rpmg as rpmg
import config as Config
from dataset im... | 6,589 | 37.764706 | 114 | py |
RPMG | RPMG-main/ModelNet_PC/code/visualize.py | import matplotlib.pyplot as plt
import torch
def visualize(pc, pred_r, gt_r):
pc_pred = torch.bmm(pc, pred_r)
pc_gt = torch.bmm(pc, gt_r)
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(pc[...,0], pc[...,1],pc[...,2])
ax = fig.add_subplot(111, projection='... | 525 | 29.941176 | 65 | py |
RPMG | RPMG-main/ModelNet_PC/code_selfsup/test.py | import torch
import numpy as np
import random
import os
from os.path import join as pjoin
import sys
import argparse
from chamfer_distance import ChamferDistance
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0,pjoin(BASEPATH, '../..'))
sys.path.insert(0,pjoin(BASEPATH, '..'))
import config as Config
import utils... | 3,079 | 37.024691 | 114 | py |
RPMG | RPMG-main/ModelNet_PC/code_selfsup/dataset.py | import torch
import numpy as np
import trimesh
def pc_normalize(pc):
centroid = (np.max(pc, axis=0) + np.min(pc, axis=0)) /2
pc = pc - centroid
scale = np.linalg.norm(np.max(pc, axis=0) - np.min(pc, axis=0))
pc = pc / scale
return pc, centroid, scale
class SingleInstanceDataset(torch.utils.dat... | 922 | 30.827586 | 67 | py |
RPMG | RPMG-main/ModelNet_PC/code_selfsup/train.py | import torch
import numpy as np
import os
from os.path import join as pjoin
import argparse
import sys
from chamfer_distance import ChamferDistance
BASEPATH = os.path.dirname(__file__)
sys.path.insert(0,pjoin(BASEPATH, '../..'))
sys.path.insert(0,pjoin(BASEPATH, '..'))
import utils.tools as tools
import utils.rpmg as... | 6,095 | 36.398773 | 114 | py |
RPMG | RPMG-main/ModelNet_PC/code_selfsup/visualize.py | import matplotlib.pyplot as plt
import torch
def visualize(pc, pred_r, gt_r):
pc_pred = torch.bmm(pc, pred_r)
pc_gt = torch.bmm(pc, gt_r)
fig = plt.figure(figsize=(8, 8))
ax = fig.add_subplot(111, projection='3d')
ax.scatter(pc[...,0], pc[...,1],pc[...,2])
ax = fig.add_subplot(111, projection='... | 525 | 29.941176 | 65 | py |
RPMG | RPMG-main/ModelNet_PC/code_selfsup/chamfer_distance/chamfer_distance.py |
import torch
from torch.utils.cpp_extension import load
cd = load(name="cd",
sources=["chamfer_distance/chamfer_distance.cpp",
"chamfer_distance/chamfer_distance.cu"])
class ChamferDistanceFunction(torch.autograd.Function):
@staticmethod
def forward(ctx, xyz1, xyz2):
batc... | 1,798 | 30.017241 | 94 | py |
RPMG | RPMG-main/utils/tools.py | import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
#rotation5d batch*5
def normalize_5d_rotation( r5d):
batch = r5d.shape[0]
sin_cos = r5d[:,0:2] #batch*2
sin_cos_mag = torch.max(torch.sqrt( sin_cos.pow(2).sum(1)), torch.autograd.Variable(torch.DoubleTensor([1e-... | 19,121 | 32.606327 | 188 | py |
RPMG | RPMG-main/utils/rpmg.py | import torch
import sys
import os
BASEPATH = os.path.dirname(__file__)
sys.path.append(BASEPATH)
import tools
def Rodrigues(w):
'''
axis angle -> rotation
:param w: [b,3]
:return: R: [b,3,3]
'''
w = w.unsqueeze(2).unsqueeze(3).repeat(1, 1, 3, 3)
b = w.shape[0]
theta = w.norm(dim=1)
... | 9,942 | 42.801762 | 148 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/dataset.py | from lib.datasets.Dataset_Base import Dataset_Base
import os
import numpy as np
import torch
import sys
BASEPATH = os.path.dirname(__file__)
sys.path.append(os.path.join(BASEPATH, '..', '..', 'utils'))
import tools
from torch.utils.data import Dataset, DataLoader
import cv2
class MyDataset(Dataset_Base):
def __ge... | 1,876 | 28.793651 | 118 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/networks.py | import torch
from torch import nn
from torch import Tensor
from typing import Callable, Any, Optional, List
def get_network(config):
return MobileNetV2(config.num_classes)
def set_requires_grad(nets, requires_grad=False):
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
P... | 8,009 | 35.244344 | 116 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/trainval_workdir.py | """
@Author : Shuai Liao
"""
# import matplotlib
# matplotlib.use('Agg') # server mode.
#
import torch
import torch.optim
#
import os, sys, time
from time import gmtime, strftime
import numpy as np
from math import pi
from easydict import EasyDict as edict
from collections import OrderedDict as odict
#
from basic.c... | 20,512 | 39.700397 | 146 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/agent.py | from utils import TrainClock, KSchedule
import os
import torch
import torch.optim as optim
import torch.nn as nn
from tensorboardX import SummaryWriter
import sys
BASEPATH = os.path.dirname(__file__)
sys.path.append(os.path.join(BASEPATH, '..', '..', 'utils'))
import tools
import rpmg
from networks import get_network
... | 6,269 | 37.703704 | 106 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/regQuatNet/regQuatNet.py | # coding: utf8
"""
@Author : Shuai Liao
"""
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from torch.autograd import Variable
import torch
import torch.nn.functional as F
from basic.common import rdict
import numpy as np
from easydict import EasyDict as edict
from collections import OrderedDict as ... | 12,708 | 38.715625 | 143 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/lib/helper.py | # coding: utf8
"""
@Author : Shuai Liao
"""
import torch
import torch.nn as nn
from torch.autograd import Variable
import numpy as np
from easydict import EasyDict as edict
from collections import OrderedDict as odict
from itertools import product
#
from collections import OrderedDict
class Cross_Entropy_Loss_Han... | 2,518 | 30.4875 | 118 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/lib/datasets/Dataset_Base.py | """
@Author : Shuai Liao
"""
import os, sys
import numpy as np
from math import ceil, floor, pi
import torch
from torch.utils.data import Dataset, DataLoader
from collections import OrderedDict as odict
import cv2
path = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
... | 8,875 | 38.802691 | 108 | py |
RPMG | RPMG-main/ModelNet_Img/S3.3D_Rotation/lib/datasets/dataset_regQuatNet.py | """
@Author : Shuai Liao
"""
import numpy as np
from Dataset_Base import Dataset_Base, netcfg
import torch
from torch.utils.data import Dataset, DataLoader
import cv2
from basic.common import add_path, env, rdict, cv2_wait, cv2_putText
# ===============================================================
def pred2ang... | 1,914 | 27.58209 | 83 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/lmdb_util/imagedata_lmdb.py | """
@Author : Shuai Liao
"""
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from basic.common import add_path, env, Timer, Checkpoint, cv2_wait, is_py3
from basic.util import load_yaml, dump_yaml
import cv2
import numpy as np
import lmdb
from pprint import pprint
if is_p... | 22,562 | 37.503413 | 159 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/torch_3rd_layers.py | import torch
import torch.nn as nn
import numpy as np
from basic.common import is_py3
if is_py3:
from functools import reduce
'''
Define Maskout layer
'''
class Maskout(nn.Module):
def __init__(self, nr_cate=3): # ks: kernel_size
super(Maskout, self).__init__()
self.nr_cate = nr_cate
d... | 1,480 | 31.911111 | 116 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/torch_v4_feature.py | import math
from torch.nn.modules.module import Module
from torch.nn.modules.utils import _single, _pair, _triple
from torch.nn.parameter import Parameter
from torch.nn.functional import * # pad, avg_pool2d
# this is already in v4.0, but now I'm using v3.0
def local_response_norm(input, size, alpha=1e-4, beta=0.75,... | 2,964 | 36.531646 | 87 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/torch_3rd_funcs.py | import torch
import torch.nn as nn
import numpy as np
from torch.autograd import Variable
np.set_printoptions(precision=5, suppress=True)
def norm2unit(vecs, dim=1, p=2):
""" vecs is of 2D: (batchsize x nr_feat) or (batchsize x nr_feat x restDims)
We normalize it to a unit vector here.
For examp... | 6,932 | 36.679348 | 140 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/netutil/common_v2/trunk_alexnet_bvlc.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
from basic.common import rdict
import numpy as np
from easydict import EasyDict as edict
import math
from pytorch_util.libtrain import copy_weights, init_weights_by_filling
from pytorch_util.torch_v4_feature import LocalResponseNorm # *
from... | 7,390 | 38.736559 | 99 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/netutil/common_v2/trunk_inception.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
__all__ = ['_Inception3_Trunk'] # ['Inception3', 'inception_v3']
model_urls = {
# Inception v3 ported from TensorFlow
'inception_v3_google': 'https://download.pytorch.org/models/inception_v3_google-1a... | 12,691 | 36.439528 | 103 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/netutil/common_v2/trunk_vgg.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import math
from collections import OrderedDict as odict
from pytorch_util.torch_v4_feature import LocalResponseNorm # *
from pytorch_util.libtrain import copy_weights, init_weights_by_filling
__all__ = ['_VGG_Trunk', 'VGGM_Trunk', 'VGG16_Trunk', 'VGG19... | 20,743 | 41.859504 | 114 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/netutil/common_v2/__init__.py | # from trunck_alexnet_bvlc import AlexNet_Trunk
# from trunck_alexnet_pytorch import AlexNet_Trunk
| 102 | 33.333333 | 50 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/netutil/common_v2/trunk_resnet.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
from pytorch_util.libtrain import init_weights_by_filling, cfg as pretrained_cfg
# __all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101', 'resnet152']
__all__ = ['_ResNet_Trunk'] # , 'resnet18', 'resnet34', 'resnet... | 13,777 | 40.251497 | 125 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/netutil/common_v2/trunk_alexnet_pytorch.py | import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch
from basic.common import rdict
import numpy as np
from easydict import EasyDict as edict
from pytorch_util.libtrain import copy_weights
from pytorch_util.torch_3rd_layers import Maskout
from pytorch_util.torch_3rd_funcs import norm2unit
__al... | 5,746 | 35.144654 | 91 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/libtrain/reducer_v2.py | import numpy as np
import torch
'''
Class hierarchy:
net_reducer
// || \\
// || \\
// || \\
// || \\
reducer_group(a) reducer_group(... | 12,331 | 38.149206 | 136 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/libtrain/tools.py | import torch
from collections import OrderedDict
def get_stripped_DataParallel_state_dict(m, base_name='', newdict=OrderedDict()):
""" strip 'module.' caused by DataParallel.
"""
try:
# Test if any child exist.
# m.children().next()
next(m.children())
# Pass test, has one o... | 3,106 | 34.712644 | 136 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/libtrain/yaml_netconf.py | import os, sys
# from cafferas import list_models, copy_weights
from basic.common import add_path
from basic.util import parse_yaml, dump_yaml, load_yaml
# import yaml
# import oyaml as yaml # oyaml is a drop-in replacement for PyYAML which preserves dict ordering.
from pprint import pprint
# from ordered_easydict imp... | 2,463 | 30.189873 | 98 | py |
RPMG | RPMG-main/ModelNet_Img/pylibs/pytorch_util/libtrain/reducer.py | import numpy as np
import torch
'''
Class hierarchy:
net_reducer
// || \\
// || \\
// || \\
// || \\
reducer_group(a) reducer_group(... | 4,395 | 37.561404 | 107 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.