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 |
|---|---|---|---|---|---|---|
PVT | PVT-master/main_kitti.py | from __future__ import print_function
import os
import argparse
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import CosineAnnealingLR
from kitti_datasets.frustum import FrustumKittiDataset
from model.kitti.frustum.frustum_net import FrustumPVT
from torch.utils.data import DataLoader
from modul... | 15,095 | 46.028037 | 141 | py |
PVT | PVT-master/modules/voxelization.py | import torch
import torch.nn as nn
import modules.functional as F
__all__ = ['Voxelization']
class Voxelization(nn.Module):
def __init__(self, resolution, normalize=True, eps=0):
super().__init__()
self.r = int(resolution)
self.normalize = normalize
self.eps = eps
def forward... | 1,014 | 35.25 | 134 | py |
PVT | PVT-master/modules/shared_transformer.py | import torch.nn as nn
import torch.nn.functional as F
import torch
__all__ = ['SharedTransformer']
class SharedTransformer(nn.Module):
def __init__(self, in_channels, out_channels, dim=1):
super().__init__()
self.conv1 = nn.Conv1d(in_channels,out_channels, kernel_size=1, bias=False)
... | 2,162 | 33.333333 | 106 | py |
PVT | PVT-master/modules/shared_mlp.py | import torch.nn as nn
__all__ = ['SharedMLP']
class SharedMLP(nn.Module):
def __init__(self, in_channels, out_channels, dim=1):
super().__init__()
if dim == 1:
conv = nn.Conv1d
bn = nn.BatchNorm1d
elif dim == 2:
conv = nn.Conv2d
bn = nn.Batc... | 923 | 26.176471 | 57 | py |
PVT | PVT-master/modules/pvtconv.py | import torch
import torch.nn as nn
import modules.functional as F
from modules.voxelization import Voxelization
from modules.shared_transformer import SharedTransformer
from modules.se import SE3d
from timm.models.layers import DropPath
import numpy as np
__all__ = ['PVTConv','PartPVTConv','SemPVTConv']
def rand_bbox... | 15,300 | 40.806011 | 116 | py |
PVT | PVT-master/modules/se.py | import torch.nn as nn
__all__ = ['SE3d']
class SE3d(nn.Module):
def __init__(self, channel, reduction=8):
super().__init__()
self.fc = nn.Sequential(
nn.Linear(channel, channel // reduction, bias=False),
nn.ReLU(inplace=True),
nn.Linear(channel // reduction, ch... | 522 | 28.055556 | 114 | py |
PVT | PVT-master/modules/frustum.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from util import huber_loss
__all__ = ['FrustumPointNetLoss', 'get_box_corners_3d']
class FrustumPointNetLoss(nn.Module):
def __init__(self, num_heading_angle_bins, num_size_templates,size_templates, box_loss_weight=1.0,
... | 6,587 | 50.874016 | 124 | py |
PVT | PVT-master/modules/functional/devoxelization.py | from torch.autograd import Function
from modules.functional.backend import _backend
__all__ = ['trilinear_devoxelize']
class TrilinearDevoxelization(Function):
@staticmethod
def forward(ctx, features, coords, resolution, is_training=True):
"""
:param ctx:
:param coords: the coordinat... | 1,485 | 33.55814 | 112 | py |
PVT | PVT-master/modules/functional/voxelization.py | from torch.autograd import Function
from modules.functional.backend import _backend
__all__ = ['avg_voxelize']
class AvgVoxelization(Function):
@staticmethod
def forward(ctx, features, coords, resolution):
"""
:param ctx:
:param features: Features of the point cloud, FloatTensor[B, C... | 1,375 | 32.560976 | 112 | py |
PVT | PVT-master/modules/functional/sampling.py | import numpy as np
import torch
from torch.autograd import Function
from modules.functional.backend import _backend
__all__ = ['gather', 'logits_mask']
class Gather(Function):
@staticmethod
def forward(ctx, features, indices):
"""
Gather
:param ctx:
:param features: features ... | 3,099 | 43.285714 | 120 | py |
PVT | PVT-master/modules/functional/interpolatation.py | from torch.autograd import Function
from modules.functional.backend import _backend
__all__ = ['nearest_neighbor_interpolate']
class NeighborInterpolation(Function):
@staticmethod
def forward(ctx, points_coords, centers_coords, centers_features):
"""
:param ctx:
:param points_coords:... | 1,452 | 36.25641 | 97 | py |
PVT | PVT-master/modules/functional/backend.py | import os
from torch.utils.cpp_extension import load
_src_path = os.path.dirname(os.path.abspath(__file__))
_backend = load(name='_pvt_backend',
extra_cflags=['-O3', '-std=c++17'],
sources=[os.path.join(_src_path,'src', f) for f in [
'interpolate/neighbor_interpolat... | 769 | 34 | 68 | py |
PVT | PVT-master/kitti_meters/frustum.py | import numpy as np
import torch
from modules.frustum import get_box_corners_3d
from kitti_meters.util import get_box_iou_3d
__all__ = ['MeterFrustumKitti']
class MeterFrustumKitti:
def __init__(self, num_heading_angle_bins, num_size_templates, size_templates, class_name_to_class_id,
metric='iou_... | 4,852 | 53.52809 | 117 | py |
PVT | PVT-master/kitti_datasets/config.py | import numpy as np
import torch
from kitti_datasets.container import G
from kitti_datasets.attributes import kitti_attributes as kitti
__all__ = ['configs']
configs = G()
configs.classes = ('Car', 'Pedestrian', 'Cyclist')
configs.num_classes = len(configs.classes)
configs.num_points_per_object = 512
configs.num_head... | 1,508 | 33.295455 | 83 | py |
PVT | PVT-master/kitti_datasets/frustum.py | import os
import pickle
import numpy as np
from torch.utils.data import Dataset
from kitti_datasets.attributes import kitti_attributes as kitti
from kitti_datasets.container import G
class FrustumKittiDataset(Dataset):
def __init__(self, split, num_points, classes, num_heading_angle_bins,class_name_to_size_templat... | 8,273 | 52.727273 | 125 | py |
PVT | PVT-master/model/pvt.py | import torch
import torch.nn as nn
from torch.nn import functional as F
from model.utils import create_pointnet_components
__all__ = ['pvt']
class pvt(nn.Module):
blocks = ((64, 1, 30), (128, 2, 15), (512, 1, None), (1024, 1, None))
def __init__(self, num_classes=40, width_multiplier=1, voxel_resolution_mu... | 2,255 | 38.578947 | 118 | py |
PVT | PVT-master/model/sempvt.py | import torch
import torch.nn as nn
from model.utils import create_pointnet_components, create_mlp_components
__all__ = ['pvt_semseg']
class pvt_semseg(nn.Module):
blocks = ((64, 1, 32), (64, 2, 16), (128, 1, 16), (1024, 1, None))
def __init__(self, seg_num_all=13, width_multiplier=1, voxel_resolution_mult... | 2,024 | 39.5 | 95 | py |
PVT | PVT-master/model/utils.py | import functools
import torch.nn as nn
from modules import SharedMLP
from modules.pvtconv import PVTConv,PartPVTConv,SemPVTConv
__all__ = ['create_mlp_components', 'create_pointnet_components']
def _linear_bn_relu(in_channels, out_channels):
return nn.Sequential(nn.Linear(in_channels, out_channels), nn.BatchNo... | 2,795 | 37.833333 | 107 | py |
PVT | PVT-master/model/partpvt.py | import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.autograd import Variable
import numpy as np
from model.utils import create_pointnet_components, create_mlp_components
__all__ = ['pvt_partseg']
class STNbox(nn.Module):
def __init__(self, k=6):
super(STNbox, self).__init... | 3,504 | 35.894737 | 128 | py |
PVT | PVT-master/model/kitti/frustum/center_regression_net.py | import torch
import torch.nn as nn
from model.utils import create_mlp_components
__all__ = ['CenterRegressionNet']
class CenterRegressionNet(nn.Module):
blocks = (128, 128, 256)
def __init__(self, num_classes=3, width_multiplier=1):
super().__init__()
self.in_channels = 3
self.num_cl... | 1,213 | 36.9375 | 108 | py |
PVT | PVT-master/model/kitti/frustum/frustum_net.py | import functools
import numpy as np
import torch.nn as nn
import modules.functional as F
from model.kitti.frustum.box_estimation import *
from model.kitti.frustum.segmentation import *
from model.kitti.frustum.center_regression_net import CenterRegressionNet
__all__ = ['FrustumPVT']
class FrustumNet(nn.Module):
... | 4,511 | 52.714286 | 117 | py |
PVT | PVT-master/model/kitti/frustum/segmentation/pointnet.py | import torch
import torch.nn as nn
from model.utils import create_pointnet_components, create_mlp_components
__all__ = ['InstanceSegmentationPVT']
class InstanceSegmentationNet(nn.Module):
def __init__(self, num_classes, point_blocks, cloud_blocks, extra_feature_channels,
width_multiplier=1, vox... | 2,578 | 45.890909 | 118 | py |
PVT | PVT-master/model/kitti/frustum/box_estimation/pointnet.py | import torch
import torch.nn as nn
from model.utils import create_pointnet_components, create_mlp_components
__all__ = ['BoxEstimationPointNet']
class BoxEstimationNet(nn.Module):
def __init__(self, num_classes, blocks, num_heading_angle_bins, num_size_templates,
width_multiplier=1, voxel_resol... | 2,076 | 42.270833 | 118 | py |
CoupleNet | CoupleNet-master/lib/fast_rcnn/train.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# Modified by yszhu
# --------------------------------------------------------
"""Train a Fast R-CNN network."""
import caffe
fro... | 10,614 | 41.975709 | 94 | py |
Mutation-Based-Text-Detection | Mutation-Based-Text-Detection-master/classifier_testing/detector.py | import numpy as np
import torch
from transformers import RobertaForSequenceClassification, RobertaTokenizer
class Detector(object):
def __init__(self, detector_file_name):
print('Initializing Detector...')
data = torch.load(detector_file_name)
self.model = RobertaForSequenceClassification.from_pretrained('r... | 1,465 | 20.880597 | 82 | py |
Mutation-Based-Text-Detection | Mutation-Based-Text-Detection-master/classifier_training/finetune_roberta.py | # The pre-trained roberta-based detector may only works w/
# - Huggingface version 2.9.1 (i.e., ```transformers==2.9.1```)
# - ```tokenizers==0.7.0```
# !pip install transformers==2.9.1
'''
~~~About Checkpoints~~~
base.pt is the most accurate checkpoint
base_1.pt is the latest checkpoint
'''
import numpy
FROM_CHECKPO... | 8,542 | 32.766798 | 134 | py |
dissect | dissect-master/netdissect/runningstats.py | '''
Running statistics on the GPU using pytorch, by David Bau.
RunningTopK maintains top-k statistics for a set of channels in parallel.
RunningQuantile maintains (sampled) quantile statistics for a set of channels.
RunningVariance calculate running mean and variance statistics stably.
RunningCovariance and RunningCro... | 53,126 | 35.588843 | 91 | py |
dissect | dissect-master/netdissect/renormalize.py | import numpy
import torch
import PIL
import io
import base64
import re
from torchvision import transforms
def as_tensor(data, source='zc', target='zc'):
renorm = renormalizer(source=source, target=target)
return renorm(data)
def as_image(data, source='zc', target='byte'):
assert len(data.shape) == 3
... | 4,893 | 33.957143 | 80 | py |
dissect | dissect-master/netdissect/sampler.py | '''
A sampler is just a list of integer listing the indexes of the
inputs in a data set to sample. For reproducibility, the
FixedRandomSubsetSampler uses a seeded prng to produce the same
sequence always. FixedSubsetSampler is just a wrapper for an
explicit list of integers.
coordinate_sample solves another sampling... | 7,375 | 38.44385 | 85 | py |
dissect | dissect-master/netdissect/segmenter.py | # Usage as a simple differentiable segmenter base class
import os
import torch
import numpy
import json
import glob
import skimage.morphology
from collections import OrderedDict
from . import upsegmodel
from . import segmodel as segmodel_module
from .easydict import EasyDict
from urllib.request import urlretrieve
cl... | 30,879 | 44.748148 | 100 | py |
dissect | dissect-master/netdissect/parallelfolder.py | '''
Variants of pytorch's ImageFolder for loading image datasets with more
information, such as parallel feature channels in separate files,
cached files with lists of filenames, etc.
'''
import os
import torch
import re
import random
import numpy
import itertools
import copy
import torch.utils.data as data
from torch... | 8,633 | 33.261905 | 84 | py |
dissect | dissect-master/netdissect/show.py | # show.py
#
# An abbreviated way to output simple HTML layout of text and images
# into a python notebook.
#
# - show a PIL image to show an inline HTML <img>.
# - show an array of items to vertically stack them, centered in a block.
# - show an array of arrays to horizontally lay them out as inline blocks.
# - show an... | 4,795 | 28.066667 | 81 | py |
dissect | dissect-master/netdissect/imgviz.py | import PIL
import torch
from . import upsample, renormalize, segviz, tally
from matplotlib import cm
class ImageVisualizer:
def __init__(self, size, image_size=None, data_size=None,
renormalizer=None, scale_offset=None, level=None, actrange=None,
source=None, convolutions=None, q... | 15,318 | 42.030899 | 101 | py |
dissect | dissect-master/netdissect/segviz.py | import numpy
import scipy
import PIL
import torch
def seg_as_image(seg, size=None):
return PIL.Image.fromarray(
segment_visualization(seg.cpu().numpy(), size=size))
def swatch_image(label, size=15):
return PIL.Image.new("RGB", (size, size), tuple(high_contrast[
label % len(high_contrast)]))
... | 19,063 | 58.575 | 77 | py |
dissect | dissect-master/netdissect/nethook.py | '''
Utilities for instrumenting a torch model.
InstrumentedModel will wrap a pytorch model and allow hooking
arbitrary layers to monitor or modify their output directly.
'''
import torch
import numpy
import types
import copy
import inspect
from collections import OrderedDict, defaultdict
class InstrumentedModel(tor... | 15,989 | 36.447307 | 92 | py |
dissect | dissect-master/netdissect/tally.py | '''
Batchwise tally functions, analogous to tensor.topk, mean+variance,
bincount, covaraince, and sort (for quantiles), implemented in a way
that permits fast computation of statistics over large data sets that
do not fit in memory at once.
These functions are useful because, while many statistics are much
cheaper to ... | 30,679 | 38.947917 | 80 | py |
dissect | dissect-master/netdissect/upsample.py | import torch
from torchvision import transforms
def upsampler(target_shape, data_shape=None,
image_size=None, scale_offset=None,
source=None, convolutions=None, dtype=torch.float, device=None):
'''
Returns a function that will upsample a batch of torch data from the
expected da... | 8,249 | 42.650794 | 102 | py |
dissect | dissect-master/netdissect/zdataset.py | import torch
import numpy
import itertools
from torch.utils.data import TensorDataset
def z_dataset_for_model(model, size=100, seed=1, indices=None):
if indices is not None:
indices = torch.as_tensor(indices, dtype=torch.int64, device='cpu')
zs = z_sample_for_model(model, indices.max().item() + 1,... | 3,994 | 32.571429 | 79 | py |
dissect | dissect-master/netdissect/segmodel/resnet.py | import os
import sys
import torch
import torch.nn as nn
import math
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
__all__ = ['Re... | 7,479 | 30.694915 | 99 | py |
dissect | dissect-master/netdissect/segmodel/resnext.py | import os
import sys
import torch
import torch.nn as nn
import math
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
__all__ = ['Re... | 6,053 | 31.902174 | 101 | py |
dissect | dissect-master/netdissect/segmodel/models.py | import torch
import torch.nn as nn
import torchvision
from . import resnet, resnext, mobilenet
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
class SegmentationModuleBase(nn.Module):
def __init__(self):
super(Segmentation... | 21,236 | 35.117347 | 114 | py |
dissect | dissect-master/netdissect/segmodel/mobilenet.py | """
This MobileNetV2 implementation is modified from the following repository:
https://github.com/tonylins/pytorch-mobilenet-v2
"""
import os
import sys
import torch
import torch.nn as nn
import math
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as Synchronize... | 5,624 | 31.142857 | 100 | py |
dissect | dissect-master/netdissect/upsegmodel/resnet.py | import os
import sys
import torch
import torch.nn as nn
import math
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
__all__ = ... | 7,363 | 30.20339 | 99 | py |
dissect | dissect-master/netdissect/upsegmodel/resnext.py | import os
import sys
import torch
import torch.nn as nn
import math
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
try:
from urllib import urlretrieve
except ImportError:
from urllib.request import urlretrieve
__all__ = ... | 6,057 | 31.923913 | 101 | py |
dissect | dissect-master/netdissect/upsegmodel/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from . import resnet, resnext
try:
from lib.nn import SynchronizedBatchNorm2d
except ImportError:
from torch.nn import BatchNorm2d as SynchronizedBatchNorm2d
class SegmentationModuleBase(nn.Module):
def __init__(self):
... | 17,942 | 40.922897 | 114 | py |
dissect | dissect-master/netdissect/upsegmodel/prroi_pool/prroi_pool.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : prroi_pool.py
# Author : Jiayuan Mao, Tete Xiao
# Email : maojiayuan@gmail.com, jasonhsiao97@gmail.com
# Date : 07/13/2018
#
# This file is part of PreciseRoIPooling.
# Distributed under terms of the MIT license.
# Copyright (c) 2017 Megvii Technology Limit... | 827 | 27.551724 | 102 | py |
dissect | dissect-master/netdissect/upsegmodel/prroi_pool/functional.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : functional.py
# Author : Jiayuan Mao, Tete Xiao
# Email : maojiayuan@gmail.com, jasonhsiao97@gmail.com
# Date : 07/13/2018
#
# This file is part of PreciseRoIPooling.
# Distributed under terms of the MIT license.
# Copyright (c) 2017 Megvii Technology Limite... | 2,510 | 34.366197 | 135 | py |
dissect | dissect-master/netdissect/upsegmodel/prroi_pool/test_prroi_pooling2d.py | # -*- coding: utf-8 -*-
# File : test_prroi_pooling2d.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 18/02/2018
#
# This file is part of Jacinle.
import unittest
import torch
import torch.nn as nn
import torch.nn.functional as F
from jactorch.utils.unittest import TorchTestCase
from prroi_po... | 1,473 | 24.859649 | 68 | py |
dissect | dissect-master/netdissect/upsegmodel/prroi_pool/build.py | #! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : build.py
# Author : Jiayuan Mao, Tete Xiao
# Email : maojiayuan@gmail.com, jasonhsiao97@gmail.com
# Date : 07/13/2018
#
# This file is part of PreciseRoIPooling.
# Distributed under terms of the MIT license.
# Copyright (c) 2017 Megvii Technology Limited.
... | 1,343 | 25.352941 | 97 | py |
dissect | dissect-master/experiment/generator_int_experiment.py | # New-style dissection experiment code.
import torch, argparse, os, shutil, inspect, json, numpy, random
from collections import defaultdict
from netdissect import pbar, nethook, renormalize, zdataset
from netdissect import upsample, tally, imgviz, imgsave, bargraph
from . import setting
import netdissect
torch.backend... | 16,924 | 41.3125 | 88 | py |
dissect | dissect-master/experiment/shapebias_experiment.py | from netdissect import parallelfolder, show, tally, nethook, renormalize
from . import readdissect, setting
import copy, PIL.Image
from netdissect import upsample, imgsave, imgviz
import re, torchvision, torch, os
from IPython.display import SVG
from matplotlib import pyplot as plt
torch.set_grad_enabled(False)
def n... | 4,910 | 34.078571 | 90 | py |
dissect | dissect-master/experiment/setting.py | import torch, torchvision, os, collections
from netdissect import parallelfolder, zdataset, renormalize, segmenter
from . import oldalexnet, oldvgg16, oldresnet152
def load_proggan(domain):
# Automatically download and cache progressive GAN model
# (From Karras, converted from Tensorflow to Pytorch.)
from ... | 4,188 | 40.89 | 80 | py |
dissect | dissect-master/experiment/proggan.py | import torch, numpy, itertools
import torch.nn as nn
from collections import OrderedDict
def print_network(net, verbose=False):
num_params = 0
for param in net.parameters():
num_params += param.numel()
if verbose:
print(net)
print('Total number of parameters: {:3.3f} M'.format(num_para... | 11,576 | 37.207921 | 79 | py |
dissect | dissect-master/experiment/oldvgg16.py | import collections, torch, torchvision, numpy
# Return a version of vgg16 where the layers are given their research names.
def vgg16(*args, **kwargs):
model = torchvision.models.vgg16(*args, **kwargs)
model.features = torch.nn.Sequential(collections.OrderedDict(zip([
'conv1_1', 'relu1_1',
'conv... | 998 | 26.75 | 76 | py |
dissect | dissect-master/experiment/readdissect.py | import argparse, os, json, numpy, PIL.Image, torch, torchvision, collections
import math, shutil
from netdissect import pidfile, tally, nethook, parallelfolder
from netdissect import upsample, imgviz, imgsave, renormalize, bargraph
from netdissect import runningstats
class DissectVis:
'''
Code to read out the... | 3,426 | 35.849462 | 76 | py |
dissect | dissect-master/experiment/intervention_experiment.py | # Measuring the importance of a unit to a class by measuring the
# impact of removing sets of units on binary classification
# accuracy for individual classes.
import torch, argparse, os, json, numpy, random
from netdissect import pbar, nethook
from netdissect.sampler import FixedSubsetSampler
from . import setting
im... | 9,008 | 42.946341 | 80 | py |
dissect | dissect-master/experiment/oldresnet152.py |
import torch
import torch.nn as nn
from functools import reduce
from torch.autograd import Variable
def load_places_resnet152(weight_file):
model = OldResNet152()
state_dict = torch.load(weight_file)
model.load_state_dict(state_dict)
return model
class LambdaBase(nn.Sequential):
def __init__(sel... | 45,210 | 48.035792 | 85 | py |
dissect | dissect-master/experiment/oldalexnet.py | from __future__ import print_function
# based on https://github.com/jiecaoyu/pytorch_imagenet
import os
import torch
import sys
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict
import torchvision.transforms
import numpy
def load_places_alexnet(weight_file):
model = AlexNet... | 3,971 | 36.471698 | 73 | py |
dissect | dissect-master/experiment/dissect_experiment.py | # New-style dissection experiment code.
import torch, argparse, os, shutil, inspect, json, numpy, random
from collections import defaultdict
from netdissect import pbar, nethook, renormalize, pidfile, zdataset
from netdissect import upsample, tally, imgviz, imgsave, bargraph
from . import setting
import netdissect
torc... | 11,094 | 37.524306 | 80 | py |
dissect | dissect-master/stylization/stylize.py | #!/usr/bin/env python
import argparse
from function import adaptive_instance_normalization
import net
from pathlib import Path
from PIL import Image
import random
import torch
import torch.nn as nn
import torchvision.transforms
from torchvision.utils import save_image
from tqdm import tqdm
import zlib # For hash
parse... | 6,673 | 38.72619 | 203 | py |
dissect | dissect-master/stylization/torch_to_pytorch.py | from __future__ import print_function
import argparse
from functools import reduce
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch.utils.serialization import load_lua
class LambdaBase(nn.Sequential):
def __init__(self, fn, *args):
super(LambdaBase, self).__init__(*args)... | 12,845 | 38.89441 | 88 | py |
dissect | dissect-master/stylization/net.py | import torch.nn as nn
from torch.autograd import Variable
from function import adaptive_instance_normalization as adain
from function import calc_mean_std
decoder = nn.Sequential(
nn.ReflectionPad2d((1, 1, 1, 1)),
nn.Conv2d(512, 256, (3, 3)),
nn.ReLU(),
nn.Upsample(scale_factor=2),
nn.ReflectionPa... | 5,000 | 33.253425 | 76 | py |
dissect | dissect-master/stylization/function.py | import torch
def calc_mean_std(feat, eps=1e-5):
# eps is a small value added to the variance to avoid divide-by-zero.
size = feat.data.size()
assert (len(size) == 4)
N, C = size[:2]
feat_var = feat.view(N, C, -1).var(dim=2) + eps
feat_std = feat_var.sqrt().view(N, C, 1, 1)
feat_mean = feat... | 2,425 | 34.676471 | 79 | py |
GraphTune | GraphTune-master/test.py | """
Neural networkを使用したmodelをtestするためのモジュール.
A) ReEncoderの事前学習結果のtest
1) test_re_encoder()
"""
import os
import argparse
import logging
import torch
from torch import nn
from torch import optim
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from torch.utils.data import Ten... | 4,909 | 31.733333 | 161 | py |
GraphTune | GraphTune-master/utils.py | """便利な関数群"""
from __future__ import annotations # Python 3.7, 3.8はこの記述が必要
import torch
from torch.distributions import Categorical
import subprocess
import logging
import json
from datetime import datetime
import os
from dataclasses import asdict
from typing import Any
import glob
import numpy as np
import pandas as p... | 8,916 | 27.672026 | 102 | py |
GraphTune | GraphTune-master/eval.py | """
学習済みモデルを使用して, 条件付き生成をするモジュール.
"""
import os
import logging
import argparse
import torch
from torch import nn
from torch.utils.tensorboard import SummaryWriter
import shutil
import joblib
import networkx as nx
from config import common_args, Parameters
import utils
from utils import dump_params, setup_params
from ... | 5,188 | 34.786207 | 118 | py |
GraphTune | GraphTune-master/train.py | """
Neural networkを使用したmodelを学習するためのモジュール.
"""
import os
import argparse
import logging
import torch
from torch import nn
from torch import optim
from torch.utils.tensorboard import SummaryWriter
from torch.utils.data import DataLoader
from torch.utils.data import TensorDataset
from torchinfo import summary
from torch... | 19,627 | 42.138462 | 162 | py |
GraphTune | GraphTune-master/preprocess.py | """
生のデータセットを前処理し、modelの入力形式に変換するモジュール.
"""
import joblib
import numpy as np
import torch
import matplotlib.pyplot as plt
from graph_process import complex_networks, convert_to_dfs_code
import utils
def preprocess(params, train_directory='./dataset/train/', valid_directory='./dataset/valid/', test_directory='./data... | 14,335 | 40.314121 | 143 | py |
GraphTune | GraphTune-master/models/re_encoder.py | """
(C)VAEのDecoderから出力されたDFSコードの確率分布から、グラフ特徴量を算出するReEncoderモデルを定義するモジュール.
"""
import torch
from torch import nn
class ReEncoder(nn.Module):
"""Decoderの後ろに配置されるLSTM
Decoderの後ろに配置されるLSTMであり、処理はEncoderと概ね同じである。
DecodeされたDFSコードからグラフ特徴量を計算する。
(モデル概要)
線形層1(input_size, emb_sizae) => LSTM(emb_size, hidd... | 3,564 | 32.317757 | 142 | py |
GraphTune | GraphTune-master/models/cvae_with_re_encoder.py | """
Conditional Variational AutoEncoder(CVAE) + ReEncoderモデルのインターフェースを定義するモジュール.
"""
import torch
from torch import nn
import sys
import os
import torch.nn.functional as F
import numpy as np
import random
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from utils import try_gpu, sample_dist, convert2on... | 2,662 | 34.506667 | 132 | py |
GraphTune | GraphTune-master/models/cvae_for_2_tuples.py | """
2-tuplesのDFSコードを学習するConditional Variational AutoEncoder(CVAE) を定義するモジュール.
"""
import os
import random
import sys
import numpy as np
import torch
from torch import nn
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from utils import try_gpu, sample_dist, convert2onehot
class CVAE(nn.Module):
... | 12,875 | 32.706806 | 129 | py |
GraphTune | GraphTune-master/models/cvae.py | """
Conditional Variational AutoEncoder(CVAE) を定義するモジュール.
"""
import torch
from torch import nn
import sys
import os
import torch.nn.functional as F
import numpy as np
import random
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from utils import try_gpu, sample_dist, convert2onehot
class CVAE(nn.Mo... | 16,762 | 35.28355 | 151 | py |
GraphTune | GraphTune-master/graph_process/complex_networks.py | """
グラフに関する処理をまとめたモジュール.
主な機能は以下の通り.
・生のデータセットを読み込み、グラフオブジェクトに変換して保存する
・グラフオブジェクトからグラフ特徴量を算出し、csvファイルに書き出す
"""
import glob
import networkx as nx
import numpy as np
from sklearn.model_selection import train_test_split
import joblib
import torch
import os
import sys
from tqdm import tqdm
import random
sys.path.append(... | 7,955 | 37.809756 | 120 | py |
GraphTune | GraphTune-master/graph_process/graph_statistic.py | """
グラフ統計量(グラフ特徴量, グラフプロパティ)を算出するモジュール.
"""
from time import time_ns
from networkx.classes import graph
from networkx.readwrite import json_graph
import numpy as np
import networkx as nx
import torch
from collections import OrderedDict
import networkx.algorithms.approximation.treewidth as nx_tree
import networkx.algor... | 13,132 | 28.51236 | 99 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/param.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import argparse
import random
import numpy as np
import torch
def get_optimizer(optim):
# Bind the optimizer
if optim == 'rms':
print("Optimizer: Using RMSProp")
optimizer = torch.optim.RMSprop
elif optim == 'adam':
print("Optimizer: U... | 7,503 | 51.475524 | 118 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/pretrain/lxmert_pretrain_spatial.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import collections
import os
import random
from GPUtil import showUtilization as gpuUsage
import gc
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from src.param import args
from src.pretrain.lxmert_data... | 16,187 | 35.214765 | 110 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/pretrain/qa_answer_table.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import torch
class AnswerTable:
ANS_CONVERT = {
"a man": "man",
"the man": "man",
"a woman": "woman",
"the woman": "woman",
'one': '1',
'two': '2',
'three': '3',
'four': '4',
'five': '... | 5,015 | 30.54717 | 85 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/pretrain/lxmert_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import random
from collections import defaultdict
from torch.utils.data import Dataset
from src.param import args
from src.pretrain.qa_answer_table import AnswerTable
from src.utils import load_spatial_data, load_spatial_gqa, load_patches
TINY_IMG_NUM = 500
F... | 12,924 | 34.122283 | 104 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/pretrain/lxmert_pretrain.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import collections
import os
import random
import gc
import sys
from datetime import datetime
# from GPUtil import showUtilization as gpuUsage
from tqdm import tqdm
import numpy as np
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
fr... | 19,245 | 37.110891 | 128 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/pretrain/demo.py | import os
import torch
import yaml
from easydict import EasyDict as edict
from pytorch_transformers.tokenization_bert import BertTokenizer
from vilbert.datasets import ConceptCapLoaderTrain, ConceptCapLoaderVal
from vilbert.vilbert import VILBertForVLTasks, BertConfig, BertForMultiModalPreTraining
from vilbert.task_ut... | 15,758 | 35.479167 | 189 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/optimization.py | # coding=utf-8
# Copyright 2019 project LXRT
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http:/... | 7,927 | 42.801105 | 141 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/modeling_capsbert.py | # coding=utf-8
# Copyright 2022 project WSG-VQA-VLT modified from project LXRT
# Copyright 2019 project LXRT.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "Licen... | 90,458 | 43.083333 | 134 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/entry.py | # coding=utf-8
# Copyright 2019 project LXRT.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... | 7,340 | 35.341584 | 131 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/modeling_spatial.py | # coding=utf-8
# Copyright 2019 project LXRT.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... | 56,193 | 42.833073 | 136 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/entry_spatial.py | # coding=utf-8
# Copyright 2019 project LXRT.
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the ... | 5,857 | 33.458824 | 127 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/pytorch_i3d.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import os
import sys
from collections import OrderedDict
class MaxPool3dSamePadding(nn.MaxPool3d):
def compute_pad(self, dim, s):
if s % self.stride[dim] == 0:
return max... | 14,430 | 40.34957 | 134 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/file_utils.py | """
Utilities for working with the local dataset cache.
This file is adapted from the AllenNLP library at https://github.com/allenai/allennlp
Copyright by the AllenNLP authors.
"""
import json
import logging
import os
import shutil
import sys
import tempfile
from functools import wraps
from hashlib import sha256
from i... | 8,209 | 32.104839 | 112 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/PositionalEncoding.py | import torch
import torch.nn as nn
class FixedPositionalEncoding(nn.Module):
def __init__(self, embedding_dim, max_length=5000):
super(FixedPositionalEncoding, self).__init__()
pe = torch.zeros(max_length, embedding_dim)
position = torch.arange(0, max_length, dtype=torch.float).unsqueeze(... | 1,419 | 32.809524 | 78 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/lxrt/capsules_new.py | # Thanks to Kevin Duarte who provided us this implementation of CapsulesNet
import math
import torch
import torch.nn as nn
from .pytorch_i3d import InceptionI3d
class sentenceNet(nn.Module):
def __init__(self):
super(sentenceNet, self).__init__()
self.conv1 = nn.Conv1d(300, 300, kernel_size=2, ... | 22,140 | 36.149329 | 220 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/refcocoplus_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import numpy as np
import torch
from torch.utils.data import Dataset
from src.param import args
from src.utils import load_obj_tsv, load_spatial_data
# Load part of the dataset for fast checking.
# Notice that here is the number of images instead of the numbe... | 7,138 | 32.359813 | 119 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/refcocoplus.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import os
import collections
import gc
import torch
from tqdm import tqdm
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
from src.param import args
from src.pretrain.qa_answer_table import load_lxmert_qa
from src.tasks.refcocoplus_model import Re... | 9,396 | 35.996063 | 191 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/gqa_gradcam.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import os
import collections
import gc
import torch
from tqdm import tqdm
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
from src.param import args
from src.pretrain.qa_answer_table import load_lxmert_qa
from src.tasks.gqa_model import GQAModel
i... | 13,105 | 37.890208 | 220 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/vqa_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import os
import pickle
import numpy as np
import torch
from torch.utils.data import Dataset
from param import args
from utils import load_obj_tsv
# Load part of the dataset for fast checking.
# Notice that here is the number of images instead of the number o... | 5,757 | 29.465608 | 99 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/refcocog_model.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import torch.nn as nn
from src.param import args
from src.lxrt.entry import LXRTEncoder
from src.lxrt.modeling_capsbert import BertLayerNorm, GeLU, MLP
# Max length including <bos> and <eos>
MAX_GQA_LENGTH = 20
class RefCOCOgModel(nn.Module):
def __init__(self, trai... | 1,979 | 30.935484 | 76 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/gqa_model.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import torch.nn as nn
from src.param import args
from src.lxrt.entry import LXRTEncoder
from src.lxrt.modeling_capsbert import BertLayerNorm, GeLU
# Max length including <bos> and <eos>
MAX_GQA_LENGTH = 20
class GQAModel(nn.Module):
def __init__(self, num_answers):
... | 1,298 | 26.0625 | 70 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/mscoco_retrieval_model.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import torch.nn as nn
from src.param import args
from src.lxrt.entry import LXRTEncoder
from src.lxrt.modeling_capsbert import BertLayerNorm, GeLU
# Max length including <bos> and <eos>
MAX_GQA_LENGTH = 20
class MSCOCOModel(nn.Module):
def __init__(self):
su... | 1,337 | 26.306122 | 72 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/gqa_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import numpy as np
import torch
from torch.utils.data import Dataset
from src.param import args
from src.utils import load_obj_tsv, load_spatial_gqa
# Load part of the dataset for fast checking.
# Notice that here is the number of images instead of the number... | 6,487 | 30.495146 | 119 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/vqa_model.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import torch.nn as nn
from param import args
from lxrt.entry import LXRTEncoder
from lxrt.modeling import BertLayerNorm, GeLU
# Max length including <bos> and <eos>
MAX_VQA_LENGTH = 20
class VQAModel(nn.Module):
def __init__(self, num_answers):
super().__ini... | 1,298 | 24.98 | 70 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/refcoco.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import os
# os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import collections
import gc
import torch
from tqdm import tqdm
import torch.nn as nn
from torch.utils.data.dataloader import DataLoader
from src import eval_utils
from src.box_utils import xywh2xyxy, xyxy2xywh, general... | 12,004 | 38.883721 | 191 | py |
WSG-VQA-VLTransformers | WSG-VQA-VLTransformers-main/src/tasks/mscoco_retrieval_data.py | # coding=utf-8
# Copyleft 2019 project LXRT.
import json
import numpy as np
import torch
from torch.utils.data import Dataset
from src.param import args
from src.utils import load_obj_tsv, load_spatial_data
# Load part of the dataset for fast checking.
# Notice that here is the number of images instead of the numbe... | 8,537 | 33.707317 | 123 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.