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 |
|---|---|---|---|---|---|---|
CUFAR | CUFAR-main/model/modules/AKR_urbanpy.py | import torch
import torch.nn.functional as F
import random
from model.modules.augments import apply_augment
from copy import deepcopy
from model.modules.MMD import MMD
from src.utils import get_gt_densities
from model.modules.urbanpy_layers import batch_kl
import numpy as np
import math
class continual:
def __init... | 3,753 | 43.164706 | 112 | py |
CUFAR | CUFAR-main/model/modules/ODE.py | import torch
import torch.nn as nn
import torch.nn.functional as F
adjoint = False
if adjoint:
from .torchdiffeq import odeint_adjoint as odeint
print("use odeint_adjoint method")
else:
from .torchdiffeq import odeint
print("use odeint method")
def conv3x3(in_planes, out_planes,stride=1):
return n... | 4,584 | 28.96732 | 122 | py |
CUFAR | CUFAR-main/model/modules/memory_buffer.py | import torch
from random import shuffle
def reservoir(num_seen_examples: int, buffer_size: int, rand_len: int) -> int:
"""
Reservoir sampling algorithm.
:param num_seen_examples: the number of seen examples
:param buffer_size: the maximum buffer size
:rand_len: the length of random list
:return... | 6,994 | 47.916084 | 123 | py |
CUFAR | CUFAR-main/model/modules/MMD.py | import torch
class MMD:
def guassian_kernel(self, source, target, kernel_mul=2.0, kernel_num=5, fix_sigma=None):
n_samples = int(source.size()[0])+int(target.size()[0])
total = torch.cat([source, target], dim=0)
total0 = total.unsqueeze(0).expand(int(total.size(0)), \
... | 1,869 | 37.958333 | 98 | py |
CUFAR | CUFAR-main/model/modules/memory_buffer_urbanpy.py | import torch
from random import shuffle
def reservoir(num_seen_examples: int, buffer_size: int, rand_len: int) -> int:
"""
Reservoir sampling algorithm.
:param num_seen_examples: the number of seen examples
:param buffer_size: the maximum buffer size
:rand_len: the length of random list
:return... | 8,114 | 49.403727 | 128 | py |
CUFAR | CUFAR-main/model/modules/AKR.py | import torch
import torch.nn.functional as F
from model.modules.augments import apply_augment
from copy import deepcopy
from model.modules.MMD import MMD
import math
class continual:
def __init__(self, model, buffer, n_tasks, args):
self.model = model
self.n_task = n_tasks
self.buffer = buf... | 2,463 | 36.333333 | 110 | py |
CUFAR | CUFAR-main/model/modules/augments.py | """
CutBlur
Copyright 2020-present NAVER corp.
MIT license
"""
import numpy as np
import torch
import torch.nn.functional as F
def apply_augment(fine, coarse):
aug_methods = ["mixup", "cutmix", "cutmixup", "cutout", "blend",]
idx = np.random.choice(len(aug_methods), p= None)
aug = aug_methods[idx]
... | 5,606 | 31.789474 | 93 | py |
CUFAR | CUFAR-main/model/modules/urbanpy_layers.py | import torch.nn as nn
import torch
import torch.nn.functional as F
cuda = True if torch.cuda.is_available() else False
Tensor = torch.cuda.FloatTensor if cuda else torch.FloatTensor
import numpy as np
class LocalConv(nn.Module):
def __init__(self, width, block_size, in_chn, out_chn):
super(LocalConv, sel... | 3,233 | 37.963855 | 120 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/adjoint.py | import torch
import torch.nn as nn
from . import odeint
from .misc import _flatten, _flatten_convert_none_to_zeros
class OdeintAdjointMethod(torch.autograd.Function):
@staticmethod
def forward(ctx, *args):
assert len(args) >= 8, 'Internal error: all arguments required.'
y0, func, t, flat_para... | 5,459 | 39.746269 | 111 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/misc.py | import warnings
import torch
def _flatten(sequence):
flat = [p.contiguous().view(-1) for p in sequence]
return torch.cat(flat) if len(flat) > 0 else torch.tensor([])
def _flatten_convert_none_to_zeros(sequence, like_sequence):
flat = [
p.contiguous().view(-1) if p is not None else torch.zeros_li... | 6,630 | 32.831633 | 119 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/interp.py | import torch
from .misc import _convert_to_tensor, _dot_product
def _interp_fit(y0, y1, y_mid, f0, f1, dt):
"""Fit coefficients for 4th order polynomial interpolation.
Args:
y0: function value at the start of the interval.
y1: function value at the end of the interval.
y_mid: function... | 2,501 | 36.909091 | 110 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/tsit5.py | import torch
from .misc import _scaled_dot_product, _convert_to_tensor, _is_finite, _select_initial_step, _handle_unused_kwargs
from .solvers import AdaptiveStepsizeODESolver
from .rk_common import _RungeKuttaState, _ButcherTableau, _runge_kutta_step
# Parameters from Tsitouras (2011).
_TSITOURAS_TABLEAU = _ButcherTab... | 6,766 | 47.335714 | 120 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/adams.py | import collections
import torch
from .solvers import AdaptiveStepsizeODESolver
from .misc import (
_handle_unused_kwargs, _select_initial_step, _convert_to_tensor, _scaled_dot_product, _is_iterable,
_optimal_step_size, _compute_error_ratio
)
_MIN_ORDER = 1
_MAX_ORDER = 12
gamma_star = [
1, -1 / 2, -1 / 12... | 6,924 | 39.497076 | 120 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/solvers.py | import abc
import torch
from .misc import _assert_increasing, _handle_unused_kwargs
class AdaptiveStepsizeODESolver(object):
__metaclass__ = abc.ABCMeta
def __init__(self, func, y0, atol, rtol, **unused_kwargs):
_handle_unused_kwargs(self, unused_kwargs)
del unused_kwargs
self.func =... | 3,276 | 29.06422 | 89 | py |
CUFAR | CUFAR-main/model/modules/torchdiffeq/_impl/dopri5.py | # Based on https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/integrate
import torch
from .misc import (
_scaled_dot_product, _convert_to_tensor, _is_finite, _select_initial_step, _handle_unused_kwargs, _is_iterable,
_optimal_step_size, _compute_error_ratio
)
from .solvers import AdaptiveSt... | 5,555 | 44.170732 | 118 | py |
audioldm_eval | audioldm_eval-main/test.py | import torch
from audioldm_eval import EvaluationHelper
device = torch.device(f"cuda:{0}")
generation_result_path = "example/paired"
# generation_result_path = "example/unpaired"
target_audio_path = "example/reference"
evaluator = EvaluationHelper(16000, device)
# Perform evaluation, result will be print out and sa... | 410 | 24.6875 | 64 | py |
audioldm_eval | audioldm_eval-main/setup.py | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
# python3 setup.py sdist bdist_wheel
"""
@File : setup.py.py
@Contact : haoheliu@gmail.com
@License : (C)Copyright 2020-2100
@Modify Time @Author @Version @Desciption
------------ ------- -------- -----------
9/6/21 5:16 PM Haohe Liu ... | 4,278 | 27.337748 | 86 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/eval.py | import os
from audioldm_eval.datasets.load_mel import load_npy_data, MelPairedDataset, WaveDataset
import numpy as np
import argparse
import datetime
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from audioldm_eval.metrics.fad import FrechetAudioDistance
from audioldm_eval import calculate... | 17,189 | 35.652452 | 165 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/audio/stft.py | import torch
import torch.nn.functional as F
import numpy as np
from scipy.signal import get_window
from librosa.util import pad_center, tiny
from librosa.filters import mel as librosa_mel_fn
from audioldm_eval.audio.audio_processing import (
dynamic_range_compression,
dynamic_range_decompression,
window_s... | 6,248 | 33.910615 | 85 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/audio/tools.py | import torch
import numpy as np
from scipy.io.wavfile import write
import pickle
import json
from audioldm_eval.audio.audio_processing import griffin_lim
def save_pickle(obj, fname):
print("Save pickle at " + fname)
with open(fname, "wb") as f:
pickle.dump(obj, f)
def load_pickle(fname):
print("... | 1,782 | 28.229508 | 88 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/audio/audio_processing.py | import torch
import numpy as np
import librosa.util as librosa_util
from scipy.signal import get_window
def window_sumsquare(
window,
n_frames,
hop_length,
win_length,
n_fft,
dtype=np.float32,
norm=None,
):
"""
# from librosa 0.6
Compute the sum-square envelope of a window func... | 2,642 | 25.168317 | 86 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/metrics/kid.py | import torch
import numpy as np
from tqdm import tqdm
# 分多组,每组一定的数量,然后每组分别计算MMD
def calculate_kid(
featuresdict_1,
featuresdict_2,
subsets,
subset_size,
degree,
gamma,
coef0,
rng_seed,
feat_layer_name,
):
features_1 = featuresdict_1[feat_layer_name]
features_2 = featuresdi... | 3,054 | 28.095238 | 104 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/metrics/isc.py | import torch
import numpy as np
def calculate_isc(featuresdict, feat_layer_name, rng_seed, samples_shuffle, splits):
print("Computing Inception Score")
features = featuresdict[feat_layer_name]
assert torch.is_tensor(features) and features.dim() == 2
N, C = features.shape
if samples_shuffle:
... | 1,075 | 31.606061 | 84 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/metrics/kl.py | import torch
from pathlib import Path
import os
def path_to_sharedkey(path, dataset_name, classes=None):
if dataset_name.lower() == "vggsound":
# a generic oneliner which extracts the unique filename for the dataset.
# Works on both FakeFolder and VGGSound* datasets
sharedkey = Path(path).... | 6,194 | 39.227273 | 110 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/metrics/fad.py | """
Calculate Frechet Audio Distance betweeen two audio directories.
Frechet distance implementation adapted from: https://github.com/mseitzer/pytorch-fid
VGGish adapted from: https://github.com/harritaylor/torchvggish
"""
import os
import numpy as np
import torch
from torch import nn
from scipy import linalg
from t... | 7,824 | 37.170732 | 103 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/metrics/fid.py | import torch
import numpy as np
import scipy.linalg
# FID评价保真度,越小越好
def calculate_fid(
featuresdict_1, featuresdict_2, feat_layer_name
): # using 2048 layer to calculate
eps = 1e-6
features_1 = featuresdict_1[feat_layer_name]
features_2 = featuresdict_2[feat_layer_name]
assert torch.is_tensor(fea... | 2,210 | 30.585714 | 98 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/datasets/load_mel.py | import torch
import os
import numpy as np
import torchaudio
from tqdm import tqdm
# import librosa
def pad_short_audio(audio, min_samples=32000):
if(audio.size(-1) < min_samples):
audio = torch.nn.functional.pad(audio, (0, min_samples - audio.size(-1)), mode='constant', value=0.0)
return audio
class M... | 6,635 | 33.206186 | 169 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/datasets/transforms.py | import torch
from specvqgan.modules.losses.vggishish.transforms import Crop
class FromMinusOneOneToZeroOne(object):
"""Actually, it doesnot do [-1, 1] --> [0, 1] as promised. It would, if inputs would be in [-1, 1]
but reconstructed specs are not."""
def __call__(self, item):
item["image"] = (ite... | 1,246 | 30.974359 | 102 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/melception.py | import torch
import torch.nn.functional as F
from torchvision.models.inception import BasicConv2d, Inception3
class Melception(Inception3):
def __init__(
self, num_classes, features_list, feature_extractor_weights_path, **kwargs
):
# inception = Melception(num_classes=309)
super().__in... | 4,622 | 34.837209 | 107 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/inception3.py | """
Adapted from `https://github.com/pytorch/vision`.
Modified by Vladimir Iashin, 2021.
"""
import math
import sys
from contextlib import redirect_stdout
import torch
import torch.nn as nn
import torch.nn.functional as F
from omegaconf.listconfig import ListConfig
from torch.hub import load_state_dict_from_url
from t... | 20,706 | 37.922932 | 140 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/melception_audioset.py | import torch
import torch.nn.functional as F
from torchvision.models.inception import BasicConv2d, Inception3
from collections import OrderedDict
def load_module2model(state_dict):
new_state_dict = OrderedDict()
for k, v in state_dict.items(): # k为module.xxx.weight, v为权重
if k[:7] == "module.":
... | 5,287 | 34.972789 | 107 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/panns/main.py | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], "../utils"))
import numpy as np
import argparse
import time
import logging
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torch.utils.data
from utilities import (
create_folder,
get_filena... | 14,159 | 28.685535 | 91 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/panns/losses.py | import torch
import torch.nn.functional as F
def clip_bce(output_dict, target_dict):
"""Binary crossentropy loss."""
return F.binary_cross_entropy(output_dict["clipwise_output"], target_dict["target"])
def get_loss_func(loss_type):
if loss_type == "clip_bce":
return clip_bce
| 300 | 22.153846 | 88 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/panns/evaluate.py | from sklearn import metrics
from pytorch_utils import forward
class Evaluator(object):
def __init__(self, model):
"""Evaluator.
Args:
model: object
"""
self.model = model
def evaluate(self, data_loader):
"""Forward evaluation data and calculate statistics.
... | 1,085 | 24.255814 | 85 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/panns/finetune_template.py | import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], "../utils"))
import numpy as np
import argparse
import h5py
import math
import time
import logging
import matplotlib.pyplot as plt
import torch
torch.backends.cudnn.benchmark = True
torch.manual_seed(0)
import torch.nn as nn
import torch.nn.functional... | 4,234 | 26.861842 | 88 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/panns/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchlibrosa.stft import Spectrogram, LogmelFilterBank
from torchlibrosa.augmentation import SpecAugmentation
import os
from audioldm_eval.feature_extractors.panns.pytorch_utils import (
do_mixup,
interpolate,
pad_framewise_output,
)
... | 128,914 | 30.736829 | 97 | py |
audioldm_eval | audioldm_eval-main/audioldm_eval/feature_extractors/panns/pytorch_utils.py | import numpy as np
import time
import torch
import torch.nn as nn
def move_data_to_device(x, device):
if "float" in str(x.dtype):
x = torch.Tensor(x)
elif "int" in str(x.dtype):
x = torch.LongTensor(x)
else:
return x
return x.to(device)
def do_mixup(x, mixup_lambda):
"""... | 8,592 | 28.733564 | 84 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/main.py | import os
import random
import shutil
import torch
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from config import *
from train import train
from utils import generate_dataset, generate_model, show_config
def main():
# print configuration
show_config({
'BASIC CONFIG': BASIC_C... | 1,754 | 21.5 | 63 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/modules.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.utils.data.sampler import Sampler
class ContrastiveModel(nn.Module):
def __init__(self, backbone, pretrained=True, head='mlp', dim_in=2048, feat_dim=128):
super(ContrastiveModel, self).__init_... | 5,041 | 36.073529 | 89 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/resnet.py | # from torchvision: https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
import torch
from torch import Tensor
import torch.nn as nn
from torch.hub import load_state_dict_from_url
from typing import Type, Any, Callable, Union, List, Optional
__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50... | 15,555 | 40.044855 | 111 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/utils.py | import os
import pickle
import warnings
# import apex
import torch
from tqdm import tqdm
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
from modules import ContrastiveModel
from data import generate_dataset_from_pickle, DatasetFromDict, data_transforms
def generate_dataset(data... | 3,762 | 29.844262 | 137 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/data.py | import os
import pickle
import random
from PIL import Image
from torchvision import transforms
from torch.utils.data import Dataset
def generate_dataset_from_pickle(data_path, pkl, data_config, transform):
data = pickle.load(open(pkl, 'rb'))
train_set, val_set = data['train'], data['val']
train_dataset ... | 4,576 | 29.513333 | 100 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/config.py | import resnet
BASIC_CONFIG = {
'network': 'resnet50', # shoud be one name in NET_CONFIG below
'data_path': '/path/to/your/data/folder', # preprocessed dataset folder
'data_index': '/path/to/your/predicted/result/file', # pickle file with lesion predicted results
'save_path': './checkpoints',
'r... | 3,850 | 44.845238 | 162 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/train.py | import os
import torch
import torchvision
import torch.nn as nn
from tqdm import tqdm
from torch.utils.data import DataLoader
from modules import *
from utils import print_msg
from utils import print_msg, inverse_normalize
def train(model, train_config, data_config, train_dataset, val_dataset, save_path, device, lo... | 7,191 | 32.924528 | 104 | py |
Lesion-based-Contrastive-Learning | Lesion-based-Contrastive-Learning-main/detection/configs/_base_/models/faster_rcnn_r50_fpn.py | model = dict(
type='FasterRCNN',
pretrained='torchvision://resnet50',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch'... | 3,640 | 31.508929 | 77 | py |
emonet | emonet-master/test.py | import numpy as np
from pathlib import Path
import argparse
import torch
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.data.sampler import WeightedRandomSampler
from torchvision import transforms
from emonet.models import EmoNet
from emonet.data import AffectNet
from emonet.data_augme... | 3,121 | 44.911765 | 275 | py |
emonet | emonet-master/emonet/evaluation.py | import numpy as np
import torch
def evaluate_metrics(ground_truth, predictions, metrics, verbose=True, print_tex=True):
results = {}
for name, metric in metrics.items():
results[name] = metric(ground_truth, predictions)
if verbose:
print(', '.join(f'{name}={results[name]:.2f}' for name in m... | 7,930 | 37.31401 | 171 | py |
emonet | emonet-master/emonet/models/emonet.py | #########################################################
# #
# Authors: Jean Kossaifi, Antoine Toisoul, Adrian Bulat #
# #
#########################################################
import torch
import torch.nn ... | 8,463 | 35.960699 | 145 | py |
emonet | emonet-master/emonet/data/affecnet.py | from pathlib import Path
import pickle
import numpy as np
import torch
import math
from torch.utils.data import Dataset
from skimage import io
class AffectNet(Dataset):
_expressions = {0: 'neutral', 1:'happy', 2:'sad', 3:'surprise', 4:'fear', 5:'disgust', 6:'anger', 7:'contempt', 8:'none'}
_expressions_indic... | 5,964 | 43.185185 | 141 | py |
CNN-PS-ECCV2018 | CNN-PS-ECCV2018-master/test.py | # Copyright 2018, Satoshi Ikehata, National Institute of Informatics (sikehata@nii.ac.jp)
import importlib
import numpy as np
import pydot
import os
import keras
from keras import backend as K
from keras.utils.vis_utils import plot_model
from keras.models import load_model
from keras.utils import multi_gpu_model
from ... | 1,893 | 36.137255 | 214 | py |
CNN-PS-ECCV2018 | CNN-PS-ECCV2018-master/train.py | # Copyright 2018, Satoshi Ikehata, National Institute of Informatics (sikehata@nii.ac.jp)
w = 32 # size of observation map
import importlib
import numpy as np
import pydot
import os
import keras
from keras import backend as K
from keras.utils.vis_utils import plot_model
from keras.models import load_model
from keras.u... | 3,159 | 37.072289 | 132 | py |
CNN-PS-ECCV2018 | CNN-PS-ECCV2018-master/mymodule/cnn_models.py | from keras import backend as K
from keras.models import Input, Model
from keras.layers.core import Layer, Dense, Dropout, Activation, Flatten, Reshape, Permute, Lambda
from keras.layers import Merge, merge, Concatenate, concatenate, MaxPooling1D, multiply
from keras.layers.convolutional import Convolution2D, MaxPooling... | 3,519 | 29.08547 | 129 | py |
MOON | MOON-main/main.py | import numpy as np
import json
import torch
import torch.optim as optim
import torch.nn as nn
import argparse
import logging
import os
import copy
import datetime
import random
from model import *
from utils import *
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--model', type=str,... | 30,664 | 44.497033 | 199 | py |
MOON | MOON-main/resnetcifar.py | '''ResNet in PyTorch.
For Pre-activation ResNet, see 'preact_resnet.py'.
Reference:
[1] Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. arXiv:1512.03385
'''
import torch
import torch.nn as nn
def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
"""... | 8,633 | 37.035242 | 106 | py |
MOON | MOON-main/utils.py | import os
import logging
import numpy as np
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
from torch.autograd import Variable
import torch.nn.functional as F
import torch.nn as nn
import random
from sklearn.metrics import confusion_matrix
from model import *
from datasets imp... | 13,974 | 36.77027 | 124 | py |
MOON | MOON-main/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import torchvision.models as models
from resnetcifar import ResNet18_cifar10, ResNet50_cifar10
#import pytorch_lightning as pl
class MLP_header(nn.Module):
def __init__(self,):
super(MLP_header, self).__init__()
self.f... | 22,157 | 33.036866 | 149 | py |
MOON | MOON-main/datasets.py | import torch.utils.data as data
from PIL import Image
import numpy as np
import torchvision
from torchvision.datasets import MNIST, EMNIST, CIFAR10, CIFAR100, SVHN, FashionMNIST, ImageFolder, DatasetFolder, utils
import os
import os.path
import logging
logging.basicConfig()
logger = logging.getLogger()
logger.setLeve... | 5,402 | 29.016667 | 120 | py |
impact-driven-exploration | impact-driven-exploration-main/main.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from src.arguments import parser
from src.algos.torchbeast import train as train_vanilla
from src.algos.count import trai... | 1,431 | 34.8 | 78 | py |
impact-driven-exploration | impact-driven-exploration-main/src/losses.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
def compute_baseline_loss(adva... | 1,691 | 33.530612 | 76 | py |
impact-driven-exploration | impact-driven-exploration-main/src/arguments.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import argparse
parser = argparse.ArgumentParser(description='PyTorch Scalable Agent')
# General Settings.
parser.add_argu... | 6,039 | 54.925926 | 123 | py |
impact-driven-exploration | impact-driven-exploration-main/src/atari_wrappers.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
# This code was taken from
# https://github.com/openai/baselines/blob/master/baselines/common/atari_wrappers.py
# and modif... | 11,074 | 30.197183 | 96 | py |
impact-driven-exploration | impact-driven-exploration-main/src/utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
import typing
import gym
import threading
from torch import multiprocessing as mp
import logging
import trace... | 9,333 | 35.319066 | 94 | py |
impact-driven-exploration | impact-driven-exploration-main/src/models.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
def init(module, weight_init, ... | 23,471 | 38.054908 | 126 | py |
impact-driven-exploration | impact-driven-exploration-main/src/env_utils.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import gym
import torch
from collections import deque, defaultdict
from gym import spaces
import numpy as np
from gym_mini... | 6,306 | 31.848958 | 183 | py |
impact-driven-exploration | impact-driven-exploration-main/src/core/vtrace.py | # This file taken from
# https://github.com/deepmind/scalable_agent/blob/
# cd66d00914d56c8ba2f0615d9cdeefcb169a8d70/vtrace.py
# and modified.
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | 4,487 | 34.619048 | 80 | py |
impact-driven-exploration | impact-driven-exploration-main/src/core/vtrace_test.py | # This file taken from
# https://github.com/deepmind/scalable_agent/blob/
# d24bd74bd53d454b7222b7f0bea57a358e4ca33e/vtrace_test.py
# and modified.
# Copyright 2018 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licen... | 9,841 | 36.280303 | 80 | py |
impact-driven-exploration | impact-driven-exploration-main/src/core/environment.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import torch
def _format_frame(frame):
frame = torch.from_numpy(frame)
return frame.view((1, 1) + frame.shape) # ... | 2,192 | 30.782609 | 75 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/count.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import threading
import time
import timeit
import pprint
import numpy as np
import torch
from tor... | 10,053 | 32.851852 | 102 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/rnd.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import sys
import threading
import time
import timeit
import pprint
import numpy as np
import tor... | 12,919 | 36.020057 | 130 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/ride.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import threading
import time
import timeit
import pprint
import numpy as np
import torch
from tor... | 15,374 | 37.4375 | 117 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/torchbeast.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import threading
import time
import timeit
import pprint
import numpy as np
import torch
from tor... | 8,845 | 31.762963 | 92 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/only_episodic_counts.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import threading
import time
import timeit
import pprint
import numpy as np
import torch
from tor... | 10,001 | 32.905085 | 92 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/no_episodic_counts.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import sys
import threading
import time
import timeit
import pprint
import numpy as np
import tor... | 14,224 | 36.044271 | 106 | py |
impact-driven-exploration | impact-driven-exploration-main/src/algos/curiosity.py | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import sys
import threading
import time
import timeit
import pprint
import numpy as np
import tor... | 15,696 | 37.662562 | 117 | py |
CoSMIG | CoSMIG-main/main.py | #python main.py --data-name DrugBank --max-nodes-per-hop 200
#python main.py --testing --no-train --data-name DGIdb --max-nodes-per-hop 200
#python main.py --testing --no-train --probe --data-name IDrugBank --max-nodes-per-hop 200
from operator import mod
import torch
import numpy as np
import os
import os.path
import... | 14,552 | 31.196903 | 113 | py |
CoSMIG | CoSMIG-main/parser.py |
import torch
import random
import argparse
import numpy as np
def get_basic_configs():
# Arguments
parser = argparse.ArgumentParser(description='Inductive Graph-based Matrix Completion')
# general settings
parser.add_argument('--testing', action='store_true', default=False,
he... | 7,317 | 59.983333 | 100 | py |
CoSMIG | CoSMIG-main/layer.py |
from typing import Optional, Union, Tuple
from torch._C import device
from torch_geometric.typing import OptTensor, Adj
import math
import torch
from torch import Tensor
import torch.nn.functional as F
from torch.nn import Parameter as Param
from torch.nn import Parameter
from torch_scatter import scatter
from torch_... | 10,304 | 36.472727 | 100 | py |
CoSMIG | CoSMIG-main/dataset.py |
import numpy as np
import random
from tqdm import tqdm
import os, sys, pdb, math, time
from copy import deepcopy
import multiprocessing as mp
import networkx as nx
import argparse
import scipy.io as sio
import scipy.sparse as ssp
import torch
from torch_geometric.data import Data, Dataset, InMemoryDataset
from sklear... | 13,962 | 37.35989 | 97 | py |
CoSMIG | CoSMIG-main/models.py |
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Linear, Conv1d
from torch_geometric.nn import MessagePassing, GCNConv, RGCNConv, global_sort_pool, global_add_pool
from torch_geometric.utils import dropout_adj
from dataset import *
import pdb
import time
from typing ... | 12,984 | 39.833333 | 102 | py |
CoSMIG | CoSMIG-main/train.py |
import time
import os
import math
import multiprocessing as mp
import numpy as np
import networkx as nx
import pandas as pd
import torch
import torch.nn.functional as F
from torch import tensor
from torch.optim import Adam
from sklearn.model_selection import StratifiedKFold
from torch_geometric.data import DataLoader,... | 14,951 | 33.136986 | 125 | py |
mmd | mmd-master/translate.py | import os
import sys
sys.path.append('..')
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
import json
import cPickle as pkl
import random
import time
import math
# import matplotlib.pyplot as plt
# import matplotlib.ticker as ticker
# plt.s... | 8,992 | 42.235577 | 119 | py |
mmd | mmd-master/train.py | import os
import sys
sys.path.append('..')
import torch
import torch.nn as nn
from torch.autograd import Variable
from torch import optim
import torch.nn.functional as F
from torch.optim import lr_scheduler
import json
import cPickle as pkl
import random
import time
import math
import numpy as np
import logging
import ... | 14,538 | 43.057576 | 115 | py |
mmd | mmd-master/modules/encoderRNN.py | #!/usr/bin/env python
# # -*- coding: utf-8 -*-
""" Encoder for Sequence to Sequence models """
__author__ = "shubhamagarwal92"
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
import torch_utils as torch_utils
... | 4,405 | 46.891304 | 90 | py |
mmd | mmd-master/modules/image_encoder.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_utils as torch_utils
class ImageEncoder(nn.Module):
r"""
Args:
Input:
Output:
"""
def __init__(self, image_in_size, image_out_size, bias=False, activation='Tanh'):
super(ImageEncoder, self).__init__()
self.input_size = ... | 729 | 25.071429 | 82 | py |
mmd | mmd-master/modules/bridge.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch_utils as torch_utils
class BridgeLayer(nn.Module):
"""
Bridge layer is used to pass encoder final representation to decoder.
It is not necessary that encoder and decoder have same number of hidden states.
Activation : currently relu
... | 1,666 | 38.690476 | 88 | py |
mmd | mmd-master/modules/torch_utils.py | # Contains the wrappers for torch functions, useful for model
import torch
import torch.nn as nn
from torch.autograd import Variable
def to_var(x, on_cpu=False):
"""Tensor => Variable"""
x = Variable(x)
if torch.cuda.is_available() and not on_cpu:
x = gpu_wrapper(x)
return x
def object_type(obj):
""" Return w... | 2,412 | 29.544304 | 66 | py |
mmd | mmd-master/modules/encoder_test.py | import torch
import torch.nn as nn
from torch.autograd import Variable
#####################################################################################
#-------------------------------------------------------------------------------------
#Encoder
#-----------------------------------------------------------------... | 1,043 | 27.216216 | 86 | py |
mmd | mmd-master/modules/decoder.py | # Adapted from https://github.com/ctr4si/A-Hierarchical-Latent-Structure-for-\
# Variational-Conversation-Modeling/blob/master/model/layers/decoder.py
import random
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import functional as F
from torch_utils import to_var
import math
from... | 8,074 | 29.938697 | 87 | py |
mmd | mmd-master/modules/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from encoderRNN import EncoderRNN
from image_encoder import ImageEncoder
from bridge import BridgeLayer
from contextRNN import ContextRNN
from decoder import DecoderRNN
import torch_utils as torch_utils
from torch_uti... | 17,500 | 48.022409 | 108 | py |
mmd | mmd-master/modules/attention.py | # Adapted from
# https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/modules/GlobalAttention.py
# https://github.com/spro/practical-pytorch/blob/master/seq2seq-translation/
# seq2seq-translation-batched.ipynb
# https://github.com/google/seq2seq/blob/master/seq2seq/decoders/attention.py
import torch
import torch.nn ... | 7,365 | 43.373494 | 103 | py |
mmd | mmd-master/modules/kb_encoder.py | import torch
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
import torch_utils as torch_utils
class KbEncoder(nn.Module):
def __init__(self, vocab_size, emb_size, hidden_size,
rnn_type='GRU', num_layers... | 1,795 | 47.540541 | 84 | py |
mmd | mmd-master/modules/contextRNN.py | import torch
import torch.nn as nn
import torch_utils as torch_utils
class ContextRNN(nn.Module):
r"""
Context RNN for HRED model
Args:
rnn_type (str): type of RNN [LSTM, GRU]
bidirectional (bool) : use a bidirectional RNN
num_layers (int) : number of stacked layers
context_hidden_size (int) : hidde... | 1,877 | 39.826087 | 85 | py |
mmd | mmd-master/utils/utils.py | import torch
import random
import math
import time
import json
from torch.autograd import Variable
import os
import numpy as np
from annoy import AnnoyIndex
def gpu_wrapper(input_var, use_cuda=True):
""" Port variable/tensor to gpu """
if use_cuda:
input_var = input_var.cuda()
return input_var
def convert_to_ten... | 3,861 | 41.43956 | 101 | py |
EasyMocap | EasyMocap-master/apps/neuralbody/train_pl.py | # Training code based on PyTorch-Lightning
import os
from os.path import join
from easymocap.mytools.debug_utils import myerror
import torch
from easymocap.config import load_object, Config
import pytorch_lightning as pl
from pytorch_lightning.loggers import TensorBoardLogger
from pytorch_lightning import seed_everyth... | 9,485 | 39.712446 | 133 | py |
EasyMocap | EasyMocap-master/apps/annotation/annot_keypoints.py | '''
@ Date: 2021-03-28 21:23:34
@ Author: Qing Shuai
@ LastEditors: Qing Shuai
@ LastEditTime: 2022-05-24 14:27:46
@ FilePath: /EasyMocapPublic/apps/annotation/annot_keypoints.py
'''
from easymocap.annotator.basic_visualize import capture_screen, plot_skeleton_factory, resize_to_screen
import os
from os.path ... | 5,481 | 39.014599 | 175 | py |
EasyMocap | EasyMocap-master/scripts/preprocess/extract_video.py | '''
@ Date: 2021-01-13 20:38:33
@ Author: Qing Shuai
@ LastEditors: Qing Shuai
@ LastEditTime: 2021-04-13 21:43:52
@ FilePath: /EasyMocapRelease/scripts/preprocess/extract_video.py
'''
import os, sys
import cv2
from os.path import join
from tqdm import tqdm
from glob import glob
import numpy as np
mkdir = la... | 11,163 | 37.629758 | 151 | py |
EasyMocap | EasyMocap-master/easymocap/estimator/yolohrnet_wrapper.py | from ..annotator.file_utils import read_json
from .wrapper_base import check_result, create_annot_file, save_annot
from glob import glob
from os.path import join
from tqdm import tqdm
import os
import cv2
import numpy as np
def detect_frame(detector, img, pid=0, only_bbox=False):
lDetections = detector.detect([img... | 4,950 | 39.581967 | 113 | py |
EasyMocap | EasyMocap-master/easymocap/estimator/SPIN/spin_api.py | '''
@ Date: 2020-10-23 20:07:49
@ Author: Qing Shuai
@ LastEditors: Qing Shuai
@ LastEditTime: 2022-07-14 12:44:30
@ FilePath: /EasyMocapPublic/easymocap/estimator/SPIN/spin_api.py
'''
"""
Demo code
To run our method, you need a bounding box around the person. The person needs to be centered inside the bound... | 14,215 | 38.709497 | 379 | py |
EasyMocap | EasyMocap-master/easymocap/estimator/SPIN/models.py | import torch
import torch.nn as nn
import torchvision.models.resnet as resnet
import numpy as np
import math
from torch.nn import functional as F
def rot6d_to_rotmat(x):
"""Convert 6D rotation representation to 3x3 rotation matrix.
Based on Zhou et al., "On the Continuity of Rotation Representations in Neural ... | 6,479 | 34.801105 | 103 | py |
EasyMocap | EasyMocap-master/easymocap/estimator/HRNet/hrnet.py | import torch
from torch import nn
from .modules import BasicBlock, Bottleneck
class StageModule(nn.Module):
def __init__(self, stage, output_branches, c, bn_momentum):
super(StageModule, self).__init__()
self.stage = stage
self.output_branches = output_branches
self.branches = nn.... | 9,807 | 44.198157 | 117 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.