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 |
|---|---|---|---|---|---|---|
3DG-STFM | 3DG-STFM-master/src/loftr/backbone/resnet_fpn.py | import torch.nn as nn
import torch.nn.functional as F
def conv1x1(in_planes, out_planes, stride=1):
"""1x1 convolution without padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False)
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with pad... | 6,772 | 33.380711 | 96 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/loftr_module/linear_attention.py | """
Linear Transformer proposed in "Transformers are RNNs: Fast Autoregressive Transformers with Linear Attention"
Modified from: https://github.com/idiap/fast-transformers/blob/master/fast_transformers/attention/linear_attention.py
"""
import torch
from torch.nn import Module, Dropout
def elu_feature_map(x):
re... | 2,794 | 33.085366 | 117 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/loftr_module/fine_preprocess.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from einops.einops import rearrange, repeat
class FinePreprocess(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config
self.cat_c_feat = config['fine_concat_coarse_feat']
self.W = self.con... | 5,006 | 43.705357 | 109 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/loftr_module/transformer.py | import copy
import torch
import torch.nn as nn
from .linear_attention import LinearAttention, FullAttention
class LoFTREncoderLayer(nn.Module):
def __init__(self,
d_model,
nhead,
attention='linear'):
super(LoFTREncoderLayer, self).__init__()
self... | 3,657 | 34.514563 | 105 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/utils/supervision.py | from math import log
from loguru import logger
import torch
from einops import repeat
from kornia.utils import create_meshgrid
from .geometry import warp_kpts
############## ↓ Coarse-Level supervision ↓ ##############
@torch.no_grad()
def mask_pts_at_padded_regions(grid_pt, mask):
"""For megadepth dataset,... | 5,724 | 36.418301 | 110 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/utils/position_encoding.py | import math
import torch
from torch import nn
class PositionEncodingSine(nn.Module):
"""
This is a sinusoidal position encoding that generalized to 2-dimensional images
"""
def __init__(self, d_model, max_shape=(256, 256)):
"""
Args:
max_shape (tuple): for 1/8 featmap, the... | 1,235 | 33.333333 | 104 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/utils/fine_matching.py | import math
import torch
import torch.nn as nn
from kornia.geometry.subpix import dsnt
from kornia.utils.grid import create_meshgrid
class FineMatching(nn.Module):
"""FineMatching with s2d paradigm"""
def __init__(self):
super().__init__()
def forward(self, feat_f0, feat_f1, data):
"""
... | 5,385 | 37.471429 | 113 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/utils/supervision_homography.py | from math import log
from loguru import logger
import torch
from einops import repeat
from kornia.utils import create_meshgrid
from .geometry import warp_kpts,warp_kpts_homo
############## ↓ Coarse-Level supervision ↓ ##############
@torch.no_grad()
def mask_pts_at_padded_regions(grid_pt, mask):
"""For me... | 5,957 | 36.708861 | 111 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/utils/geometry.py | import torch
import cv2
@torch.no_grad()
def warp_kpts_homo(kpts0, M):
""" Warp kpts0 from I0 to I1 with Homography M
Args:
kpts0 (torch.Tensor): [N, L, 2] - <x, y>,
M (torch.Tensor):
Returns:
warped_keypoints0 (torch.Tensor): [N, L, 2] <x0_hat, y1_hat>
"""
#kpts0_long = kpt... | 2,838 | 34.936709 | 113 | py |
3DG-STFM | 3DG-STFM-master/src/loftr/utils/coarse_matching.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from einops.einops import rearrange
INF = 1e9
def mask_border(m, b: int, v):
""" Mask borders with value
Args:
m (torch.Tensor): [N, H0, W0, H1, W1]
b (int)
v (m.dtype)
"""
if b <= 0:
return
m[:, :b... | 20,002 | 41.289641 | 120 | py |
3DG-STFM | 3DG-STFM-master/src/optimizers/__init__.py | import torch
from torch.optim.lr_scheduler import MultiStepLR, CosineAnnealingLR, ExponentialLR
def build_optimizer(model, config):
name = config.TRAINER.OPTIMIZER
lr = config.TRAINER.TRUE_LR
if name == "adam":
return torch.optim.Adam(filter(lambda p: p.requires_grad, model.parameters()), lr=lr, ... | 1,665 | 35.217391 | 135 | py |
3DG-STFM | 3DG-STFM-master/src/utils/comm.py | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
"""
[Copied from detectron2]
This file contains primitives for multi-gpu communication.
This is useful when doing distributed training.
"""
import functools
import logging
import numpy as np
import pickle
import torch
import torch.distributed as di... | 7,776 | 28.236842 | 100 | py |
3DG-STFM | 3DG-STFM-master/src/utils/misc.py | import os
import contextlib
import joblib
from typing import Union
from loguru import _Logger, logger
from itertools import chain
import torch
from yacs.config import CfgNode as CN
from pytorch_lightning.utilities import rank_zero_only
def lower_config(yacs_cfg):
if not isinstance(yacs_cfg, CN):
return y... | 3,512 | 33.441176 | 128 | py |
3DG-STFM | 3DG-STFM-master/src/utils/dataset.py | import io
from loguru import logger
import cv2
import numpy as np
import h5py
import torch
from numpy.linalg import inv
import os
try:
# for internel use only
from .client import MEGADEPTH_CLIENT, SCANNET_CLIENT
except Exception:
MEGADEPTH_CLIENT = SCANNET_CLIENT = None
# --- DATA IO ---
def load_array_... | 8,671 | 31.479401 | 111 | py |
3DG-STFM | 3DG-STFM-master/src/utils/metrics.py | import torch
import cv2
import numpy as np
from collections import OrderedDict
from loguru import logger
from kornia.geometry.epipolar import numeric
from kornia.geometry.conversions import convert_points_to_homogeneous
import random
# --- METRICS ---
def relative_pose_error(T_0to1, R, t, ignore_gt_t_thr=0.0):
# a... | 16,290 | 35.042035 | 119 | py |
3DG-STFM | 3DG-STFM-master/src/utils/profiler.py | import torch
from pytorch_lightning.profiler import SimpleProfiler, PassThroughProfiler
from contextlib import contextmanager
from pytorch_lightning.utilities import rank_zero_only
class InferenceProfiler(SimpleProfiler):
"""
This profiler records duration of actions with cuda.synchronize()
Use this in te... | 1,199 | 29 | 81 | py |
3DG-STFM | 3DG-STFM-master/src/losses/loftr_loss.py | from loguru import logger
import torch
import torch.nn as nn
import torch.nn.functional as F
class LoFTRLoss(nn.Module):
def __init__(self, config):
super().__init__()
self.config = config # config under the global namespace
self.loss_config = config['loftr']['loss']
self.match_ty... | 20,436 | 46.30787 | 179 | py |
tencent-ml-images | tencent-ml-images-master/models/resnet.py | """ResNet model
Related papers:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
[2] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Identity Mappings in Deep Residual Networks. arXiv: 1603.05027
"""
from __future__ import absolute_im... | 7,099 | 33.803922 | 111 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/main.py | import sys
import argparse
import os
import random
import numpy
import pandas as pd
import torch
import torch.backends.cudnn as cudnn
import torch.nn.parallel
import torch.optim
import torch.utils.data
import agents
import utils
numpy.set_printoptions(edgeitems=5, linewidth=160, formatter={'float': '{:0.6f}'.format})
... | 6,839 | 51.21374 | 134 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/example.py | # Code reused from: https://github.com/kuangliu/pytorch-cifar
import torch
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import os
import net
import losses
import tools
from torchmetrics import AUROC
import random
import numpy
import torchnet as tnt
base_seed = 42
... | 8,369 | 41.923077 | 164 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/detect.py | from __future__ import print_function
import argparse
import torch
import models
import os
import losses
import data_loader
import calculate_log as callog
from torchvision import transforms
parser = argparse.ArgumentParser(description='PyTorch code: OOD detector')
parser.add_argument('--batch_size', type=int, default=... | 7,841 | 44.593023 | 140 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/data_loader.py | import torch
from torchvision import datasets
import os
def getSVHN(batch_size, TF, data_root='data', train=True, val=True, **kwargs):
data_root = os.path.expanduser(os.path.join(data_root, 'svhn'))
kwargs.pop('input_size', None)
ds = []
if train:
train_loader = torch.utils.data.DataLoader(
... | 3,956 | 46.674699 | 158 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/tools.py | # Code reused from: https://github.com/kuangliu/pytorch-cifar
'''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
_... | 2,429 | 24.578947 | 68 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/net.py | # Code reused from: https://github.com/kuangliu/pytorch-cifar
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import losses
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNor... | 5,441 | 40.861538 | 107 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/analyze.py | import argparse
import os
import torch
import sys
import numpy as np
import pandas as pd
import random
pd.options.display.float_format = '{:,.4f}'.format
pd.set_option('display.width', 160)
parser = argparse.ArgumentParser(description='Analize results in csv files')
parser.add_argument('-p', '--path', default="", ty... | 6,074 | 43.343066 | 135 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/loaders/image.py | import random
import torchvision
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
class ImageLoader:
def __init__(self, args):
self.args = args
self.mnist = False
if args.dataset == "cifar10":
self.normalize = transforms.Normalize((0.491, 0.4... | 4,367 | 52.925926 | 151 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/models/densenet.py | # code reused from: https://github.com/kuangliu/pytorch-cifar
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)... | 7,490 | 39.274194 | 127 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/models/proper_resnet.py | # code reused from: https://github.com/akamaster/pytorch_resnet_cifar10
'''
Properly implemented ResNet-s for CIFAR10 as described in paper [1].
The implementation and structure of this file is hugely influenced by [2]
which is implemented for ImageNet and doesn't have option A for identity.
Moreover, most of the imple... | 6,110 | 35.375 | 130 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/agents/classifier.py | import os
import sys
import torch
import models
import loaders
import losses
import statistics
import math
import torchnet as tnt
import numpy as np
import utils
class ClassifierAgent:
def __init__(self, args):
self.args = args
self.epoch = None
# create dataset
image_loaders = lo... | 25,791 | 58.842227 | 164 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/utils/procedures.py | import os
import pickle
import torch.nn.parallel
import torch.optim
import torch.utils.data
import torch
import torch.nn.functional as F
import csv
import numpy as np
from sklearn import metrics
def compute_weights(iterable):
return [sum(iterable) / (iterable[i] * len(iterable)) if iterable[i] != 0 else float("in... | 6,271 | 29.595122 | 126 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/losses/softmax.py | import torch.nn as nn
import torch
import math
class SoftMaxLossFirstPart(nn.Module):
def __init__(self, num_features, num_classes, temperature=1.0):
super(SoftMaxLossFirstPart, self).__init__()
self.num_features = num_features
self.num_classes = num_classes
self.temperature = temp... | 1,694 | 41.375 | 111 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/losses/isomaxplus.py | import torch.nn as nn
import torch.nn.functional as F
import torch
class IsoMaxPlusLossFirstPart(nn.Module):
"""This part replaces the model classifier output layer nn.Linear()"""
def __init__(self, num_features, num_classes, temperature=1.0):
super(IsoMaxPlusLossFirstPart, self).__init__()
se... | 2,771 | 52.307692 | 169 | py |
entropic-out-of-distribution-detection | entropic-out-of-distribution-detection-master/losses/isomax.py | import torch.nn as nn
import torch.nn.functional as F
import torch
class IsoMaxLossFirstPart(nn.Module):
"""This part replaces the model classifier output layer nn.Linear()"""
def __init__(self, num_features, num_classes, temperature=1.0):
super(IsoMaxLossFirstPart, self).__init__()
self.num_f... | 2,571 | 50.44 | 117 | py |
stable-continual-learning | stable-continual-learning-master/stable_sgd/main.py | import os
import torch
import numpy as np
import pandas as pd
import torch.nn as nn
from stable_sgd.models import MLP, ResNet18
from stable_sgd.data_utils import get_permuted_mnist_tasks, get_rotated_mnist_tasks, get_split_cifar100_tasks
from stable_sgd.utils import parse_arguments, DEVICE, init_experiment, end_experim... | 4,867 | 29.425 | 128 | py |
stable-continual-learning | stable-continual-learning-master/stable_sgd/utils.py | import uuid
import torch
import argparse
import matplotlib
import numpy as np
import pandas as pd
matplotlib.use('Agg')
import seaborn as sns
from pathlib import Path
import matplotlib.pyplot as plt
from external_libs.hessian_eigenthings import compute_hessian_eigenthings
TRIAL_ID = uuid.uuid4().hex.upper()[0:6]
EXPE... | 5,329 | 35.758621 | 122 | py |
stable-continual-learning | stable-continual-learning-master/stable_sgd/data_utils.py | import numpy as np
import torch
import torchvision
from torch.utils.data import TensorDataset, DataLoader
import torchvision.transforms.functional as TorchVisionFunc
def get_permuted_mnist(task_id, batch_size):
"""
Get the dataset loaders (train and test) for a `single` task of permuted MNIST.
This function will b... | 5,087 | 34.333333 | 200 | py |
stable-continual-learning | stable-continual-learning-master/stable_sgd/models.py | import torch
import torch.nn as nn
from torch.nn.functional import relu, avg_pool2d
class MLP(nn.Module):
"""
Two layer MLP for MNIST benchmarks.
"""
def __init__(self, hiddens, config):
super(MLP, self).__init__()
self.W1 = nn.Linear(784, hiddens)
self.relu = nn.ReLU(inplace=True)
self.dropout_1 = nn.Dro... | 3,240 | 27.182609 | 87 | py |
stable-continual-learning | stable-continual-learning-master/external_libs/hessian_eigenthings/lanczos.py | """ Use scipy/ARPACK implicitly restarted lanczos to find top k eigenthings """
import numpy as np
import torch
from scipy.sparse.linalg import LinearOperator as ScipyLinearOperator
from scipy.sparse.linalg import eigsh
from warnings import warn
def lanczos(
operator,
num_eigenthings=10,
which="LM",
m... | 2,585 | 29.785714 | 87 | py |
stable-continual-learning | stable-continual-learning-master/external_libs/hessian_eigenthings/hvp_operator.py | """
This module defines a linear operator to compute the hessian-vector product
for a given pytorch model using subsampled data.
"""
import torch
from .power_iter import Operator, deflated_power_iteration
from .lanczos import lanczos
class HVPOperator(Operator):
"""
Use PyTorch autograd for Hessian Vec produc... | 6,060 | 32.486188 | 86 | py |
stable-continual-learning | stable-continual-learning-master/external_libs/hessian_eigenthings/power_iter.py | """
This module contains functions to perform power iteration with deflation
to compute the top eigenvalues and eigenvectors of a linear operator
"""
import numpy as np
import torch
from .utils import log, progress_bar
class Operator:
"""
maps x -> Lx for a linear operator L
"""
def __init__(self, s... | 4,147 | 28.841727 | 87 | py |
stable-continual-learning | stable-continual-learning-master/external_libs/hessian_eigenthings/spectral_density.py | import numpy as np
import torch
def _lanczos_step(vec, size, current_draw):
pass
def lanczos(
operator,
max_steps=20,
tol=1e-6,
num_lanczos_vectors=None,
init_vec=None,
use_gpu=False,
):
"""
Use the scipy.sparse.linalg.eigsh hook to the ARPACK lanczos algorithm
to find the t... | 1,764 | 27.467742 | 87 | py |
snare | snare-master/train.py | import os
from pathlib import Path
import hydra
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
import numpy as np
import random
import torch
import models
from data.dataset import CLIPGraspingDataset
from torch.utils.data import DataLoader
@hydra.main(config_path="cfgs... | 2,139 | 28.315068 | 97 | py |
snare | snare-master/models/single_cls.py | import numpy as np
import json
import os
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
from pytorch_lightning import LightningModule
import wandb
import models.aggregator as agg
class SingleClassifier(LightningModule):
def __init__(self, cfg, train_ds, val_ds):
... | 16,049 | 36.066975 | 226 | py |
snare | snare-master/models/zero_shot_cls.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.single_cls import SingleClassifier
class ZeroShotClassifier(SingleClassifier):
def __init__(self, cfg, train_ds, val_ds):
super().__init__(cfg, train_ds, val_ds)
self.logit_scale = nn.Parameter(torch... | 3,277 | 31.78 | 109 | py |
snare | snare-master/models/aggregator.py | import torch
import torch.nn as nn
class MaxPool(nn.Module):
def __init__(self, cfg):
super().__init__()
self.cfg = cfg
def forward(self, x):
x, _ = x.max(dim=-2) # [B 14 512] -> [B 512]
return x
class MeanPool(nn.Module):
def __init__(self, cfg):
super().__init_... | 1,455 | 26.471698 | 86 | py |
snare | snare-master/models/rotator.py | import numpy as np
import collections
import json
import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import wandb
from models.single_cls import SingleClassifier
class Rotator(SingleClassifier):
def __init__(self, cfg, train_ds, val_ds):
self.estimate_init_state = False
... | 23,767 | 41.980108 | 335 | py |
snare | snare-master/scripts/extract_clip_features.py | import os
import torch
from PIL import Image
import numpy as np
from numpy import asarray
import clip
import pickle, gzip, json
from tqdm import tqdm
# Set filepaths
shapenet_images_path = './data/shapenet-images/screenshots'
ann_files = ["train.json", "val.json", "test.json"]
folds = './amt/folds_adversarial'
keys... | 1,724 | 25.953125 | 89 | py |
snare | snare-master/scripts/aggregate_results.py |
import argparse
import json
import os
import numpy as np
import pandas as pd
from scipy.stats import ttest_ind
from tqdm import tqdm
clip_model_types = ['clip-single_cls-maxpool',
'clip-single_cls-meanpool',
'clip-single_cls-random_index',
'clip-single_cls-... | 13,282 | 46.270463 | 187 | py |
snare | snare-master/data/dataset.py | import os
import json
import torch
import torch.utils.data
import numpy as np
import gzip
import json
class CLIPGraspingDataset(torch.utils.data.Dataset):
def __init__(self, cfg, mode='train'):
self.total_views = 14
self.cfg = cfg
self.mode = mode
self.folds = os.path.join(self.cf... | 3,365 | 30.754717 | 130 | py |
pySDC | pySDC-master/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pySDC documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 11 15:58:40 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... | 10,415 | 28.258427 | 119 | py |
dswgan-paper | dswgan-paper-main/gan_estimation/ldw_gan.py | #wrapper function to save model weights and generate large dataset for
#any Lalonde dataset passed
import wgan
import torch
import pandas as pd
import numpy as np
import ot
from hypergrad import AdamHD
def wd_distance(real, gen):
n = real.shape[0]
a = np.ones(n)/n
d_gen = ot.emd2(a, a, M=ot.dist(real.to_numpy()... | 4,765 | 44.826923 | 156 | py |
dswgan-paper | dswgan-paper-main/monotonicity_penalty/monotonicity.py | import wgan
import pandas as pd
import torch
import numpy as np
import torch.nn.functional as F
from matplotlib import pyplot as plt
########################################
# setup
########################################
df = pd.read_feather("data/original_data/cps_merged.feather").drop("u75",1).drop("u74",1)
df = ... | 7,429 | 41.701149 | 160 | py |
HC-MGAN | HC-MGAN-main/fmnist.py | import argparse
import os
import sys
from utils.data import create_dataloader, merge_dataloaders
from tree.tree import Node, grow_tree_from_root
import torch
parser = argparse.ArgumentParser()
#main config
parser.add_argument('--dataset_path', type=str, default='data',
metavar='', help='Path fo... | 5,985 | 64.065217 | 202 | py |
HC-MGAN | HC-MGAN-main/sop.py | import argparse
import os
import sys
from utils.data import create_dataloader, merge_dataloaders
from tree.tree import Node, grow_tree_from_root
import torch
parser = argparse.ArgumentParser()
#main config
parser.add_argument('--dataset_path', type=str, default='data',
metavar='', help='Path f... | 5,968 | 63.880435 | 202 | py |
HC-MGAN | HC-MGAN-main/mnist.py | import argparse
import os
import sys
from utils.data import create_dataloader, merge_dataloaders
from tree.tree import Node, grow_tree_from_root
import torch
parser = argparse.ArgumentParser()
#omain config
parser.add_argument('--dataset_path', type=str, default='data',
metavar='', help='Path ... | 5,984 | 63.354839 | 202 | py |
HC-MGAN | HC-MGAN-main/models/models_32x32.py | import argparse
import os
from torch.autograd import Variable
import torch.nn as nn
import torch
from models.utils import verify_string_args, linear_block, Reshape, convT_block, conv_block
class Generator(nn.Module):
def __init__(self,
architecture = 'cnn',
nf=128,
... | 5,899 | 39.972222 | 225 | py |
HC-MGAN | HC-MGAN-main/models/models_general.py | import torch.nn as nn
import torch.nn.functional as F
import torch
class GeneratorSet(nn.Module):
def __init__(self, *gens):
super(GeneratorSet, self).__init__()
modules = nn.ModuleList()
for gen in gens:
modules.append(gen)
self.paths = modules
def forward... | 2,298 | 29.25 | 70 | py |
HC-MGAN | HC-MGAN-main/models/utils.py | from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
import torch
def get_seq_model_shapes(seq_model, input_shape, seq_model_name = 'seq_model'):
input_tensor = torch.zeros(*input_shape)
output = input_tensor
print("\n{} Layers:\n".format(seq_model_name))
for i... | 2,061 | 33.949153 | 116 | py |
HC-MGAN | HC-MGAN-main/models/gan.py | #torch imports
from torch.autograd import Variable
import torch
import numpy as np
class GAN:
def __init__(self,
gen_set,
disc,
clasf,
feature_layers,
optimizer_G,
optimizer_D,
optimizer_C,
... | 12,909 | 42.177258 | 143 | py |
HC-MGAN | HC-MGAN-main/models/models_28x28.py | import argparse
import os
from torch.autograd import Variable
import torch.nn as nn
import torch
from models.utils import verify_string_args, linear_block, Reshape, convT_block, conv_block
class Generator(nn.Module):
def __init__(self,
architecture = 'cnn',
nf=128,
... | 5,274 | 37.786765 | 225 | py |
HC-MGAN | HC-MGAN-main/tree/tree.py | import torch
from tree.refinement import refinement
from tree.raw_split import raw_split
import numpy as np
import copy
import os
from utils.soft_cluster import view_global_tree_logs, show, view_global_tree_logs
from utils.others import save_log_text, remove_bold_from_string, print_save_log, get_log_heading
class Nod... | 9,572 | 49.920213 | 184 | py |
HC-MGAN | HC-MGAN-main/tree/refinement.py | #basic imports
import argparse
import os
import numpy as np
import math
import shutil
import time
import datetime
import copy
import sys
#torch imports
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torchvision import datase... | 24,678 | 52.417749 | 182 | py |
HC-MGAN | HC-MGAN-main/tree/raw_split.py | #basic imports
import argparse
import os
import numpy as np
import math
import shutil
import time
import datetime
import copy
import sys
#torch imports
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
from torchvision import datase... | 20,482 | 49.575309 | 182 | py |
HC-MGAN | HC-MGAN-main/utils/others.py | import os
import math
import torch
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torchvision import datasets
import torch
from models.gan import GAN
def sum_dicts(dict_a, dict_b):
assert(dict_a.keys() == dict_b.keys())
return {k:dict_a[k]+dict_b[k] for k,v... | 3,956 | 34.648649 | 122 | py |
HC-MGAN | HC-MGAN-main/utils/data.py | import os
import math
import torch
import torchvision.transforms as transforms
from torchvision.utils import save_image, make_grid
from torchvision import datasets
from torch.utils.data import Dataset
import torch
class MyDataset(Dataset):
def __init__(self, dataset):
self.dataset = dataset
self.t... | 3,721 | 46.113924 | 137 | py |
HC-MGAN | HC-MGAN-main/utils/soft_cluster.py | import os
import numpy as np
import math
import matplotlib.pyplot as plt
import torch
import seaborn as sn
import pandas as pd
import numpy as np
import math
from sklearn import metrics
import sklearn
import scipy
import scipy.optimize as opt
import matplotlib.pyplot as plt
import torchvision.transforms as transforms... | 13,406 | 46.042105 | 176 | py |
DKVMN | DKVMN-main/evaluation/run.py | """
Usage:
run.py [options]
Options:
--length=<int> max length of question sequence [default: 50]
--questions=<int> num of question [default: 100]
--lr=<float> learning rate [default: 0.001]
--bs=<int> batch siz... | 3,566 | 34.67 | 118 | py |
DKVMN | DKVMN-main/evaluation/eval.py | import tqdm
import torch
import logging
import os
from sklearn import metrics
logger = logging.getLogger('main.eval')
def __load_model__(ckpt):
'''
ckpt: Path of the checkpoint
return: Checkpoint dict
'''
if os.path.isfile(ckpt):
checkpoint = torch.load(ckpt)
print("Successfully loa... | 1,882 | 35.921569 | 130 | py |
DKVMN | DKVMN-main/data/dataloader.py | import torch
import torch.utils.data as Data
from .readdata import DataReader
#assist2015/assist2015_train.txt assist2015/assist2015_test.txt
#assist2017/assist2017_train.txt assist2017/assist2017_test.txt
#assist2009/builder_train.csv assist2009/builder_test.csv
def getDataLoader(batch_size, num_of_questions, max_st... | 1,089 | 50.904762 | 78 | py |
DKVMN | DKVMN-main/model/memory.py | import torch
from torch import nn
class DKVMNHeadGroup(nn.Module):
def __init__(self, memory_size, memory_state_dim, is_write):
super(DKVMNHeadGroup, self).__init__()
""""
Parameters
memory_size: scalar
memory_state_dim: scalar
is_write: ... | 5,209 | 41.704918 | 117 | py |
DKVMN | DKVMN-main/model/model.py | import torch
import torch.nn as nn
from model.memory import DKVMN
class MODEL(nn.Module):
def __init__(self, n_question, batch_size, q_embed_dim, qa_embed_dim, memory_size, final_fc_dim):
super(MODEL, self).__init__()
self.n_question = n_question
self.batch_size = batch_size
self.... | 3,932 | 44.206897 | 129 | py |
probabilistic-ensemble | probabilistic-ensemble-main/baseline_train.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
from ensemble_model import BaselineModel
from noise_mnist_utils import normal_parse_params, rec_log_prob
import pickle
tfd = tfp.distributions
config = tf.ConfigProto()
config.gpu_options.allow_growth = True... | 6,002 | 34.732143 | 121 | py |
probabilistic-ensemble | probabilistic-ensemble-main/baseline_generate.py | import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import tensorflow_probability as tfp
from ensemble_model import BaselineModel
from noise_mnist_utils import normal_parse_params, rec_log_prob
tfd = tfp.distributions
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
tf.enable_eag... | 4,805 | 31.255034 | 105 | py |
probabilistic-ensemble | probabilistic-ensemble-main/ensemble_model.py | import numpy as np
import tensorflow as tf
from noise_mnist_utils import normal_parse_params, rec_log_prob
layers = tf.keras.layers
tf.enable_eager_execution()
class ResBlock(tf.keras.Model):
"""
Usual full pre-activation ResNet bottleneck block.
"""
def __init__(self, outer_dim, inner_dim):
... | 6,326 | 38.055556 | 107 | py |
finer | finer-main/finer.py | import itertools
import logging
import os
import time
import re
import datasets
import numpy as np
import tensorflow as tf
import wandb
from copy import deepcopy
from tqdm import tqdm
from gensim.models import KeyedVectors
from seqeval.metrics import classification_report
from seqeval.scheme import IOB2
from tensorflo... | 33,261 | 42.881266 | 138 | py |
finer | finer-main/models/callbacks.py | import logging
import numpy as np
import itertools
from tqdm import tqdm
from seqeval.metrics.sequence_labeling import precision_recall_fscore_support
from tensorflow.keras.callbacks import Callback, EarlyStopping
from configurations import Configuration
LOGGER = logging.getLogger(__name__)
class ReturnBestEarlyS... | 5,967 | 39.053691 | 104 | py |
finer | finer-main/models/transformer_bilstm.py | import tensorflow as tf
import numpy as np
from transformers import AutoTokenizer, TFAutoModel
from tf2crf import CRF
class TransformerBiLSTM(tf.keras.Model):
def __init__(
self,
model_name,
n_classes,
dropout_rate=0.1,
crf=False,
n_layers=1... | 5,047 | 29.409639 | 112 | py |
finer | finer-main/models/bilstm.py | import tensorflow as tf
import numpy as np
from tf2crf import CRF
class BiLSTM(tf.keras.Model):
def __init__(
self,
n_classes,
n_layers=1,
n_units=128,
dropout_rate=0.1,
crf=False,
word2vectors_weights=None,
subword_po... | 4,319 | 31 | 110 | py |
finer | finer-main/models/transformer.py | import tensorflow as tf
import numpy as np
from transformers import AutoTokenizer, TFAutoModel
from tf2crf import CRF
class Transformer(tf.keras.Model):
def __init__(
self,
model_name,
n_classes,
dropout_rate=0.1,
crf=False,
tokenizer=None,
... | 4,291 | 29.013986 | 112 | py |
UDAStrongBaseline | UDAStrongBaseline-master/sbs_traindbscan_unc.py | from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import random
import numpy as np
import sys
from sklearn.cluster import DBSCAN
# from sklearn.preprocessing import normalize
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import Dat... | 23,722 | 40.692443 | 151 | py |
UDAStrongBaseline | UDAStrongBaseline-master/sbs_traindbscan.py | from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import random
import numpy as np
import sys
from sklearn.cluster import DBSCAN
# from sklearn.preprocessing import normalize
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import Dat... | 22,980 | 40.0375 | 151 | py |
UDAStrongBaseline | UDAStrongBaseline-master/source_pretrain.py | from __future__ import print_function, absolute_import
import argparse
import os.path as osp
import random
import numpy as np
import sys
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
from UDAsbs import datasets
from UDAsbs import models
from UDAsbs.trainers... | 9,253 | 39.946903 | 154 | py |
UDAStrongBaseline | UDAStrongBaseline-master/sbs_trainkmeans.py | from __future__ import print_function, absolute_import
import argparse
import os
import os.path as osp
import random
import numpy as np
import sys
from sklearn.cluster import DBSCAN,KMeans
# from sklearn.preprocessing import normalize
import torch
from torch import nn
from torch.backends import cudnn
from torch.util... | 23,432 | 42.718284 | 162 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/evaluators.py | from __future__ import print_function, absolute_import
import time
from collections import OrderedDict
import numpy as np
import torch
from .evaluation_metrics import cmc, mean_ap
from .feature_extraction import extract_cnn_feature
from .utils.meters import AverageMeter
from .utils.rerank import re_ranking
def extra... | 6,592 | 37.109827 | 126 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/trainers.py | from __future__ import print_function, absolute_import
import time
import torch
import torch.nn as nn
from torch.nn import functional as F
from .evaluation_metrics import accuracy
from .loss import SoftTripletLoss_vallia, CrossEntropyLabelSmooth, SoftTripletLoss, SoftEntropy
from .memorybank.NCECriterion import Multi... | 24,831 | 41.01692 | 163 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/dist_metric.py | from __future__ import absolute_import
import torch
from .evaluators import extract_features
from .metric_learning import get_metric
class DistanceMetric(object):
def __init__(self, algorithm='euclidean', *args, **kwargs):
super(DistanceMetric, self).__init__()
self.algorithm = algorithm
... | 926 | 28.903226 | 63 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/multigpu.py | import time
import torch
# from util import MovingAverage
def aggreg_multi_gpu(model, dataloader, hc, dim, TYPE=torch.float64, model_gpus=1):
""""Accumulate activations and save them on multiple GPUs
* this function assumes the model is on the first `model_gpus` GPUs
so that it can write the acti... | 5,048 | 40.04878 | 123 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/sinkhornknopp.py | import torch
import torch.nn as nn
import time
import numpy as np
from UDAsbs.multigpu import gpu_mul_Ax, gpu_mul_xA, aggreg_multi_gpu, gpu_mul_AB
from scipy.special import logsumexp
def py_softmax(x, axis=None):
"""stable softmax"""
return np.exp(x - logsumexp(x, axis=axis, keepdims=True))
def cpu_sk(self)... | 8,028 | 36.872642 | 117 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/memorybank/alias_multinomial.py | import torch
class AliasMethod(object):
"""
From: https://hips.seas.harvard.edu/blog/2013/03/03/the-alias-method-efficient-sampling-with-many-discrete-outcomes/
"""
def __init__(self, probs):
if probs.sum() > 1:
probs.div_(probs.sum())
K = len(probs)
self.prob = to... | 1,968 | 28.833333 | 120 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/memorybank/NCEAverage.py | import torch
from torch import nn
from torch.nn import functional as F
import math
from numpy.testing import assert_almost_equal
def normalize(x, axis=-1):
"""Normalizing to unit length along the specified dimension.
Args:
x: pytorch Variable
Returns:
x: pytorch Variable, same shape as input
... | 22,548 | 44.370221 | 151 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/memorybank/NCECriterion.py | import torch
from torch import nn
import torch.nn.functional as F
eps = 1e-7
class NCECriterion(nn.Module):
"""
Eq. (12): L_{memorybank}
"""
def __init__(self, n_data):
super(NCECriterion, self).__init__()
self.n_data = n_data
def forward(self, x):
bsz = x.shape[0]
... | 3,840 | 29.975806 | 108 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/models/resnet_multi.py | from __future__ import absolute_import
from torch import nn
from torch.nn import functional as F
from torch.nn import Parameter
from torch.nn import init
import torchvision
import torch
from ..layers import (
IBN,
Non_local,
get_norm,
)
from .gem_pooling import GeneralizedMeanPoolingP
__all__ = ['ResNet'... | 9,954 | 36.566038 | 129 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/models/memory_bank.py | import torch
from torch import nn
from torch.nn import functional as F
import math
from numpy.testing import assert_almost_equal
def normalize(x, axis=-1):
"""Normalizing to unit length along the specified dimension.
Args:
x: pytorch Variable
Returns:
x: pytorch Variable, same shape as input
... | 7,998 | 38.019512 | 154 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/models/resnet.py | from __future__ import absolute_import
from torch import nn
from torch.nn import functional as F
from torch.nn import init
import torchvision
import torch
from ..layers import (
IBN,
Non_local,
get_norm,
)
from .gem_pooling import GeneralizedMeanPoolingP
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resn... | 8,933 | 34.879518 | 129 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/models/gem_pooling.py | # encoding: utf-8
"""
@author: l1aoxingyu
@contact: sherlockliao01@gmail.com
"""
import torch
import torch.nn.functional as F
from torch import nn
class GeneralizedMeanPooling(nn.Module):
r"""Applies a 2D power-average adaptive pooling over an input signal composed of several input planes.
The function comp... | 1,764 | 35.020408 | 106 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/models/dsbn.py | import torch
import torch.nn as nn
# Domain-specific BatchNorm
class DSBN2d(nn.Module):
def __init__(self, planes):
super(DSBN2d, self).__init__()
self.num_features = planes
self.BN_S = nn.BatchNorm2d(planes)
self.BN_T = nn.BatchNorm2d(planes)
def forward(self, x):
if ... | 2,669 | 32.797468 | 68 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/batch_norm.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
import logging
import torch
import torch.nn.functional as F
from torch import nn
__all__ = [
"BatchNorm",
"IBN",
"GhostBatchNorm",
"FrozenBatchNorm",
"SyncBatchNorm",
"get_norm",
]
class BatchNorm(nn.BatchNorm... | 8,165 | 39.029412 | 118 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/non_local.py | # encoding: utf-8
import torch
from torch import nn
from .batch_norm import get_norm
class Non_local(nn.Module):
def __init__(self, in_channels, bn_norm, num_splits, reduc_ratio=2):
super(Non_local, self).__init__()
self.in_channels = in_channels
self.inter_channels = reduc_ratio // red... | 1,901 | 33.581818 | 94 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/__init__.py | # encoding: utf-8
"""
@author: liaoxingyu
@contact: sherlockliao01@gmail.com
"""
from torch import nn
# from .batch_drop import BatchDrop
# from .attention import *
from .batch_norm import *
# from .context_block import ContextBlock
from .non_local import Non_local
# from .se_layer import SELayer
# from .frn import F... | 622 | 23.92 | 69 | py |
UDAStrongBaseline | UDAStrongBaseline-master/UDAsbs/layers/sync_bn/replicate.py | # -*- coding: utf-8 -*-
# File : replicate.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 27/01/2018
#
# This file is part of Synchronized-BatchNorm-PyTorch.
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
# Distributed under MIT License.
import functools
from torch.nn.parallel.da... | 3,226 | 32.968421 | 115 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.