code stringlengths 17 6.64M |
|---|
def parse_col(toks, start_idx, tables_with_alias, schema, default_tables=None):
'\n :returns next idx, column id\n '
tok = toks[start_idx]
if (tok == '*'):
return ((start_idx + 1), schema.idMap[tok])
if ('.' in tok):
(alias, col) = tok.split('.')
key = ((tables_with_a... |
def parse_col_unit(toks, start_idx, tables_with_alias, schema, default_tables=None):
'\n :returns next idx, (agg_op id, col_id)\n '
idx = start_idx
len_ = len(toks)
isBlock = False
isDistinct = False
if (toks[idx] == '('):
isBlock = True
idx += 1
if (toks[idx] in ... |
def parse_val_unit(toks, start_idx, tables_with_alias, schema, default_tables=None):
idx = start_idx
len_ = len(toks)
isBlock = False
if (toks[idx] == '('):
isBlock = True
idx += 1
col_unit1 = None
col_unit2 = None
unit_op = UNIT_OPS.index('none')
(idx, col_unit1) = par... |
def parse_table_unit(toks, start_idx, tables_with_alias, schema):
'\n :returns next idx, table id, table name\n '
idx = start_idx
len_ = len(toks)
key = tables_with_alias[toks[idx]]
if (((idx + 1) < len_) and (toks[(idx + 1)] == 'as')):
idx += 3
else:
idx += 1
ret... |
def parse_value(toks, start_idx, tables_with_alias, schema, default_tables=None):
idx = start_idx
len_ = len(toks)
isBlock = False
if (toks[idx] == '('):
isBlock = True
idx += 1
if (toks[idx] == 'select'):
(idx, val) = parse_sql(toks, idx, tables_with_alias, schema)
eli... |
def parse_condition(toks, start_idx, tables_with_alias, schema, default_tables=None):
idx = start_idx
len_ = len(toks)
conds = []
while (idx < len_):
(idx, val_unit) = parse_val_unit(toks, idx, tables_with_alias, schema, default_tables)
not_op = False
if (toks[idx] == 'not'):
... |
def parse_select(toks, start_idx, tables_with_alias, schema, default_tables=None):
idx = start_idx
len_ = len(toks)
assert (toks[idx] == 'select'), "'select' not found"
idx += 1
isDistinct = False
if ((idx < len_) and (toks[idx] == 'distinct')):
idx += 1
isDistinct = True
v... |
def parse_from(toks, start_idx, tables_with_alias, schema):
'\n Assume in the from clause, all table units are combined with join\n '
assert ('from' in toks[start_idx:]), "'from' not found"
len_ = len(toks)
idx = (toks.index('from', start_idx) + 1)
default_tables = []
table_units = []
... |
def parse_where(toks, start_idx, tables_with_alias, schema, default_tables):
idx = start_idx
len_ = len(toks)
if ((idx >= len_) or (toks[idx] != 'where')):
return (idx, [])
idx += 1
(idx, conds) = parse_condition(toks, idx, tables_with_alias, schema, default_tables)
return (idx, conds)... |
def parse_group_by(toks, start_idx, tables_with_alias, schema, default_tables):
idx = start_idx
len_ = len(toks)
col_units = []
if ((idx >= len_) or (toks[idx] != 'group')):
return (idx, col_units)
idx += 1
assert (toks[idx] == 'by')
idx += 1
while ((idx < len_) and (not ((toks... |
def parse_order_by(toks, start_idx, tables_with_alias, schema, default_tables):
idx = start_idx
len_ = len(toks)
val_units = []
order_type = 'asc'
if ((idx >= len_) or (toks[idx] != 'order')):
return (idx, val_units)
idx += 1
assert (toks[idx] == 'by')
idx += 1
while ((idx ... |
def parse_having(toks, start_idx, tables_with_alias, schema, default_tables):
idx = start_idx
len_ = len(toks)
if ((idx >= len_) or (toks[idx] != 'having')):
return (idx, [])
idx += 1
(idx, conds) = parse_condition(toks, idx, tables_with_alias, schema, default_tables)
return (idx, cond... |
def parse_limit(toks, start_idx):
idx = start_idx
len_ = len(toks)
if ((idx < len_) and (toks[idx] == 'limit')):
idx += 2
if (type(toks[(idx - 1)]) != int):
return (idx, 1)
return (idx, int(toks[(idx - 1)]))
return (idx, None)
|
def parse_sql(toks, start_idx, tables_with_alias, schema):
isBlock = False
len_ = len(toks)
idx = start_idx
sql = {}
if (toks[idx] == '('):
isBlock = True
idx += 1
(from_end_idx, table_units, conds, default_tables) = parse_from(toks, start_idx, tables_with_alias, schema)
sq... |
def load_data(fpath):
with open(fpath) as f:
data = json.load(f)
return data
|
def get_sql(schema, query):
toks = tokenize(query)
tables_with_alias = get_tables_with_alias(schema.schema, toks)
(_, sql) = parse_sql(toks, 0, tables_with_alias, schema)
return sql
|
def skip_semicolon(toks, start_idx):
idx = start_idx
while ((idx < len(toks)) and (toks[idx] == ';')):
idx += 1
return idx
|
def clean_str_month(o):
if isinstance(o, int):
o = str(o)
for (month, n) in month2num.items():
o = o.replace(month, n)
return o
|
def date_parser(o):
default_result = {'value': None, 'template': 'N/A'}
if (o is None):
return default_result
o = clean_str_month(o)
for t in templates:
try:
d = datetime.datetime.strptime(o, t)
return {'value': d, 'template': t}
except ValueError:
... |
class cv_colors(Enum):
RED = (0, 0, 255)
GREEN = (0, 255, 0)
BLUE = (255, 0, 0)
PURPLE = (247, 44, 200)
ORANGE = (44, 162, 247)
MINT = (239, 255, 66)
YELLOW = (2, 255, 250)
|
def constraint_to_color(constraint_idx):
return {0: cv_colors.PURPLE.value, 1: cv_colors.ORANGE.value, 2: cv_colors.MINT.value, 3: cv_colors.YELLOW.value}[constraint_idx]
|
def create_2d_box(box_2d):
corner1_2d = box_2d[0]
corner2_2d = box_2d[1]
pt1 = corner1_2d
pt2 = (corner1_2d[0], corner2_2d[1])
pt3 = corner2_2d
pt4 = (corner2_2d[0], corner1_2d[1])
return (pt1, pt2, pt3, pt4)
|
def project_3d_pt(pt, cam_to_img, calib_file=None):
if (calib_file is not None):
cam_to_img = get_calibration_cam_to_image(calib_file)
R0_rect = get_R0(calib_file)
Tr_velo_to_cam = get_tr_to_velo(calib_file)
point = np.array(pt)
point = np.append(point, 1)
point = np.dot(cam_to... |
def plot_3d_pts(img, pts, center, calib_file=None, cam_to_img=None, relative=False, constraint_idx=None):
if (calib_file is not None):
cam_to_img = get_calibration_cam_to_image(calib_file)
for pt in pts:
if relative:
pt = [(i + center[j]) for (j, i) in enumerate(pt)]
point ... |
def plot_3d_box(img, cam_to_img, ry, dimension, center):
R = rotation_matrix(ry)
corners = create_corners(dimension, location=center, R=R)
box_3d = []
for corner in corners:
point = project_3d_pt(corner, cam_to_img)
box_3d.append(point)
cv2.line(img, (box_3d[0][0], box_3d[0][1]), (... |
def plot_2d_box(img, box_2d):
(pt1, pt2, pt3, pt4) = create_2d_box(box_2d)
cv2.line(img, pt1, pt2, cv_colors.BLUE.value, 2)
cv2.line(img, pt2, pt3, cv_colors.BLUE.value, 2)
cv2.line(img, pt3, pt4, cv_colors.BLUE.value, 2)
cv2.line(img, pt4, pt1, cv_colors.BLUE.value, 2)
|
@app.route('/')
def start_page():
print('Start')
return render_template('index.html')
|
@app.route('/upload', methods=['POST'])
def upload_file():
FILENAME = {}
image = request.files['image']
image.save('static/image_eval.png')
if ('image' in request.files):
detect = True
detect3d(reg_weights='weights/epoch_10.pkl', model_select='resnet', source='static', calib_file='eval... |
def parse_opt():
parser = argparse.ArgumentParser()
parser.add_argument('--weights', nargs='+', type=str, default=(ROOT / 'yolov5s.pt'), help='model path(s)')
parser.add_argument('--source', type=str, default=(ROOT / 'eval/image_2'), help='file/dir/URL/glob, 0 for webcam')
parser.add_argument('--data'... |
class CrossConv(nn.Module):
def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
super().__init__()
c_ = int((c2 * e))
self.cv1 = Conv(c1, c_, (1, k), (1, s))
self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
self.add = (shortcut and (c1 == c2))
def forward(se... |
class Sum(nn.Module):
def __init__(self, n, weight=False):
super().__init__()
self.weight = weight
self.iter = range((n - 1))
if weight:
self.w = nn.Parameter(((- torch.arange(1.0, n)) / 2), requires_grad=True)
def forward(self, x):
y = x[0]
if sel... |
class MixConv2d(nn.Module):
def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
super().__init__()
n = len(k)
if equal_ch:
i = torch.linspace(0, (n - 1e-06), c2).floor()
c_ = [(i == g).sum() for g in range(n)]
else:
b = ([c2] + ([0] * n))
... |
class Ensemble(nn.ModuleList):
def __init__(self):
super().__init__()
def forward(self, x, augment=False, profile=False, visualize=False):
y = []
for module in self:
y.append(module(x, augment, profile, visualize)[0])
y = torch.cat(y, 1)
return (y, None)
|
def attempt_load(weights, map_location=None, inplace=True, fuse=True):
from models.yolo import Detect, Model
model = Ensemble()
for w in (weights if isinstance(weights, list) else [weights]):
ckpt = torch.load(attempt_download(w), map_location=map_location)
if fuse:
model.appen... |
class NumpyEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, np.ndarray):
return obj.tolist()
return json.JSONEncoder.default(self, obj)
|
class ClassAverages():
def __init__(self, classes=[]):
self.dimension_map = {}
self.filename = (os.path.abspath(os.path.dirname(__file__)) + '/class_averages.txt')
if (len(classes) == 0):
self.load_items_from_file()
for detection_class in classes:
class_ = ... |
def train(epochs=10, batch_size=32, alpha=0.6, w=0.4, num_workers=2, lr=0.0001, save_epoch=10, train_path=(ROOT / 'dataset/KITTI/training'), model_path=(ROOT / 'weights/'), select_model='resnet18', api_key=''):
train_path = str(train_path)
model_path = str(model_path)
print('[INFO] Loading dataset...')
... |
def parse_opt():
parser = argparse.ArgumentParser(description='Regressor Model Training')
parser.add_argument('--epochs', type=int, default=10, help='Number of epochs')
parser.add_argument('--batch_size', type=int, default=32, help='Number of batch size')
parser.add_argument('--alpha', type=float, def... |
def main(opt):
train(**vars(opt))
|
def train(train_path=(ROOT / 'dataset/KITTI/training'), checkpoint_path=(ROOT / 'weights/checkpoints'), model_select='resnet18', epochs=10, batch_size=32, num_workers=2, gpu=1, val_split=0.1, model_path=(ROOT / 'weights/'), api_key=''):
comet_logger = CometLogger(api_key=api_key, project_name='YOLO3D')
checkp... |
def parse_opt():
parser = argparse.ArgumentParser(description='Regressor Model Training')
parser.add_argument('--train_path', type=str, default=(ROOT / 'dataset_dummy/training'), help='Training path KITTI')
parser.add_argument('--checkpoint_path', type=str, default=(ROOT / 'weights/checkpoint'), help='Che... |
def main(opt):
train(**vars(opt))
|
def notebook_init(verbose=True):
print('Checking setup...')
import os
import shutil
from utils.general import check_requirements, emojis, is_colab
from utils.torch_utils import select_device
check_requirements(('psutil', 'IPython'))
import psutil
from IPython import display
if is_c... |
class SiLU(nn.Module):
@staticmethod
def forward(x):
return (x * torch.sigmoid(x))
|
class Hardswish(nn.Module):
@staticmethod
def forward(x):
return ((x * F.hardtanh((x + 3), 0.0, 6.0)) / 6.0)
|
class Mish(nn.Module):
@staticmethod
def forward(x):
return (x * F.softplus(x).tanh())
|
class MemoryEfficientMish(nn.Module):
class F(torch.autograd.Function):
@staticmethod
def forward(ctx, x):
ctx.save_for_backward(x)
return x.mul(torch.tanh(F.softplus(x)))
@staticmethod
def backward(ctx, grad_output):
x = ctx.saved_tensors[0]
... |
class FReLU(nn.Module):
def __init__(self, c1, k=3):
super().__init__()
self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
self.bn = nn.BatchNorm2d(c1)
def forward(self, x):
return torch.max(x, self.bn(self.conv(x)))
|
class AconC(nn.Module):
' ACON activation (activate or not).\n AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter\n according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.\n '
def __init__(self, c1):
super().__i... |
class MetaAconC(nn.Module):
' ACON activation (activate or not).\n MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network\n according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.\n '
def __init__(self, c1, k=1, ... |
def check_train_batch_size(model, imgsz=640):
with amp.autocast():
return autobatch(deepcopy(model).train(), imgsz)
|
def autobatch(model, imgsz=640, fraction=0.9, batch_size=16):
prefix = colorstr('AutoBatch: ')
LOGGER.info(f'{prefix}Computing optimal batch size for --imgsz {imgsz}')
device = next(model.parameters()).device
if (device.type == 'cpu'):
LOGGER.info(f'{prefix}CUDA not detected, using default CPU... |
class Callbacks():
'"\n Handles all registered callbacks for YOLOv5 Hooks\n '
def __init__(self):
self._callbacks = {'on_pretrain_routine_start': [], 'on_pretrain_routine_end': [], 'on_train_start': [], 'on_train_epoch_start': [], 'on_train_batch_start': [], 'optimizer_step': [], 'on_before_zer... |
def gsutil_getsize(url=''):
s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
return (eval(s.split(' ')[0]) if len(s) else 0)
|
def safe_download(file, url, url2=None, min_bytes=1.0, error_msg=''):
file = Path(file)
assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
try:
print(f'Downloading {url} to {file}...')
torch.hub.download_url_to_file(url, str(file))
assert (fi... |
def attempt_download(file, repo='ultralytics/yolov5'):
file = Path(str(file).strip().replace("'", ''))
if (not file.exists()):
name = Path(urllib.parse.unquote(str(file))).name
if str(file).startswith(('http:/', 'https:/')):
url = str(file).replace(':/', '://')
file = n... |
def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
t = time.time()
file = Path(file)
cookie = Path('cookie')
print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
file.unlink(missing_ok=True)
cookie.unlink(missing_ok=True)
... |
def get_token(cookie='./cookie'):
with open(cookie) as f:
for line in f:
if ('download' in line):
return line.split()[(- 1)]
return ''
|
@app.route(DETECTION_URL, methods=['POST'])
def predict():
if (not (request.method == 'POST')):
return
if request.files.get('image'):
image_file = request.files['image']
image_bytes = image_file.read()
img = Image.open(io.BytesIO(image_bytes))
results = model(img, size=... |
def create_dataset_artifact(opt):
logger = WandbLogger(opt, None, job_type='Dataset Creation')
if (not logger.wandb):
LOGGER.info('install wandb using `pip install wandb` to log the dataset')
|
def sweep():
wandb.init()
hyp_dict = vars(wandb.config).get('_items')
opt = parse_opt(known=True)
opt.batch_size = hyp_dict.get('batch_size')
opt.save_dir = str(increment_path((Path(opt.project) / opt.name), exist_ok=(opt.exist_ok or opt.evolve)))
opt.epochs = hyp_dict.get('epochs')
opt.no... |
@contextmanager
def torch_distributed_zero_first(local_rank: int):
'\n Decorator to make all processes in distributed training wait for each local_master to do something.\n '
if (local_rank not in [(- 1), 0]):
dist.barrier(device_ids=[local_rank])
(yield)
if (local_rank == 0):
di... |
def date_modified(path=__file__):
t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
return f'{t.year}-{t.month}-{t.day}'
|
def git_describe(path=Path(__file__).parent):
s = f'git -C {path} describe --tags --long --always'
try:
return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:(- 1)]
except subprocess.CalledProcessError as e:
return ''
|
def select_device(device='', batch_size=0, newline=True):
s = f'YOLOv5 🚀 {(git_describe() or date_modified())} torch {torch.__version__} '
device = str(device).strip().lower().replace('cuda:', '')
cpu = (device == 'cpu')
if cpu:
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
elif device:
... |
def time_sync():
if torch.cuda.is_available():
torch.cuda.synchronize()
return time.time()
|
def profile(input, ops, n=10, device=None):
results = []
device = (device or select_device())
print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}{'input':>24s}{'output':>24s}")
for x in (input if isinstance(input, list) else [input]):
x = x.to... |
def is_parallel(model):
return (type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel))
|
def de_parallel(model):
return (model.module if is_parallel(model) else model)
|
def initialize_weights(model):
for m in model.modules():
t = type(m)
if (t is nn.Conv2d):
pass
elif (t is nn.BatchNorm2d):
m.eps = 0.001
m.momentum = 0.03
elif (t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU]):
m.inplace... |
def find_modules(model, mclass=nn.Conv2d):
return [i for (i, m) in enumerate(model.module_list) if isinstance(m, mclass)]
|
def sparsity(model):
(a, b) = (0, 0)
for p in model.parameters():
a += p.numel()
b += (p == 0).sum()
return (b / a)
|
def prune(model, amount=0.3):
import torch.nn.utils.prune as prune
print('Pruning model... ', end='')
for (name, m) in model.named_modules():
if isinstance(m, nn.Conv2d):
prune.l1_unstructured(m, name='weight', amount=amount)
prune.remove(m, 'weight')
print((' %.3g glob... |
def fuse_conv_and_bn(conv, bn):
fusedconv = nn.Conv2d(conv.in_channels, conv.out_channels, kernel_size=conv.kernel_size, stride=conv.stride, padding=conv.padding, groups=conv.groups, bias=True).requires_grad_(False).to(conv.weight.device)
w_conv = conv.weight.clone().view(conv.out_channels, (- 1))
w_bn = ... |
def model_info(model, verbose=False, img_size=640):
n_p = sum((x.numel() for x in model.parameters()))
n_g = sum((x.numel() for x in model.parameters() if x.requires_grad))
if verbose:
print(f"{'layer':>5} {'name':>40} {'gradient':>9} {'parameters':>12} {'shape':>20} {'mu':>10} {'sigma':>10}")
... |
def scale_img(img, ratio=1.0, same_shape=False, gs=32):
if (ratio == 1.0):
return img
else:
(h, w) = img.shape[2:]
s = (int((h * ratio)), int((w * ratio)))
img = F.interpolate(img, size=s, mode='bilinear', align_corners=False)
if (not same_shape):
(h, w) = (... |
def copy_attr(a, b, include=(), exclude=()):
for (k, v) in b.__dict__.items():
if ((len(include) and (k not in include)) or k.startswith('_') or (k in exclude)):
continue
else:
setattr(a, k, v)
|
class EarlyStopping():
def __init__(self, patience=30):
self.best_fitness = 0.0
self.best_epoch = 0
self.patience = (patience or float('inf'))
self.possible_stop = False
def __call__(self, epoch, fitness):
if (fitness >= self.best_fitness):
self.best_epoch... |
class ModelEMA():
' Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models\n Keep a moving average of everything in the model state_dict (parameters and buffers).\n This is intended to allow functionality like\n https://www.tensorflow.org/api_docs/python/tf/train/Exponent... |
def get_weights(weights):
weights_list = {'resnet': '1Bw4gUsRBxy8XZDGchPJ_URQjbHItikjw', 'resnet18': '1k_v1RrDO6da_NDhBtMZL5c0QSogCmiRn', 'vgg11': '1vZcB-NaPUCovVA-pH-g-3NNJuUA948ni'}
url = f'https://drive.google.com/uc?id={weights_list[weights]}'
output = f'./{weights}.pkl'
gdown.download(url, output... |
def geodesic_fps(points, n_samples):
if (n_samples > points.shape[0]):
warnings.warn('Number of samples is larger than number of points.')
if (type(points) is not np.ndarray):
raise ValueError('`points` should be a numpy array')
if ((len(points.shape) != 2) or (points.shape[1] != 3)):
... |
def batch_dot(a, b):
return torch.bmm(a.unsqueeze(1), b.unsqueeze((- 1))).squeeze((- 1))
|
class DeltaNetBase(torch.nn.Module):
def __init__(self, in_channels, conv_channels, mlp_depth, num_neighbors, grad_regularizer, grad_kernel_width, centralize_first=True):
"Classification of Point Clouds with DeltaConv.\n The architecture is based on the architecture used by DGCNN (https://dl.acm.o... |
class DeltaNetClassification(torch.nn.Module):
def __init__(self, in_channels, num_classes, conv_channels=[64, 64, 128, 256], num_neighbors=20, grad_regularizer=0.001, grad_kernel_width=1):
"Classification of Point Clouds with DeltaConv.\n The architecture is based on the architecture used by DGCN... |
class DeltaNetSegmentation(torch.nn.Module):
def __init__(self, in_channels, num_classes, conv_channels=[64, 128, 256], mlp_depth=2, embedding_size=1024, categorical_vector=False, num_neighbors=20, grad_regularizer=0.001, grad_kernel_width=1):
"Segmentation of Point Clouds with DeltaConv.\n The ar... |
class DeltaConv(torch.nn.Module):
' DeltaConv convolution from the paper \n "DeltaConv: Anisotropic Operators for Geometric Deep Learning on Point Clouds".\n This convolution learns a combination of operators from vector calculus:\n grad, co-grad, div, curl; and their compositions Laplacian and Hodge... |
def MLP(channels, bias=False, nonlin=LeakyReLU(negative_slope=0.2)):
return Seq(*[Seq(Lin(channels[(i - 1)], channels[i], bias=bias), BatchNorm1d(channels[i]), nonlin) for i in range(1, len(channels))])
|
def VectorMLP(channels, batchnorm=True):
return Seq(*[Seq(Lin(channels[(i - 1)], channels[i], bias=False), VectorNonLin(channels[i], batchnorm=(BatchNorm1d(channels[i]) if batchnorm else None))) for i in range(1, len(channels))])
|
class ScalarVectorMLP(torch.nn.Module):
def __init__(self, channels, nonlin=True, vector_stream=True):
super(ScalarVectorMLP, self).__init__()
self.scalar_mlp = MLP(channels, nonlin=(LeakyReLU(negative_slope=0.2) if nonlin else torch.nn.Identity()))
self.vector_mlp = None
if vecto... |
class ScalarVectorIdentity(torch.nn.Module):
def __init__(self, *args, **kwargs):
super(ScalarVectorIdentity, self).__init__()
def forward(self, input):
return input
|
class BatchNorm1d(torch.nn.Module):
'Convenience wrapper around BatchNorm1d that transforms an\n input tensor from [N x C] to [1 x C x N] so that it uses the faster\n batch-wise implementation of PyTorch.\n '
def __init__(self, in_channels, eps=1e-05, momentum=0.1, affine=True, track_running_stats=T... |
class VectorNonLin(torch.nn.Module):
'Applies a non-linearity to the norm of vector features.\n\n Args:\n in_channels (int): the number of channels in the input tensor.\n nonlin (Module, optional): non-linearity that will be applied\n to the features (default: ReLU).\n batchnorm... |
class GeodesicFPS(object):
'Sample points using geodesic furthest point samples.\n '
def __init__(self, n_samples=None, store_original=False):
self.n_samples = n_samples
self.store_original = store_original
return
def __call__(self, data):
if (self.n_samples is None):
... |
class NormalizeScale(object):
'Centers and normalizes node positions to the interval :math:`(-1, 1)`.\n '
def __init__(self, norm_ord=2, scaling_factor=None):
self.norm_ord = norm_ord
self.scaling_factor = scaling_factor
def __call__(self, data):
data.pos = (data.pos - ((torch... |
class RandomNormals(object):
'Jitters normals by a translation within a given interval.\n This is followed by normalization to ensure unit normals.\n\n Args:\n translate (sequence or float or int): Maximum translation in each\n dimension, defining the range\n :math:`(-\\mathrm{t... |
class RandomRotate(object):
'Rotates node positions around a specific axis by a randomly sampled\n angle within a given interval.\n\n Args:\n degrees (tuple or float): Rotation interval from which the rotation\n angle is sampled. If :obj:`degrees` is a number instead of a\n tupl... |
class RandomScale(object):
'Scales node positions by a randomly sampled factor :math:`s` within a\n given interval, *e.g.*, resulting in the transformation matrix\n\n .. math::\n \\begin{bmatrix}\n s & 0 & 0 \\\\\n 0 & s & 0 \\\\\n 0 & 0 & s \\\\\n \\end{bmatri... |
class RandomTranslateGlobal(object):
'Translates shapes by randomly sampled translation values\n within a given interval. This translation happens for the entire shape,\n retaining local relationships.\n\n Args:\n translate (sequence or float or int): Maximum translation in each\n dimen... |
class ModelNet(InMemoryDataset):
'The ModelNet10/40 datasets from the `"3D ShapeNets: A Deep\n Representation for Volumetric Shapes"\n <https://people.csail.mit.edu/khosla/papers/cvpr2015_wu.pdf>`_ paper,\n containing CAD models of 10 and 40 categories, respectively.\n\n .. note::\n\n Data obje... |
class ScanObjectNN(InMemoryDataset):
"The pre-processed ScanObjectNN dataset from the paper\n 'Revisiting Point Cloud Classification: A New Benchmark Dataset and Classification Model on Real-World Data'\n https://arxiv.org/pdf/1908.04616.pdf\n\n Args:\n root (string): Root directory where the data... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.