python_code stringlengths 0 4.04M | repo_name stringlengths 7 58 | file_path stringlengths 5 147 |
|---|---|---|
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
"""
See "Data Augmentation" tutorial for an overview of the system:
https://detectron2.readthedocs.io/tutorials/augmentation.html
"""
import numpy as np
import torch
import torch.nn.functional as F
from fvcore.transforms.transform import (
... | banmo-main | third_party/detectron2_old/detectron2/data/transforms/transform.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from .distributed_sampler import InferenceSampler, RepeatFactorTrainingSampler, TrainingSampler
from .grouped_batch_sampler import GroupedBatchSampler
__all__ = [
"GroupedBatchSampler",
"TrainingSampler",
"InferenceSampler",
"RepeatFactorTrainingSample... | banmo-main | third_party/detectron2_old/detectron2/data/samplers/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import numpy as np
from torch.utils.data.sampler import BatchSampler, Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It enforces that the batch only contain elements from the same group.
It... | banmo-main | third_party/detectron2_old/detectron2/data/samplers/grouped_batch_sampler.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import itertools
import math
from collections import defaultdict
from typing import Optional
import torch
from torch.utils.data.sampler import Sampler
from detectron2.utils import comm
class TrainingSampler(Sampler):
"""
In training, we only care about the "... | banmo-main | third_party/detectron2_old/detectron2/data/samplers/distributed_sampler.py |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import datetime
import itertools
import logging
import os
import tempfile
import time
from collections import Counter
import torch
from fvcore.common.checkpoint import PeriodicCheckpointer as _PeriodicCheckpointer
from fvcore.common.param_sched... | banmo-main | third_party/detectron2_old/detectron2/engine/hooks.py |
# Copyright (c) Facebook, Inc. and its affiliates.
from .launch import *
from .train_loop import *
__all__ = [k for k in globals().keys() if not k.startswith("_")]
# prefer to let hooks and defaults live in separate namespaces (therefore not in __all__)
# but still make them available here
from .hooks import *
from... | banmo-main | third_party/detectron2_old/detectron2/engine/__init__.py |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
import numpy as np
import time
import weakref
from typing import Dict, List, Optional
import torch
from torch.nn.parallel import DataParallel, DistributedDataParallel
import detectron2.utils.comm as comm
from detectron2.utils.ev... | banmo-main | third_party/detectron2_old/detectron2/engine/train_loop.py |
# Copyright (c) Facebook, Inc. and its affiliates.
import logging
from datetime import timedelta
import torch
import torch.distributed as dist
import torch.multiprocessing as mp
from detectron2.utils import comm
__all__ = ["DEFAULT_TIMEOUT", "launch"]
DEFAULT_TIMEOUT = timedelta(minutes=30)
def _find_free_port():
... | banmo-main | third_party/detectron2_old/detectron2/engine/launch.py |
# -*- coding: utf-8 -*-
# Copyright (c) Facebook, Inc. and its affiliates.
"""
This file contains components with some default boilerplate logic user may need
in training / testing. They will not work for everyone, but many users may find them useful.
The behavior of functions/classes in this file is subject to chang... | banmo-main | third_party/detectron2_old/detectron2/engine/defaults.py |
from __future__ import print_function
import sys
sys.path.insert(0,'../')
import cv2
import pdb
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
impo... | banmo-main | third_party/vcnplus/auto_gen.py |
"""
# ==============================
# flowlib.py
# library for optical flow processing
# Author: Ruoteng Li
# Date: 6th Aug 2016
# ==============================
"""
import png
from flowutils.util_flow import readPFM
import numpy as np
import matplotlib.colors as cl
import matplotlib.pyplot as plt
from PIL import Imag... | banmo-main | third_party/vcnplus/flowutils/flowlib.py |
"""
Taken from https://github.com/ClementPinard/FlowNetPytorch
"""
import pdb
import torch
import torch.nn.functional as F
def EPE(input_flow, target_flow, mask, sparse=False, mean=True):
#mask = target_flow[:,2]>0
target_flow = target_flow[:,:2]
EPE_map = torch.norm(target_flow-input_flow,2,1)
batch_... | banmo-main | third_party/vcnplus/flowutils/multiscaleloss.py |
import errno
import os
import shutil
import sys
import traceback
import zipfile
if sys.version_info[0] == 2:
import urllib2
else:
import urllib.request
def add_image(log,tag,img,step):
"""
for torch tensorboard
"""
timg = img[0]
timg = (timg-timg.min())/(timg.max()-timg.min())
if... | banmo-main | third_party/vcnplus/flowutils/io.py |
import math
import png
import struct
import array
import numpy as np
import cv2
import pdb
from io import *
UNKNOWN_FLOW_THRESH = 1e9;
UNKNOWN_FLOW = 1e10;
# Middlebury checks
TAG_STRING = 'PIEH' # use this when WRITING the file
TAG_FLOAT = 202021.25 # check for this when READING the file
def readPFM(file):
... | banmo-main | third_party/vcnplus/flowutils/util_flow.py |
banmo-main | third_party/vcnplus/flowutils/__init__.py | |
gpuid = 1
import pdb
import sys
import torch
import numpy as np
import cv2
def write_calib(K,bl,shape,maxd,path):
str1 = 'camera.A=[%f 0 %f; 0 %f %f; 0 0 1]'%(K[0,0], K[0,2], K[1,1],K[1,2])
str2 = 'camera.height=%d'%(shape[0])
str3 = 'camera.width=%d' %(shape[1])
str4 = 'camera.zmax=%f'%(maxd)
str5 ... | banmo-main | third_party/vcnplus/flowutils/dydepth.py |
import pdb
import math
import numpy as np
import cv2
import torch
import torch.nn.functional as F
import torch.nn as nn
def gaussian2D(shape, sigma=1):
m, n = [(ss - 1.) / 2. for ss in shape]
y, x = np.ogrid[-m:m+1,-n:n+1]
h = np.exp(-(x * x + y * y) / (2 * sigma * sigma))
h[h < np.finfo(h.dtype).eps ... | banmo-main | third_party/vcnplus/flowutils/detlib.py |
#! /usr/bin/env python2
"""
I/O script to save and load the data coming with the MPI-Sintel low-level
computer vision benchmark.
For more details about the benchmark, please visit www.mpi-sintel.de
CHANGELOG:
v1.0 (2015/02/03): First release
Copyright (c) 2015 Jonas Wulff
Max Planck Institute for Intelligent System... | banmo-main | third_party/vcnplus/flowutils/sintel_io.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torchvision.models as models
import torch
import torch.nn as nn
import os
from .networks.msra_resnet import get_pose_net
from .networks.dlav0 import get_pose_net as get_dlav0
from .networks.pose_dla_dcn... | banmo-main | third_party/vcnplus/models/det.py |
# ------------------------------------------------------------------------------
# Portions of this code are from
# CornerNet (https://github.com/princeton-vl/CornerNet)
# Copyright (c) 2018, University of Michigan
# Licensed under the BSD 3-Clause License
# -------------------------------------------------------------... | banmo-main | third_party/vcnplus/models/det_losses.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
def _sigmoid(x):
y = torch.clamp(x.sigmoid_(), min=1e-4, max=1-1e-4)
return y
def _gather_feat(feat, ind, mask=None):
dim = feat.size(2)
ind = ind.unsqueeze(2)... | banmo-main | third_party/vcnplus/models/det_utils.py |
banmo-main | third_party/vcnplus/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).
This file incorporates work covered by the following copyright and permission notice:
Copyright (c) 2018 Ignacio Rocco
Permission is here... | banmo-main | third_party/vcnplus/models/feature_extraction.py |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.utils.data
from torch.autograd import Variable
import torch.nn.functional as F
import math
import numpy as np
import pdb
#import kornia
class residualBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, n_filters,... | banmo-main | third_party/vcnplus/models/submodule.py |
import pdb
import torch.nn as nn
import math
import torch
from torch.nn.parameter import Parameter
import torch.nn.functional as F
from torch.nn import Module
from torch.nn.modules.conv import _ConvNd
from torch.nn.modules.utils import _quadruple
from torch.autograd import Variable
from torch.nn import Conv2d
def conv... | banmo-main | third_party/vcnplus/models/conv4d.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
import pdb
import time
import cv2
from .submodule import pspnet, bfmodule, bfmodule_feat, conv, compute_geo_costs, get_skew_mat, get_intrinsics, F_ngransac
from .conv4d import sepConv4d... | banmo-main | third_party/vcnplus/models/VCNplus.py |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Dequan Wang and Xingyi Zhou
# ------------------------------------------------------------------------------
from __f... | banmo-main | third_party/vcnplus/models/networks/resnet_dcn.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import math
import logging
import numpy as np
from os.path import join
import torch
from torch import nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
from .DCNv2.DCN.dcn... | banmo-main | third_party/vcnplus/models/networks/pose_dla_dcn.py |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# Modified by Xingyi Zhou
# ------------------------------------------------------------------------------
from __future__ import a... | banmo-main | third_party/vcnplus/models/networks/msra_resnet.py |
# ------------------------------------------------------------------------------
# This code is base on
# CornerNet (https://github.com/princeton-vl/CornerNet)
# Copyright (c) 2018, University of Michigan
# Licensed under the BSD 3-Clause License
# ----------------------------------------------------------------------... | banmo-main | third_party/vcnplus/models/networks/large_hourglass.py |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from os.path import join
import torch
from torch import nn
import torch.utils.model_zoo as model_zoo
import numpy as np
BatchNorm = nn.BatchNorm2d
d... | banmo-main | third_party/vcnplus/models/networks/dlav0.py |
#!/usr/bin/env python
import os
import glob
import torch
from torch.utils.cpp_extension import CUDA_HOME
from torch.utils.cpp_extension import CppExtension
from torch.utils.cpp_extension import CUDAExtension
from setuptools import find_packages
from setuptools import setup
requirements = ["torch", "torchvision"]
... | banmo-main | third_party/vcnplus/models/networks/DCNv2/setup.py |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import gradcheck
from dcn_v2 import dcn_v2_conv, DCNv2, DCN
from dcn_v2 import dcn_v2_pooling, DCNv2Pooling, DCNPooling
... | banmo-main | third_party/vcnplus/models/networks/DCNv2/DCN/testcpu.py |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import time
import torch
import torch.nn as nn
from torch.autograd import gradcheck
from dcn_v2 import dcn_v2_conv, DCNv2, DCN
from dcn_v2 import dcn_v2_pooling, DCNv2Pooling, DCNPooling
... | banmo-main | third_party/vcnplus/models/networks/DCNv2/DCN/testcuda.py |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import math
import torch
from torch import nn
from torch.autograd import Function
from torch.nn.modules.utils import _pair
from torch.autograd.function import once_differentiable
import _... | banmo-main | third_party/vcnplus/models/networks/DCNv2/DCN/dcn_v2.py |
from .dcn_v2 import *
| banmo-main | third_party/vcnplus/models/networks/DCNv2/DCN/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import sys
sys.path.insert(0,'third_party')
sys.path.insert(0,'./')
import numpy as np
import trimesh
import torch
import cv2
import pdb
from scipy.spatial.transform import Rotation as R
from utils.io import mkdir_p
import argparse
parser = argpa... | banmo-main | scripts/misc/generate_traj.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# python scripts/add_cam_noise.py cam-files/cse-ama/ 30
import cv2
import numpy as np
import pdb
import sys
import glob
import os
cam_dir=sys.argv[1]
std_rot=float(sys.argv[2]) # deg
seqname=cam_dir.split('/')[-2]
std=np.pi/180*std_rot
odir='%s... | banmo-main | scripts/misc/add_cam_noise.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# from: https://gist.github.com/adewes/5884820
import random
def get_random_color(pastel_factor = 0.5):
return [(x+pastel_factor)/(1.0+pastel_factor) for x in [random.uniform(0,1.0) for i in [1,2,3]]]
def color_distance(c1,c2):
return sum... | banmo-main | scripts/misc/random_colors.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
os.environ["PYOPENGL_PLATFORM"] = "egl" #opengl seems to only work with TPU
sys.path.insert(0,'third_party')
import subprocess
import imageio
import glob
from utils.io ... | banmo-main | scripts/visualize/render_vis.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
os.environ["PYOPENGL_PLATFORM"] = "egl" #opengl seems to only work with TPU
curr_dir = os.path.abspath(os.getcwd())
sys.path.insert(0,curr_dir)
import pdb
import glob
imp... | banmo-main | scripts/visualize/render_root_txt.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import sys, os
import pdb
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
os.environ["PYOPENGL_PLATFORM"] = "egl" #opengl seems to only work with TPU
curr_dir = os.path.abspath(os.getcwd())
sys.path.insert(0,curr_dir)
import subproc... | banmo-main | scripts/visualize/render_root.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
"""
bash scripts/render_nvs.sh
"""
from absl import flags, app
import sys
sys.path.insert(0,'')
sys.path.insert(0,'third_party')
import numpy as np
import torch
import os
import glob
import pdb
import cv2
import trimesh
from scipy.spatial.transfor... | banmo-main | scripts/visualize/nvs.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
"""
bash scripts/render_nvs.sh
"""
from absl import flags, app
import sys
sys.path.insert(0,'')
sys.path.insert(0,'third_party')
import numpy as np
import torch
import os
import glob
import pdb
import cv2
import trimesh
from scipy.spatial.transfor... | banmo-main | scripts/visualize/nvs_iter.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# TODO: pass ft_cse to use fine-tuned feature
# TODO: pass fine_steps -1 to use fine samples
from absl import flags, app
import sys
sys.path.insert(0,'')
sys.path.insert(0,'third_party')
import numpy as np
from matplotlib import pyplot as plt
impor... | banmo-main | scripts/visualize/match.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
"""
python scripts/ama-process/ama2davis.py --path ./database/T_swing/
"""
import pdb
import cv2
import numpy as np
import os
import glob
import argparse
import sys
from shutil import copyfile
sys.path.insert(0,'')
from utils.io import mkdir_p
p... | banmo-main | scripts/ama-process/ama2davis.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import numpy as np
import cv2
import pdb
pmat = np.loadtxt('/private/home/gengshany/data/AMA/T_swing/calibration/Camera1.Pmat.cal')
K,R,T,_,_,_,_=cv2.decomposeProjectionMatrix(pmat)
print(K/K[-1,-1])
print(R)
print(T/T[-1])
pdb.set_trace()
| banmo-main | scripts/ama-process/read_cam.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
import sys
sys.path.insert(0,'third_party')
sys.path.insert(0,'./')
import numpy as np
import trimesh
import torch
import cv2
import pdb
from scipy.spatial.transform import Rotation as R
from nnutils.geom_utils import obj_to_cam, pinhole_cam, ren... | banmo-main | scripts/synthetic/render_synthetic.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# python scripts/eval_root.py cam-files/adult7-b25/ cam-files/adult-masked-cam/ 1000
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(sys.path[0])))
os.environ["PYOPENGL_PLATFORM"] = "egl" #opengl seems to only work with TPU
curr_dir... | banmo-main | scripts/eval/eval_root.py |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import pdb
import os.path as osp
import sys
sys.path.insert(0,'third_party')
import numpy as np
from absl import flags, app
import torc... | banmo-main | dataloader/vidbase.py |
banmo-main | dataloader/__init__.py | |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os.path as osp
import numpy as np
import scipy.io as sio
from absl import flags, app
import random
import torch
from torch.utils... | banmo-main | dataloader/frameloader.py |
"""
# Copyright (c) Facebook, Inc. and its 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 setup, find_packages
setup(
name='clutrr',
version='1.0.0',
description='Comp... | clutrr-main | setup.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# Clean the templates from mturk annotated data
# Input = mturk annotated file (amt_mturk.csv)
# Output = placeho... | clutrr-main | clutrr/template_mturk.py |
clutrr-main | clutrr/__init__.py | |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# Generate story-summary pairs
from clutrr.actors.ancestry import Ancestry
from clutrr.relations.builder import ... | clutrr-main | clutrr/generator.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
## Note: With these current args (max level 3, min_child = max_child = 4), its only possible to generate
## upto ... | clutrr-main | clutrr/args.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# main file which defines the tasks
from clutrr.args import get_args
from clutrr.generator import generate_rows
f... | clutrr-main | clutrr/main.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# Main Puzzle class which maintains the state of a single puzzle
import uuid
import random
from clutrr.utils.util... | clutrr-main | clutrr/relations/puzzle.py |
clutrr-main | clutrr/relations/__init__.py | |
"""
# Copyright (c) Facebook, Inc. and its 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 copy
import random
class Templator:
"""
Templator base class
"""
def __init__(self, templ... | clutrr-main | clutrr/relations/templator.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# New builder class which makes use of our new data generation
import random
import itertools as it
import copy
... | clutrr-main | clutrr/relations/builder.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# File which was used in data collection from AMT using ParlAI-Mturk.
# Wrapper to communicate with backend datab... | clutrr-main | clutrr/utils/data_backend.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# Split the test files into their own task specific files
# Not required in actual data generation
import pandas ... | clutrr-main | clutrr/utils/test_splitter.py |
"""
# Copyright (c) Facebook, Inc. and its 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.
#
"""
# file to create and maintain an index.html file which will contain a table of datasets for easy maintainance
imp... | clutrr-main | clutrr/utils/web.py |
clutrr-main | clutrr/utils/__init__.py | |
"""
# Copyright (c) Facebook, Inc. and its 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 itertools as it
import numpy as np
import csv
import pandas as pd
import random
def pairwise(iterable):
... | clutrr-main | clutrr/utils/utils.py |
clutrr-main | clutrr/actors/__init__.py | |
"""
# Copyright (c) Facebook, Inc. and its 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 numpy as np
import names
import copy
import random
from clutrr.actors.actor import Actor, Entity
from clut... | clutrr-main | clutrr/actors/ancestry.py |
"""
# Copyright (c) Facebook, Inc. and its 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 random
class Actor:
"""
male or female actor
"""
def __init__(self, gender='male', name=... | clutrr-main | clutrr/actors/actor.py |
"""
# Copyright (c) Facebook, Inc. and its 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 os
import json
import yaml
class Store:
def __init__(self,args):
attribute_store = args.attri... | clutrr-main | clutrr/store/store.py |
clutrr-main | clutrr/store/__init__.py | |
import os
import re
import setuptools
class CleanCommand(setuptools.Command):
"""Custom clean command to tidy up the project root."""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
os.system("rm -vrf ./build ./dist ... | metal-master | setup.py |
import numpy as np
import sklearn.metrics as skm
import torch
from metal.utils import arraylike_to_numpy, pred_to_prob
def accuracy_score(gold, pred, ignore_in_gold=[], ignore_in_pred=[]):
"""
Calculate (micro) accuracy.
Args:
gold: A 1d array-like of gold labels
pred: A 1d array-like of ... | metal-master | metal/metrics.py |
import os
import random
import warnings
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from scipy.sparse import issparse
from torch.utils.data import DataLoader, Dataset, TensorDataset
from metal.analysis import confusion_matrix
from metal.logging import Checkpointer, Logger, LogWri... | metal-master | metal/classifier.py |
from collections import Counter, defaultdict
import numpy as np
import scipy.sparse as sparse
from pandas import DataFrame, Series
from metal.utils import arraylike_to_numpy
############################################################
# Label Matrix Diagnostics
######################################################... | metal-master | metal/analysis.py |
from .end_model import EndModel
from .label_model import LabelModel, MajorityClassVoter, MajorityLabelVoter, RandomVoter
from .tuners import RandomSearchTuner
__all__ = [
"EndModel",
"LabelModel",
"MajorityClassVoter",
"MajorityLabelVoter",
"RandomVoter",
"RandomSearchTuner",
]
__version__ = "... | metal-master | metal/__init__.py |
import argparse
import copy
import random
import warnings
from collections import defaultdict
import numpy as np
import torch
from scipy.sparse import issparse
from torch.utils.data import Dataset
class MetalDataset(Dataset):
"""A dataset that group each item in X with its label from Y
Args:
X: an n... | metal-master | metal/utils.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
from metal.classifier import Classifier
from metal.end_model.em_defaults import em_default_config
from metal.end_model.identity_module import IdentityModule
from metal.end_model.loss import SoftCrossEntropyLoss
from metal.utils import MetalDataset, pre... | metal-master | metal/end_model/end_model.py |
import torch.nn as nn
class IdentityModule(nn.Module):
"""A default identity input module that simply passes the input through."""
def __init__(self):
super().__init__()
def reset_parameters(self):
pass
def forward(self, x):
return x
| metal-master | metal/end_model/identity_module.py |
from .end_model import EndModel
from .identity_module import IdentityModule
from .logreg import LogisticRegression
from .loss import SoftCrossEntropyLoss
__all__ = ["EndModel", "IdentityModule", "LogisticRegression", "SoftCrossEntropyLoss"]
| metal-master | metal/end_model/__init__.py |
import torch
import torch.nn as nn
import torch.nn.functional as F
class SoftCrossEntropyLoss(nn.Module):
"""Computes the CrossEntropyLoss while accepting probabilistic (float) targets
Args:
weight: a tensor of relative weights to assign to each class.
the kwarg name 'weight' is used to m... | metal-master | metal/end_model/loss.py |
from metal.end_model import EndModel
from metal.utils import recursive_merge_dicts
class LogisticRegression(EndModel):
"""A logistic regression classifier for a single-task problem"""
def __init__(self, input_dim, output_dim=2, **kwargs):
layer_out_dims = [input_dim, output_dim]
overrides = {... | metal-master | metal/end_model/logreg.py |
em_default_config = {
# GENERAL
"seed": None,
"verbose": True,
"show_plots": True,
# Network
# The first value is the output dim of the input module (or the sum of
# the output dims of all the input modules if multitask=True and
# multiple input modules are provided). The last value is t... | metal-master | metal/end_model/em_defaults.py |
import time
from collections import defaultdict
class Logger(object):
"""Tracks when it is time to calculate train/valid metrics and logs them"""
def __init__(self, config, batches_per_epoch, writer={}, verbose=True):
# Strip split name from config keys
self.config = config
self.write... | metal-master | metal/mmtl/mmtl_logger.py |
from abc import ABC
import torch.nn.functional as F
from metal.end_model import IdentityModule
from metal.mmtl.modules import MetalModule, MetalModuleWrapper
from metal.mmtl.scorer import Scorer
class Task(ABC):
"""A abstract class for tasks in MMTL Metal Model.
Args:
name: (str) The name of the ta... | metal-master | metal/mmtl/task.py |
from collections import defaultdict
import numpy as np
import torch
import torch.nn as nn
from metal.utils import move_to_device, recursive_merge_dicts, set_seed
model_defaults = {
"seed": None,
"device": 0, # gpu id (int) or -1 for cpu
"verbose": True,
"fp16": False,
"model_weights": None, # t... | metal-master | metal/mmtl/metal_model.py |
import random
from abc import ABC, abstractmethod
class PayloadScheduler(ABC):
"""Returns batches from multiple payloads in some order for MTL training"""
def __init__(self, model, payloads, split, **kwargs):
pass
@abstractmethod
def get_batches(self, payloads, split, **kwargs):
"""R... | metal-master | metal/mmtl/task_scheduler.py |
from .metal_model import MetalModel
from .payload import Payload
__all__ = ["Payload", "MetalModel"]
| metal-master | metal/mmtl/__init__.py |
import torch
from metal.mmtl.data import MmtlDataLoader, MmtlDataset
class Payload(object):
"""A bundle of data_loaders...
Args:
name: the name of the payload (i.e., the name of the instance set)
data_loaders: A DataLoader to feed through the network
The DataLoader should wrap an... | metal-master | metal/mmtl/payload.py |
import numpy as np
import torch.nn.functional as F
from metal.end_model import IdentityModule
from metal.mmtl.scorer import Scorer
from metal.mmtl.task import Task
def tokenwise_ce_loss(out, Y_gold):
"""Compute the token-averaged cross-entropy loss
We assume the standard MeTaL convention of no 0 labels in Y... | metal-master | metal/mmtl/token_task.py |
import torch.nn as nn
class MetalModule(nn.Module):
"""An abstract class of a module that accepts and returns a dict"""
def __init__(self):
super().__init__()
class MetalModuleWrapper(nn.Module):
def __init__(self, module):
super().__init__()
self.module = module
def forwar... | metal-master | metal/mmtl/modules.py |
import copy
import os
import warnings
from collections import defaultdict
from pprint import pprint
from shutil import copy2
import dill
import numpy as np
import torch
import torch.optim as optim
from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors
from metal.logging import Checkpointer, LogWrit... | metal-master | metal/mmtl/trainer.py |
from collections import defaultdict
import torch
from torch.utils.data import DataLoader, Dataset
from metal.utils import padded_tensor
class MmtlDataset(Dataset):
"""A pairing of data with one or more fields to one or more label sets
Args:
X: Instances. If X is a dict, it should be in the form {fi... | metal-master | metal/mmtl/data.py |
from metal.metrics import METRICS as STANDARD_METRICS, metric_score
class Scorer(object):
"""
DESIGN:
- A Scorer is a bundle of metrics; it defines what metrics _can_ be calculated on a
given task (may be able to use smart defaults based on the Task subclass; e.g.,
classification comes with many n... | metal-master | metal/mmtl/scorer.py |
import math
import numpy as np
from metal.tuners.tuner import ModelTuner
class HyperbandTuner(ModelTuner):
"""Performs hyperparameter search according to the Hyperband algorithm
Reference: (https://arxiv.org/pdf/1603.06560.pdf)
Args:
model: (nn.Module) The model class to train (uninitiated)
... | metal-master | metal/tuners/hyperband_tuner.py |
from .hyperband_tuner import HyperbandTuner
from .random_tuner import RandomSearchTuner
__all__ = ["HyperbandTuner", "RandomSearchTuner"]
| metal-master | metal/tuners/__init__.py |
from metal.tuners.tuner import ModelTuner
class RandomSearchTuner(ModelTuner):
"""A tuner for models
Args:
model: (nn.Module) The model class to train (uninitiated)
log_dir: The directory in which to save intermediate results
If no log_dir is given, the model tuner will attempt to... | metal-master | metal/tuners/random_tuner.py |
import json
import os
import pickle
import random
from itertools import cycle, product
from time import strftime, time
import numpy as np
import pandas as pd
from metal.utils import recursive_merge_dicts
class ModelTuner(object):
"""A tuner for models
Args:
model_class: (nn.Module class) The model ... | metal-master | metal/tuners/tuner.py |
metal-master | metal/contrib/__init__.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.