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 |
|---|---|---|---|---|---|---|
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/data/datasets/coco.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torchvision
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
class COCODataset(torchvision.datasets.coco.CocoDetection):
def __ini... | 2,363 | 34.818182 | 89 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/data/samplers/grouped_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import itertools
import torch
from torch.utils.data.sampler import BatchSampler
from torch.utils.data.sampler import Sampler
class GroupedBatchSampler(BatchSampler):
"""
Wraps another sampler to yield a mini-batch of indices.
It enfo... | 4,844 | 41.130435 | 88 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/data/samplers/iteration_based_batch_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch.utils.data.sampler import BatchSampler
class IterationBasedBatchSampler(BatchSampler):
"""
Wraps a BatchSampler, resampling from it until
a specified number of iterations have been sampled
"""
def __init__(self, ba... | 1,164 | 35.40625 | 71 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/data/samplers/distributed.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# Code is copy-pasted exactly as in torch.utils.data.distributed,
# with a modification in the import to use the deprecated backend
# FIXME remove this once c10d fixes the bug it has
import math
import torch
import torch.distributed as dist
from to... | 2,777 | 38.126761 | 86 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/data/transforms/transforms.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import random
import cv2
import numpy as np
from PIL import Image
from shapely import affinity
from shapely.geometry import Polygon
from torchvision.transforms import functional as F
class Compose(object):
def __init__(self, transforms):
... | 12,621 | 32.480106 | 83 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/matcher.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
class Matcher(object):
"""
This class assigns to each predicted "element" (e.g., a box) a ground-truth
element. Each predicted element will have exactly zero or one matches; each
ground-truth element may be assigned t... | 4,845 | 44.28972 | 88 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/make_layers.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Miscellaneous utility functions
"""
import torch
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.config import cfg
from maskrcnn_benchmark.layers import Conv2d
from maskrcnn_benchmark.modeling.poolers import P... | 3,557 | 27.926829 | 78 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/utils.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Miscellaneous utility functions
"""
import torch
def cat(tensors, dim=0):
"""
Efficient version of torch.cat that avoids a copy if there is only a single element in a list
"""
assert isinstance(tensors, (list, tuple))
if ... | 404 | 22.823529 | 97 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/poolers.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.layers import ROIAlign
from .utils import cat
class LevelMapper(object):
"""Determine which FPN level each RoI in a set of RoIs should map... | 4,171 | 32.645161 | 90 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/balanced_positive_negative_sampler.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
# TODO
class BalancedPositiveNegativeSampler(object):
"""
This class samples batches,
ensuring that they contain a fixed proportion of positives
"""
def __init__(self, batch_size_per_image, positive_fraction):
... | 2,678 | 37.271429 | 83 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/box_coder.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import torch
class BoxCoder(object):
"""
This class encodes and decodes a set of bounding boxes into
the representation used for training the regressors.
"""
def __init__(self, weights, bbo... | 3,462 | 33.979798 | 86 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/backbone/resnet.py | # # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# """
# Variant of the resnet module that takes cfg as an argument.
# Example usage. Strings may be specified in the config file.
# model = ResNet(
# "StemWithFixedBatchNorm",
# "BottleneckWithFixedBatchNorm",
# "ResNe... | 24,619 | 30.808786 | 90 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/backbone/backbone.py | # # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# from collections import OrderedDict
# from torch import nn
# from . import fpn as fpn_module
# from . import resnet
# def build_resnet_backbone(cfg):
# body = resnet.ResNet(cfg)
# model = nn.Sequential(OrderedDict([("body", body)]))... | 4,395 | 32.30303 | 89 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/backbone/resnet34.py | import torch
import torch.nn.functional as F
from torch import nn
import math
from maskrcnn_benchmark.layers import FrozenBatchNorm2d
from maskrcnn_benchmark.layers import Conv2d
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return Conv2d(in_planes, out_planes, kernel_size=3, stri... | 2,729 | 26.857143 | 67 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/backbone/fpn.py | # #!/usr/bin/env python3
# # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# import torch
# import torch.nn.functional as F
# from torch import nn
# class FPN(nn.Module):
# """
# Module that adds FPN on top of a list of feature maps.
# The feature maps are currently supposed to be ... | 7,331 | 40.659091 | 88 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/detector/generalized_rcnn.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Implements the Generalized R-CNN framework
"""
import torch
from torch import nn
from maskrcnn_benchmark.structures.image_list import to_image_list
from ..backbone import build_backbone
from ..rpn.rpn import build_rpn
... | 3,837 | 35.903846 | 101 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/segmentation/inference.py | #!/usr/bin/env python3
import numpy as np
import torch
import cv2
import pyclipper
from shapely.geometry import Polygon
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist, cat_boxlist_gt
from maskrcnn_benchmark.structures.boxlist_ops import ... | 15,089 | 38.815303 | 148 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/segmentation/loss.py | #!/usr/bin/env python3
"""
This file contains specific functions for computing losses on the SEG
file
"""
import torch
class SEGLossComputation(object):
"""
This class computes the SEG loss.
"""
def __init__(self, cfg):
self.eps = 1e-6
self.cfg = cfg
def __call__(self, preds, ta... | 2,122 | 31.661538 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/segmentation/segmentation.py | #!/usr/bin/env python3
import torch
from torch import nn
from .inference import make_seg_postprocessor
from .loss import make_seg_loss_evaluator
import time
def conv3x3(in_planes, out_planes, stride=1, has_bias=False):
"3x3 convolution with padding"
return nn.Conv2d(
in_planes, out_planes, kernel_siz... | 6,573 | 34.923497 | 110 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/rpn/inference.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import cat_boxlist
from maskrcnn_benchmark... | 7,490 | 35.720588 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/rpn/anchor_generator.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import math
import numpy as np
import torch
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
class BufferList(nn.Module):
"""
Similar to nn.ParameterList, but for buffers
"""
def __init__(self... | 8,907 | 32.742424 | 88 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/rpn/loss.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
This file contains specific functions for computing losses on the RPN
file
"""
import torch
from torch.nn import functional as F
from ..balanced_positive_negative_sampler import BalancedPositiveNegativeSampler
from ..ut... | 6,123 | 39.026144 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/rpn/rpn.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.modeling.box_coder import BoxCoder
from .loss import make_rpn_loss_evaluator
from .anchor_generator import make_anchor_generator
from ... | 5,453 | 37.680851 | 88 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/roi_heads.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .box_head.box_head import build_roi_box_head
from .mask_head.mask_head import build_roi_mask_head
class CombinedROIHeads(torch.nn.ModuleDict):
"""
Combines a set of individual heads (for box predi... | 2,237 | 36.932203 | 86 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/mask_head/inference.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import torch
from PIL import Image
from torch import nn
import cv2
from torch.nn import functional as F
from maskrcnn_benchmark.structures.bounding_box import BoxList
# TODO check if want to return a single BoxList or a composi... | 8,971 | 34.184314 | 209 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_mask_feature_extractors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
from torch.nn import functional as F
from ..box_head.roi_box_feature_extractors import ResNet50Conv5ROIFeatureExtractor
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_benchmark.layers import Conv2d
clas... | 2,762 | 36.849315 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/mask_head/loss.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
# from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.modeling.utils import cat
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_iou
from to... | 8,431 | 34.428571 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_seq_predictors.py | # Written by Minghui Liao
import math
import random
import numpy as np
import torch
from maskrcnn_benchmark.utils.chars import char2num, num2char
from torch import nn
from torch.nn import functional as F
gpu_device = torch.device("cuda")
cpu_device = torch.device("cpu")
def reduce_mul(l):
out = 1.0
for x i... | 16,629 | 42.534031 | 134 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/mask_head/roi_mask_predictors.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from maskrcnn_benchmark.layers import Conv2d, ConvTranspose2d
from torch import nn
from torch.nn import functional as F
from .roi_seq_predictors import make_roi_seq_predictor
class MaskRCNNC4Predictor(nn.Module):
def __init__(self, cfg):
... | 11,124 | 40.356877 | 122 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/mask_head/mask_head.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from maskrcnn_benchmark.modeling.matcher import Matcher
from maskrcnn_benchmark.modeling.utils import cat
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmar... | 27,041 | 44.679054 | 160 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/box_head/inference.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
import torch.nn.functional as F
from torch import nn
from maskrcnn_benchmark.structures.bounding_box import BoxList
from maskrcnn_benchmark.structures.boxlist_ops import boxlist_nms
from maskrcnn_benchmark.struc... | 7,693 | 42.468927 | 148 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/box_head/roi_box_feature_extractors.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from torch import nn
from torch.nn import functional as F
from maskrcnn_benchmark.modeling.backbone import resnet
from maskrcnn_benchmark.modeling.poolers import Pooler
from maskrcnn_benchmark.modeling.utils imp... | 6,713 | 38.263158 | 145 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/box_head/box_head.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from .inference import make_roi_box_post_processor
from .loss import make_roi_box_loss_evaluator
from .roi_box_feature_extractors import make_roi_box_feature_extractor
from .roi_box_predictors import make_roi_bo... | 3,104 | 35.529412 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/box_head/loss.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from maskrcnn_benchmark.layers import smooth_l1_loss
from maskrcnn_benchmark.modeling.balanced_positive_negative_sampler import (
BalancedPositiveNegativeSampler,
)
from maskrcnn_benchmark.modeling.box_coder ... | 7,135 | 37.572973 | 91 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/modeling/roi_heads/box_head/roi_box_predictors.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from torch import nn
class FastRCNNPredictor(nn.Module):
def __init__(self, config, pretrained=None):
super(FastRCNNPredictor, self).__init__()
stage_index = 4
stage2_relative_factor = 2 ** (sta... | 2,501 | 33.273973 | 76 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/structures/image_list.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
class ImageList(object):
"""
Structure that holds a list of images (of possibly
varying sizes) as a single tensor.
This works by padding the images to the same size,
and storing in a field the original sizes of ea... | 4,459 | 35.859504 | 87 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/structures/segmentation_mask.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import cv2
import numpy as np
import pycocotools.mask as mask_utils
import torch
from maskrcnn_benchmark.utils.chars import char2num
import pyclipper
# from PIL import Image
from shapely import affinity
from shapely.geometry ... | 27,175 | 34.431551 | 161 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/structures/bounding_box.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import numpy as np
import torch
# from shapely import affinity
# from shapely.geometry import box
# transpose
FLIP_LEFT_RIGHT = 0
FLIP_TOP_BOTTOM = 1
class BoxList(object):
"""
This class represents a set of bounding boxes.
The boun... | 11,570 | 35.617089 | 88 | py |
MaskTextSpotterV3 | MaskTextSpotterV3-master/maskrcnn_benchmark/structures/boxlist_ops.py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import torch
from maskrcnn_benchmark.layers import nms as _box_nms
from .bounding_box import BoxList
from maskrcnn_benchmark.structures.segmentation_mask import SegmentationMask
import numpy as np
import shapely
from shapely... | 7,393 | 30.46383 | 90 | py |
HASOC-2021---Hate-Speech-Detection | HASOC-2021---Hate-Speech-Detection-main/main.py | import getopt
import sys
import tensorflow as tf
import os
import json
import numpy as np
import file_utils
from datetime import datetime
import matplotlib.pyplot as plt
import h5py
from bert.tokenization.bert_tokenization import FullTokenizer
from bert import BertModelLayer
from bert.loader import StockBertConfig, map... | 7,085 | 37.934066 | 179 | py |
HASOC-2021---Hate-Speech-Detection | HASOC-2021---Hate-Speech-Detection-main/data_loader.py | import pandas as pd
import numpy as np
from bert.tokenization.bert_tokenization import FullTokenizer
from ekphrasis.classes.preprocessor import TextPreProcessor
from ekphrasis.classes.tokenizer import SocialTokenizer
from ekphrasis.dicts.emoticons import emoticons
from tensorflow.keras.preprocessing.text import Tokeniz... | 10,369 | 31.507837 | 144 | py |
HASOC-2021---Hate-Speech-Detection | HASOC-2021---Hate-Speech-Detection-main/models.py | import tensorflow as tf
import numpy as np
from bert import BertModelLayer
from bert.loader import StockBertConfig, map_stock_config_to_params, load_stock_weights
from tensorflow import keras
from tensorflow.keras import layers
class MultiHeadSelfAttention(layers.Layer):
def __init__(self, embed_dim, num_heads=8):... | 17,504 | 41.799511 | 166 | py |
steer | steer-master/ffjord/train_vae_flow.py | # !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import time
import torch
import torch.utils.data
import torch.optim as optim
import numpy as np
import math
import random
import os
import datetime
import lib.utils as utils
import lib.layers.odefunc as odefunc
imp... | 14,613 | 39.707521 | 124 | py |
steer | steer-master/ffjord/train_toy.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse
import os
import time
import torch
import torch.optim as optim
import lib.toy_data as toy_data
import lib.utils as utils
from lib.visualize_flow import visualize_transform
import lib.layers.odefunc as odefunc
from train_misc imp... | 9,288 | 39.038793 | 119 | py |
steer | steer-master/ffjord/train_img2d.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse
import os
import time
import torch
import torch.optim as optim
import lib.utils as utils
from lib.visualize_flow import visualize_transform
import lib.layers.odefunc as odefunc
from train_misc import standard_normal_logprob
from... | 9,789 | 37.543307 | 119 | py |
steer | steer-master/ffjord/train_cnf.py | import argparse
import os
import time
import numpy as np
import torch
import torch.optim as optim
import torchvision.datasets as dset
import torchvision.transforms as tforms
from torchvision.utils import save_image
import lib.layers as layers
import lib.utils as utils
import lib.odenvp as odenvp
import lib.multiscale... | 18,212 | 39.654018 | 119 | py |
steer | steer-master/ffjord/train_discrete_tabular.py | import argparse
import os
import time
import torch
import lib.utils as utils
from lib.custom_optimizers import Adam
import lib.layers as layers
import datasets
from train_misc import standard_normal_logprob, count_parameters
parser = argparse.ArgumentParser()
parser.add_argument(
'--data', choices=['power', 'g... | 8,301 | 34.177966 | 120 | py |
steer | steer-master/ffjord/train_tabular.py | import argparse
import os
import time
import torch
import lib.utils as utils
import lib.layers.odefunc as odefunc
from lib.custom_optimizers import Adam
import datasets
from train_misc import standard_normal_logprob
from train_misc import set_cnf_options, count_nfe, count_parameters, count_total_time
from train_mis... | 12,249 | 38.90228 | 120 | py |
steer | steer-master/ffjord/train_discrete_toy.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import argparse
import os
import time
import torch
import torch.optim as optim
import lib.layers as layers
import lib.toy_data as toy_data
import lib.utils as utils
from lib.visualize_flow import visualize_transform
from train_misc import stand... | 6,334 | 32.877005 | 119 | py |
steer | steer-master/ffjord/vae_lib/models/VAE.py | from __future__ import print_function
import torch
import torch.nn as nn
import vae_lib.models.flows as flows
from vae_lib.models.layers import GatedConv2d, GatedConvTranspose2d
class VAE(nn.Module):
"""
The base VAE class containing gated convolutional encoder and decoder architecture.
Can be used as a ... | 25,211 | 33.255435 | 120 | py |
steer | steer-master/ffjord/vae_lib/models/CNFVAE.py | import torch
import torch.nn as nn
from train_misc import build_model_tabular
import lib.layers as layers
from .VAE import VAE
import lib.layers.diffeq_layers as diffeq_layers
from lib.layers.odefunc import NONLINEARITIES
from torchdiffeq import odeint_adjoint as odeint
def get_hidden_dims(args):
return tuple(ma... | 14,405 | 33.881356 | 116 | py |
steer | steer-master/ffjord/vae_lib/models/layers.py | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import numpy as np
import torch.nn.functional as F
class Identity(nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
class GatedConv2d(nn.Module):
def __init__(self... | 7,128 | 32.947619 | 115 | py |
steer | steer-master/ffjord/vae_lib/models/flows.py | """
Collection of flow strategies
"""
from __future__ import print_function
import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
from vae_lib.models.layers import MaskedConv2d, MaskedLinear
class Planar(nn.Module):
"""
PyTorch implementation of planar flows... | 9,939 | 32.133333 | 118 | py |
steer | steer-master/ffjord/vae_lib/optimization/loss.py | from __future__ import print_function
import numpy as np
import torch
import torch.nn as nn
from vae_lib.utils.distributions import log_normal_diag, log_normal_standard, log_bernoulli
import torch.nn.functional as F
def binary_loss_function(recon_x, x, z_mu, z_var, z_0, z_k, ldj, beta=1.):
"""
Computes the b... | 10,566 | 37.849265 | 116 | py |
steer | steer-master/ffjord/vae_lib/optimization/training.py | from __future__ import print_function
import time
import torch
from vae_lib.optimization.loss import calculate_loss
from vae_lib.utils.visual_evaluation import plot_reconstructions
from vae_lib.utils.log_likelihood import calculate_likelihood
import numpy as np
from train_misc import count_nfe, override_divergence_fn... | 5,518 | 31.087209 | 120 | py |
steer | steer-master/ffjord/vae_lib/utils/distributions.py | from __future__ import print_function
import torch
import torch.utils.data
import math
MIN_EPSILON = 1e-5
MAX_EPSILON = 1. - 1e-5
PI = torch.FloatTensor([math.pi])
if torch.cuda.is_available():
PI = PI.cuda()
# N(x | mu, var) = 1/sqrt{2pi var} exp[-1/(2 var) (x-mean)(x-mean)]
# log N(x| mu, var) = -log sqrt(2pi... | 1,768 | 25.80303 | 86 | py |
steer | steer-master/ffjord/vae_lib/utils/load_data.py | from __future__ import print_function
import torch
import torch.utils.data as data_utils
import pickle
from scipy.io import loadmat
import numpy as np
import os
def load_static_mnist(args, **kwargs):
"""
Dataloading function for static mnist. Outputs image data in vectorized form: each image is a vector of... | 7,592 | 35.859223 | 116 | py |
steer | steer-master/ffjord/diagnostics/viz_toy.py | import os
import math
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
def standard_normal_logprob(z):
logZ = -0.5 * math.log(2 * math.pi)
return logZ - z.pow(2) / 2
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)... | 7,028 | 38.05 | 119 | py |
steer | steer-master/ffjord/diagnostics/viz_cnf.py | from inspect import getsourcefile
import sys
import os
import subprocess
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
import argparse
import torch
import torchvision.dataset... | 9,576 | 36.120155 | 107 | py |
steer | steer-master/ffjord/diagnostics/viz_fig1.py | import os
import math
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
from scipy import interpolate as interp
import lib.utils as utils
def standard_normal_logprob(z):
logZ = -0.5 * math.log(2 * math.pi)
return logZ - z.pow(2) / 2
def makedirs(dirname):... | 54,154 | 42.04849 | 172 | py |
steer | steer-master/ffjord/diagnostics/approx_error_1d_particle_traj.py | from inspect import getsourcefile
import sys
import os
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
f... | 15,540 | 36.720874 | 116 | py |
steer | steer-master/ffjord/diagnostics/plot_flows.py | from inspect import getsourcefile
import sys
import os
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
... | 6,070 | 37.424051 | 119 | py |
steer | steer-master/ffjord/diagnostics/viz_high_fidelity_toy.py | import os
import math
from tqdm import tqdm
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import torch
def standard_normal_logprob(z):
logZ = -0.5 * math.log(2 * math.pi)
return logZ - z.pow(2) / 2
def makedirs(dirname):
if not os.path.exists(dirname):
... | 5,114 | 37.458647 | 119 | py |
steer | steer-master/ffjord/diagnostics/approx_error_1d.py | from inspect import getsourcefile
import sys
import os
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
f... | 12,572 | 36.984894 | 116 | py |
steer | steer-master/ffjord/diagnostics/fig_1_1d_toy.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from inspect import getsourcefile
import sys
import argparse
import os
import time
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.p... | 12,538 | 41.795222 | 166 | py |
steer | steer-master/ffjord/diagnostics/viz_multiscale.py | from inspect import getsourcefile
import sys
import os
import math
current_path = os.path.abspath(getsourcefile(lambda: 0))
current_dir = os.path.dirname(current_path)
parent_dir = current_dir[:current_dir.rfind(os.path.sep)]
sys.path.insert(0, parent_dir)
import argparse
import lib.layers as layers
import lib.odenv... | 8,489 | 37.071749 | 119 | py |
steer | steer-master/ffjord/lib/priors.py | import math
import numpy as np
import torch
import torch.nn as nn
from torch.autograd import Variable
eps = 1e-8
class Uniform(nn.Module):
def __init__(self, a=0, b=1):
super(Normal, self).__init__()
self.a = Variable(torch.Tensor([a]))
self.b = Variable(torch.Tensor([b]))
def _che... | 8,414 | 32.392857 | 84 | py |
steer | steer-master/ffjord/lib/spectral_norm.py | """
Spectral Normalization from https://arxiv.org/abs/1802.05957
"""
import types
import torch
from torch.nn.functional import normalize
POWER_ITERATION_FN = "spectral_norm_power_iteration"
class SpectralNorm(object):
def __init__(self, name='weight', dim=0, eps=1e-12):
self.name = name
self.dim ... | 6,512 | 38.957055 | 119 | py |
steer | steer-master/ffjord/lib/utils.py | import os
import math
from numbers import Number
import logging
import torch
def makedirs(dirname):
if not os.path.exists(dirname):
os.makedirs(dirname)
def get_logger(logpath, filepath, package_files=[], displaying=True, saving=True, debug=False):
logger = logging.getLogger()
if debug:
... | 3,046 | 24.822034 | 95 | py |
steer | steer-master/ffjord/lib/odenvp.py | import torch
import torch.nn as nn
import lib.layers as layers
from lib.layers.odefunc import ODEnet
import numpy as np
class ODENVP(nn.Module):
"""
Real NVP for image data. Will downsample the input until one of the
dimensions is less than or equal to 4.
Args:
input_size (tuple): 4D tuple of... | 6,008 | 34.556213 | 116 | py |
steer | steer-master/ffjord/lib/datasets.py | import torch
class Dataset(object):
def __init__(self, loc, transform=None):
self.dataset = torch.load(loc).float().div(255)
self.transform = transform
def __len__(self):
return self.dataset.size(0)
@property
def ndim(self):
return self.dataset.size(1)
def __geti... | 725 | 24.928571 | 97 | py |
steer | steer-master/ffjord/lib/multiscale_parallel.py | import torch
import torch.nn as nn
import lib.layers as layers
from lib.layers.odefunc import ODEnet
import numpy as np
class MultiscaleParallelCNF(nn.Module):
"""
CNF model for image data.
Squeezes the input into multiple scales, applies different conv-nets at each scale
and adds the resulting gradi... | 5,203 | 31.525 | 113 | py |
steer | steer-master/ffjord/lib/custom_optimizers.py | import math
import torch
from torch.optim.optimizer import Optimizer
class Adam(Optimizer):
"""Implements Adam algorithm.
It has been proposed in `Adam: A Method for Stochastic Optimization`_.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
paramete... | 4,597 | 41.574074 | 116 | py |
steer | steer-master/ffjord/lib/visualize_flow.py | import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import torch
LOW = -4
HIGH = 4
def plt_potential_func(potential, ax, npts=100, title="$p(x)$"):
"""
Args:
potential: computes U(z_k) given z_k
"""
xside = np.linspace(LOW, HIGH, npts)
yside = np.lin... | 4,341 | 31.646617 | 118 | py |
steer | steer-master/ffjord/lib/layers/squeeze.py | import torch.nn as nn
__all__ = ['SqueezeLayer']
class SqueezeLayer(nn.Module):
def __init__(self, downscale_factor):
super(SqueezeLayer, self).__init__()
self.downscale_factor = downscale_factor
def forward(self, x, logpx=None, reverse=False):
if reverse:
return self._up... | 1,955 | 29.5625 | 119 | py |
steer | steer-master/ffjord/lib/layers/container.py | import torch.nn as nn
class SequentialFlow(nn.Module):
"""A generalized nn.Sequential container for normalizing flows.
"""
def __init__(self, layersList):
super(SequentialFlow, self).__init__()
self.chain = nn.ModuleList(layersList)
def forward(self, x, logpx=None, reverse=False, ind... | 766 | 27.407407 | 67 | py |
steer | steer-master/ffjord/lib/layers/norm_flows.py | import math
import torch
import torch.nn as nn
from torch.autograd import grad
class PlanarFlow(nn.Module):
def __init__(self, nd=1):
super(PlanarFlow, self).__init__()
self.nd = nd
self.activation = torch.tanh
self.register_parameter('u', nn.Parameter(torch.randn(self.nd)))
... | 2,240 | 31.014286 | 101 | py |
steer | steer-master/ffjord/lib/layers/cnf.py | import torch
import torch.nn as nn
#from torchdiffeq import odeint_adjoint_stochastic_end_v2
from torchdiffeq import odeint_adjoint_stochastic_end_v3
from torchdiffeq import odeint_adjoint_stochastic_end_normal
from torchdiffeq import odeint_adjoint as odeint
#from torchdiffeq import odeint
from .wrappers.cnf_regula... | 3,561 | 32.92381 | 118 | py |
steer | steer-master/ffjord/lib/layers/odefunc.py | import copy
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from . import diffeq_layers
from .squeeze import squeeze, unsqueeze
__all__ = ["ODEnet", "AutoencoderDiffEqNet", "ODEfunc", "AutoencoderODEfunc"]
def divergence_bf(dx, y, **unused_kwargs):
sum_diag = 0.
for i i... | 12,985 | 34.675824 | 114 | py |
steer | steer-master/ffjord/lib/layers/resnet.py | import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, dim):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(dim, dim, kernel_size=3, padding=1, bias=False)
self.bn1 = nn.GroupNorm(2, dim, eps=1e-4)
self.re... | 2,335 | 35.5 | 107 | py |
steer | steer-master/ffjord/lib/layers/glow.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class BruteForceLayer(nn.Module):
def __init__(self, dim):
super(BruteForceLayer, self).__init__()
self.weight = nn.Parameter(torch.eye(dim))
def forward(self, x, logpx=None, reverse=False):
if not reverse:
... | 836 | 26 | 76 | py |
steer | steer-master/ffjord/lib/layers/elemwise.py | import math
import torch
import torch.nn as nn
_DEFAULT_ALPHA = 1e-6
class ZeroMeanTransform(nn.Module):
def __init__(self):
nn.Module.__init__(self)
def forward(self, x, logpx=None, reverse=False):
if reverse:
x = x + .5
if logpx is None:
return x
... | 1,918 | 24.25 | 84 | py |
steer | steer-master/ffjord/lib/layers/normalization.py | import torch
import torch.nn as nn
from torch.nn import Parameter
__all__ = ['MovingBatchNorm1d', 'MovingBatchNorm2d']
class MovingBatchNormNd(nn.Module):
def __init__(self, num_features, eps=1e-4, decay=0.1, bn_lag=0., affine=True):
super(MovingBatchNormNd, self).__init__()
self.num_features = n... | 4,688 | 32.978261 | 100 | py |
steer | steer-master/ffjord/lib/layers/coupling.py | import torch
import torch.nn as nn
__all__ = ['CouplingLayer', 'MaskedCouplingLayer']
class CouplingLayer(nn.Module):
"""Used in 2D experiments."""
def __init__(self, d, intermediate_dim=64, swap=False):
nn.Module.__init__(self)
self.d = d - (d // 2)
self.swap = swap
self.net... | 3,525 | 30.20354 | 101 | py |
steer | steer-master/ffjord/lib/layers/wrappers/cnf_regularization.py | import torch
import torch.nn as nn
class RegularizedODEfunc(nn.Module):
def __init__(self, odefunc, regularization_fns):
super(RegularizedODEfunc, self).__init__()
self.odefunc = odefunc
self.regularization_fns = regularization_fns
def before_odeint(self, *args, **kwargs):
sel... | 3,591 | 31.654545 | 115 | py |
steer | steer-master/ffjord/lib/layers/diffeq_layers/container.py | import torch
import torch.nn as nn
from .wrappers import diffeq_wrapper
class SequentialDiffEq(nn.Module):
"""A container for a sequential chain of layers. Supports both regular and diffeq layers.
"""
def __init__(self, *layers):
super(SequentialDiffEq, self).__init__()
self.layers = nn.... | 1,357 | 30.581395 | 106 | py |
steer | steer-master/ffjord/lib/layers/diffeq_layers/resnet.py | import torch.nn as nn
from . import basic
from . import container
NGROUPS = 16
class ResNet(container.SequentialDiffEq):
def __init__(self, dim, intermediate_dim, n_resblocks, conv_block=None):
super(ResNet, self).__init__()
if conv_block is None:
conv_block = basic.ConcatCoordConv2... | 2,003 | 28.470588 | 99 | py |
steer | steer-master/ffjord/lib/layers/diffeq_layers/wrappers.py | from inspect import signature
import torch.nn as nn
__all__ = ["diffeq_wrapper", "reshape_wrapper"]
class DiffEqWrapper(nn.Module):
def __init__(self, module):
super(DiffEqWrapper, self).__init__()
self.module = module
if len(signature(self.module.forward).parameters) == 1:
se... | 1,365 | 28.06383 | 104 | py |
steer | steer-master/ffjord/lib/layers/diffeq_layers/basic.py | import torch
import torch.nn as nn
import torch.nn.functional as F
def weights_init(m):
classname = m.__class__.__name__
if classname.find('Linear') != -1 or classname.find('Conv') != -1:
nn.init.constant_(m.weight, 0)
nn.init.normal_(m.bias, 0, 0.01)
class HyperLinear(nn.Module):
def __... | 11,057 | 36.869863 | 120 | py |
steer | steer-master/latent_ode/mujoco_physics.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Authors: Yulia Rubanova and Ricky Chen
###########################
import os
import numpy as np
import torch
from lib.utils import get_dict_template
import lib.utils as utils
from torchvision.datasets.utils import download_url
class Hoppe... | 4,315 | 27.966443 | 92 | py |
steer | steer-master/latent_ode/person_activity.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Authors: Yulia Rubanova and Ricky Chen
###########################
import os
import lib.utils as utils
import numpy as np
import tarfile
import torch
from torch.utils.data import DataLoader
from torchvision.datasets.utils import download_... | 9,173 | 29.682274 | 120 | py |
steer | steer-master/latent_ode/generate_timeseries.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
# Create a synthetic dataset
from __future__ import print_function
from __future__ import absolute_import, division
import lib.utils as utils
import torch
import matplotlib.image
import ma... | 5,248 | 33.761589 | 131 | py |
steer | steer-master/latent_ode/physionet.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Authors: Yulia Rubanova and Ricky Chen
###########################
import os
import matplotlib
if os.path.exists("/Users/yulia"):
matplotlib.use('TkAgg')
else:
matplotlib.use('Agg')
import matplotlib.pyplot
import matplotlib.pyplot as pl... | 11,603 | 31.233333 | 114 | py |
steer | steer-master/latent_ode/run_models.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import os
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
import matplotlib.pyplot as plt
import time
import datetime
import argparse
import numpy as np
import... | 13,141 | 38.584337 | 170 | py |
steer | steer-master/latent_ode/lib/rnn_baselines.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import numpy as np
import torch
import torch.nn as nn
from torch.nn.functional import relu
import lib.utils as utils
from lib.utils import get_device
from lib.encoder_decoder import *
fro... | 14,730 | 32.177928 | 121 | py |
steer | steer-master/latent_ode/lib/create_latent_ode_model.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import os
import numpy as np
import torch
import torch.nn as nn
from torch.nn.functional import relu
import lib.utils as utils
from lib.latent_ode import LatentODE
from lib.encoder_decod... | 3,325 | 30.377358 | 101 | py |
steer | steer-master/latent_ode/lib/ode_rnn.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import numpy as np
import torch
import torch.nn as nn
from torch.nn.functional import relu
import lib.utils as utils
from lib.encoder_decoder import *
from lib.likelihood_eval import *
f... | 3,133 | 31.309278 | 121 | py |
steer | steer-master/latent_ode/lib/plotting.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import matplotlib
# matplotlib.use('TkAgg')
matplotlib.use('Agg')
import matplotlib.pyplot
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import os
from scipy.stats i... | 16,053 | 33.673866 | 125 | py |
steer | steer-master/latent_ode/lib/diffeq_solver.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import time
import numpy as np
import torch
import torch.nn as nn
import lib.utils as utils
from torch.distributions.multivariate_normal import MultivariateNormal
# git clone https://gi... | 2,845 | 37.986301 | 126 | py |
steer | steer-master/latent_ode/lib/ode_func.py | ###########################
# Latent ODEs for Irregularly-Sampled Time Series
# Author: Yulia Rubanova
###########################
import numpy as np
import torch
import torch.nn as nn
from torch.nn.utils.spectral_norm import spectral_norm
import lib.utils as utils
###################################################... | 3,935 | 32.641026 | 135 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.