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 |
|---|---|---|---|---|---|---|
Meta-RL-Harlow | Meta-RL-Harlow-master/models/ep_lstm_cell.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from dataclasses import dataclass
import numpy as np
import torch as T
from torch import nn
from torch import Tensor
from torch.nn import functional as F
# from models.ep_lstm imp... | 5,570 | 28.47619 | 125 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_conv_lstm.py | import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.model_zoo as model_zoo
model_urls = {
'cifar10': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar10-d875770b.pth',
'cifar100': 'http://ml.cs.tsinghua.edu.cn/~chenxi/pytorch-models/cifar100-3... | 6,009 | 33.94186 | 104 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_dnd_lstm.py | """
A DND-based LSTM based on ...
Ritter, et al. (2018).
Been There, Done That: Meta-Learning with Episodic Recall.
Proceedings of the International Conference on Machine Learning (ICML).
"""
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from models.dnd import DND
from models.... | 3,612 | 27.448819 | 85 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_lstm_simple.py | import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from models.rgu import RGUnit
CELLS = {
'lstm': nn.LSTM,
'gru': nn.GRU,
'rgu': RGUnit
}
class A3C_LSTM(nn.Module):
def __init__(self, input_dim, hidden_size, num_actions, c... | 3,913 | 29.341085 | 88 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/densenet_lstm.py | import numpy as np
import torch as T
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self, freeze = True):
super(Encoder,self).__init__()
original_model = torchvision.models.densenet161(pretrained=True)
self.features = T.nn.Se... | 2,587 | 31.759494 | 82 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/a3c_lstm.py | import numpy as np
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
class A3C_LSTM(nn.Module):
def __init__(self, config, num_actions):
super(A3C_LSTM, self).__init__()
self.encoder = nn.Sequential(
nn.Conv2d(3, 16, kernel_si... | 3,636 | 33.638095 | 88 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/rgu_cell.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from abc import ABC, abstractmethod
from dataclasses import dataclass
import torch as T
from torch import nn
from torch.nn import functional as F
from torch import Tensor
import p... | 5,418 | 26.93299 | 101 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/rgu.py | from typing import (
Tuple,
List,
Optional,
Dict,
Callable,
Union,
cast,
)
from collections import namedtuple
from abc import ABC, abstractmethod
from dataclasses import dataclass
import numpy as np
import torch as T
from torch import nn
from torch.nn import functional as F
from torch imp... | 3,620 | 25.23913 | 75 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/models/resnet_lstm.py | import numpy as np
import torch as T
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class Encoder(nn.Module):
def __init__(self):
super(Encoder,self).__init__()
original_model = torchvision.models.resnet18(pretrained=False)
self.features = T.nn.Sequential(*list(or... | 1,788 | 30.385965 | 78 | py |
Meta-RL-Harlow | Meta-RL-Harlow-master/Harlow_1D/train.py | import os
import yaml
import pickle
import argparse
import numpy as np
import torch as T
import torch.nn as nn
from torch.nn import functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
from datetime import datetime
from collections import namedtuple
from Harlow_1D.harlow import H... | 15,561 | 30.502024 | 108 | py |
FEAT | FEAT-master/pretrain.py | import argparse
import os
import os.path as osp
import shutil
import torch
import torch.nn.functional as F
from torch.utils.data import DataLoader
from model.models.classifier import Classifier
from model.dataloader.samplers import CategoriesSampler
from model.utils import pprint, set_gpu, ensure_path, Averager, Timer,... | 9,931 | 42.946903 | 147 | py |
FEAT | FEAT-master/train_fsl.py | import numpy as np
import torch
from model.trainer.fsl_trainer import FSLTrainer
from model.utils import (
pprint, set_gpu,
get_command_line_parser,
postprocess_args,
)
# from ipdb import launch_ipdb_on_exception
if __name__ == '__main__':
parser = get_command_line_parser()
args = postprocess_args(... | 561 | 20.615385 | 48 | py |
FEAT | FEAT-master/model/data_parallel.py | from torch.nn.parallel import DataParallel
import torch
from torch.nn.parallel._functions import Scatter
from torch.nn.parallel.parallel_apply import parallel_apply
def scatter(inputs, target_gpus, chunk_sizes, dim=0):
r"""
Slices tensors into approximately equal chunks and
distributes them across given GP... | 3,764 | 40.373626 | 84 | py |
FEAT | FEAT-master/model/utils.py | import os
import shutil
import time
import pprint
import torch
import argparse
import numpy as np
def one_hot(indices, depth):
"""
Returns a one-hot tensor.
This is a PyTorch equivalent of Tensorflow's tf.one_hot.
Parameters:
indices: a (n_batch, m) Tensor or (m) Tensor.
depth: a scalar. ... | 7,275 | 38.32973 | 166 | py |
FEAT | FEAT-master/model/trainer/base.py | import abc
import torch
import os.path as osp
from model.utils import (
ensure_path,
Averager, Timer, count_acc,
compute_confidence_interval,
)
from model.logger import Logger
class Trainer(object, metaclass=abc.ABCMeta):
def __init__(self, args):
self.args = args
# ensure_path(
... | 3,407 | 33.77551 | 103 | py |
FEAT | FEAT-master/model/trainer/fsl_trainer.py | import time
import os.path as osp
import numpy as np
import torch
import torch.nn.functional as F
from model.trainer.base import Trainer
from model.trainer.helpers import (
get_dataloader, prepare_model, prepare_optimizer,
)
from model.utils import (
pprint, ensure_path,
Averager, Timer, count_acc, one_ho... | 7,495 | 35.038462 | 132 | py |
FEAT | FEAT-master/model/trainer/helpers.py | import torch
import torch.nn as nn
import numpy as np
import torch.optim as optim
from torch.utils.data import DataLoader
from model.dataloader.samplers import CategoriesSampler, RandomSampler, ClassSampler
from model.models.protonet import ProtoNet
from model.models.matchnet import MatchNet
from model.models.feat impo... | 6,374 | 38.351852 | 100 | py |
FEAT | FEAT-master/model/networks/dropblock.py | import torch
import torch.nn.functional as F
from torch import nn
from torch.distributions import Bernoulli
class DropBlock(nn.Module):
def __init__(self, block_size):
super(DropBlock, self).__init__()
self.block_size = block_size
def forward(self, x, gamma):
# shape: (bsize, channel... | 2,392 | 37.596774 | 129 | py |
FEAT | FEAT-master/model/networks/convnet.py | import torch.nn as nn
# Basic ConvNet with Pooling layer
def conv_block(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, 3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(),
nn.MaxPool2d(2)
)
class ConvNet(nn.Module):
def __init__(... | 735 | 23.533333 | 59 | py |
FEAT | FEAT-master/model/networks/res12.py | import torch.nn as nn
import torch
import torch.nn.functional as F
from model.networks.dropblock import DropBlock
# This ResNet network was designed following the practice of the following papers:
# TADAM: Task dependent adaptive metric for improved few-shot learning (Oreshkin et al., in NIPS 2018) and
# A Simple Neur... | 4,705 | 36.349206 | 125 | py |
FEAT | FEAT-master/model/networks/WRN28.py | import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Variable
import sys
import numpy as np
def conv3x3(in_planes, out_planes, stride=1):
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
def conv_init... | 2,858 | 34.296296 | 98 | py |
FEAT | FEAT-master/model/networks/res18.py | import torch.nn as nn
__all__ = ['resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
padding=1, bias=Fal... | 5,632 | 28.492147 | 106 | py |
FEAT | FEAT-master/model/models/base.py | import torch
import torch.nn as nn
import numpy as np
class FewShotModel(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
if args.backbone_class == 'ConvNet':
from model.networks.convnet import ConvNet
self.encoder = ConvNet()
elif ar... | 2,434 | 43.272727 | 174 | py |
FEAT | FEAT-master/model/models/graphnet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
import math
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
from itertools import permutations
import scipy.sparse as sp
class GraphConvolution(Module):
... | 6,810 | 37.480226 | 128 | py |
FEAT | FEAT-master/model/models/deepset.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
class DeepSetsFunc(nn.Module):
def __init__(self, z_dim):
super(DeepSetsFunc, self).__init__()
"""
DeepSets Function
"""
self.gen1 = nn.Linear(z_dim, ... | 5,338 | 43.865546 | 117 | py |
FEAT | FEAT-master/model/models/semi_protofeat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
from model.utils import one_hot
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__ini... | 8,560 | 45.781421 | 230 | py |
FEAT | FEAT-master/model/models/protonet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
# Note: As in Protonet, we use Euclidean Distances here, you can change to the Cosine Similarity by replace
# TRUE in line 30 as self.args.use_euclidean
class ProtoNet(FewShotModel):
... | 2,007 | 40.833333 | 137 | py |
FEAT | FEAT-master/model/models/bilstm.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from torch.autograd import Variable
from model.models import FewShotModel
class BidirectionalLSTM(nn.Module):
def __init__(self, layer_sizes, vector_dim):
super(BidirectionalLSTM, self).__init__()
"""
Ini... | 5,746 | 45.723577 | 118 | py |
FEAT | FEAT-master/model/models/classifier.py | import torch
import torch.nn as nn
import numpy as np
from model.utils import euclidean_metric
import torch.nn.functional as F
class Classifier(nn.Module):
def __init__(self, args):
super().__init__()
self.args = args
if args.backbone_class == 'ConvNet':
from model.networks... | 1,617 | 32.708333 | 75 | py |
FEAT | FEAT-master/model/models/featstar.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
# No-Reg for FEAT-STAR here
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__... | 4,959 | 37.153846 | 114 | py |
FEAT | FEAT-master/model/models/matchnet.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
from model.utils import one_hot
# Note: This is the MatchingNet without FCE
# it predicts an instance based on nearest neighbor rule (not Nearest center mean)
class MatchNet(FewShotModel)... | 2,299 | 40.818182 | 133 | py |
FEAT | FEAT-master/model/models/feat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature =... | 6,494 | 42.590604 | 119 | py |
FEAT | FEAT-master/model/models/semi_feat.py | import torch
import torch.nn as nn
import numpy as np
import torch.nn.functional as F
from model.models import FewShotModel
class ScaledDotProductAttention(nn.Module):
''' Scaled Dot-Product Attention '''
def __init__(self, temperature, attn_dropout=0.1):
super().__init__()
self.temperature =... | 6,584 | 42.9 | 119 | py |
FEAT | FEAT-master/model/dataloader/tiered_imagenet.py | from __future__ import print_function
import os
import os.path as osp
import numpy as np
import pickle
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image
# Set the appropriate paths of the datasets here.
THIS_PATH = osp.dirname(__file__)
ROOT_PATH... | 4,423 | 35.561983 | 114 | py |
FEAT | FEAT-master/model/dataloader/cub.py | import os.path as osp
import PIL
from PIL import Image
import numpy as np
from torch.utils.data import Dataset
from torchvision import transforms
THIS_PATH = osp.dirname(__file__)
ROOT_PATH1 = osp.abspath(osp.join(THIS_PATH, '..', '..', '..'))
ROOT_PATH2 = osp.abspath(osp.join(THIS_PATH, '..', '..'))
IMAGE_PATH = osp... | 4,840 | 38.040323 | 112 | py |
FEAT | FEAT-master/model/dataloader/mini_imagenet.py | import torch
import os.path as osp
from PIL import Image
from torch.utils.data import Dataset
from torchvision import transforms
from tqdm import tqdm
import numpy as np
THIS_PATH = osp.dirname(__file__)
ROOT_PATH = osp.abspath(osp.join(THIS_PATH, '..', '..'))
ROOT_PATH2 = osp.abspath(osp.join(THIS_PATH, '..', '..', ... | 4,581 | 36.252033 | 112 | py |
FEAT | FEAT-master/model/dataloader/samplers.py | import torch
import numpy as np
class CategoriesSampler():
def __init__(self, label, n_batch, n_cls, n_per):
self.n_batch = n_batch
self.n_cls = n_cls
self.n_per = n_per
label = np.array(label)
self.m_ind = []
for i in range(max(label) + 1):
ind = np.a... | 2,586 | 27.119565 | 82 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/examples/keras_nonvis.py | # thanks to @edersantana and @fchollet for suggestions & help.
import numpy as np
from ple import PLE # our environment
from ple.games.catcher import Catcher
from keras.models import Sequential
from keras.layers.core import Dense
from keras.optimizers import SGD
from example_support import ExampleAgent, ReplayMemor... | 5,449 | 31.634731 | 167 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/examples/example_support.py | import numpy as np
from collections import deque
# keras and model related
from keras.models import Sequential
from keras.layers.core import Dense, Flatten
from keras.layers.convolutional import Convolution2D
from keras.optimizers import SGD, Adam, RMSprop
import theano.tensor as T
class ExampleAgent():
"""
... | 6,844 | 30.837209 | 201 | py |
PyGame-Learning-Environment | PyGame-Learning-Environment-master/docs/conf.py | import sys
import os
from mock import Mock
sys.modules['pygame'] = Mock()
sys.modules['pygame.constants'] = Mock()
#so we can import ple
sys.path.append(os.path.join(os.path.dirname(__name__), ".."))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.mathjax',
'sphinx.ext.viewc... | 1,940 | 22.962963 | 95 | py |
Intraclass-clustering-measures | Intraclass-clustering-measures-main/measures.py | '''
Measures of intraclass clustering ability and generalization
'''
import sys
sys.path.insert(0, "../")
import warnings
import numpy as np
from scipy.spatial.distance import cosine
from sklearn.metrics import silhouette_score, silhouette_samples, calinski_harabasz_score
from sklearn.metrics.pairwise import cosine_... | 23,997 | 45.15 | 181 | py |
Diverse-ViT | Diverse-ViT-main/main.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import argparse
import datetime
import numpy as np
import time
import torch
import torch.backends.cudnn as cudnn
import json
import warnings
warnings.filterwarnings('ignore')
from pathlib import Path
from timm.data import Mixup
from timm.models impor... | 22,308 | 47.079741 | 119 | py |
Diverse-ViT | Diverse-ViT-main/losses.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Implements the knowledge distillation loss
"""
import torch
import torch.nn as nn
from torch.nn import functional as F
class DistillationLoss(torch.nn.Module):
"""
This module wraps a standard criterion and adds an extra knowledge distilla... | 2,792 | 41.969231 | 114 | py |
Diverse-ViT | Diverse-ViT-main/engine.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Train and eval functions used in main.py
"""
import sys
import math
import utils
import torch
import torch.nn as nn
from timm.data import Mixup
from losses import DistillationLoss
from typing import Iterable, Optional
from timm.utils import accura... | 5,354 | 39.263158 | 98 | py |
Diverse-ViT | Diverse-ViT-main/hubconf.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
from models import *
dependencies = ["torch", "torchvision", "timm"]
| 138 | 22.166667 | 47 | py |
Diverse-ViT | Diverse-ViT-main/gradinit_optimizers.py | import torch
import math
import pdb
class RescaleAdam(torch.optim.Optimizer):
r"""Implements Adam algorithm.
It has been proposed in `Adam: A Method for Stochastic Optimization`_.
Arguments:
params (iterable): iterable of parameters to optimize or dicts defining
parameter groups
... | 7,541 | 45.269939 | 111 | py |
Diverse-ViT | Diverse-ViT-main/utils.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
"""
Misc functions, including distributed helpers.
Mostly copy-paste from torchvision references.
"""
import io
import os
import time
from collections import defaultdict, deque
import datetime
import torch
import torch.distributed as dist
class Smo... | 7,067 | 28.573222 | 94 | py |
Diverse-ViT | Diverse-ViT-main/vision_transformer_diverse.py | """ Vision Transformer (ViT) in PyTorch
A PyTorch implement of Vision Transformers as described in
'An Image Is Worth 16 x 16 Words: Transformers for Image Recognition at Scale' - https://arxiv.org/abs/2010.11929
The official jax code is released and available at https://github.com/google-research/vision_transformer
De... | 17,793 | 40.574766 | 132 | py |
Diverse-ViT | Diverse-ViT-main/layers.py | import math
import torch
import torch.nn as nn
from torch.nn import functional as F
from torch.nn import init
from torch.nn.parameter import Parameter
from torch.nn.modules.utils import _pair
class Linear(nn.Linear):
def __init__(self, in_features, out_features, bias=True):
super(Linear, self).__init__(in... | 1,575 | 36.52381 | 95 | py |
Diverse-ViT | Diverse-ViT-main/datasets.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import os
import json
from torchvision import datasets, transforms
from torchvision.datasets.folder import ImageFolder, default_loader
from timm.data.constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD
from timm.data import create_transform
... | 4,235 | 36.821429 | 105 | py |
Diverse-ViT | Diverse-ViT-main/reg.py | import torch
import numpy as np
from timm.loss import LabelSmoothingCrossEntropy, SoftTargetCrossEntropy
__all__ = ['Loss_mixing', 'Loss_cosine', 'Loss_contrastive',
'Loss_cosine_attn', 'Loss_condition_orth_weight']
# Embedding Level Size: (Batch-size, Tokens, Dims * Heads)
# Attention Level Size: (B... | 15,331 | 34.084668 | 115 | py |
Diverse-ViT | Diverse-ViT-main/models.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.nn as nn
from functools import partial
from timm.models.vision_transformer import VisionTransformer, _cfg
from timm.models.registry import register_model
from timm.models.layers import trunc_normal_
from vision_transformer_di... | 4,745 | 37.585366 | 146 | py |
Diverse-ViT | Diverse-ViT-main/samplers.py | # Copyright (c) 2015-present, Facebook, Inc.
# All rights reserved.
import torch
import torch.distributed as dist
import math
class RASampler(torch.utils.data.Sampler):
"""Sampler that restricts data loading to a subset of the dataset for distributed,
with repeated augmentation.
It ensures that different ... | 2,292 | 37.216667 | 103 | py |
Diverse-ViT | Diverse-ViT-main/loss_scaler.py | """ CUDA / AMP utils
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
try:
from apex import amp
has_apex = True
except ImportError:
amp = None
has_apex = False
from timm.utils import *
__all__ = ['NativeScaler']
class NativeScaler:
state_dict_key = "amp_scaler"
def __init_... | 1,136 | 29.72973 | 138 | py |
Diverse-ViT | Diverse-ViT-main/gradient_utils.py | import torch
from torch import nn
from gradinit_optimizers import RescaleAdam
import numpy as np
import os
class Scale(torch.nn.Module):
def __init__(self):
super(Scale, self).__init__()
self.weight = torch.nn.Parameter(torch.ones(1))
def forward(self, x):
return x * self.weight
clas... | 9,598 | 34.420664 | 163 | py |
Diverse-ViT | Diverse-ViT-main/mix.py | """ Mixup and Cutmix
Papers:
mixup: Beyond Empirical Risk Minimization (https://arxiv.org/abs/1710.09412)
CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features (https://arxiv.org/abs/1905.04899)
Code Reference:
CutMix: https://github.com/clovaai/CutMix-PyTorch
Hacked together by / Copyri... | 5,266 | 42.528926 | 120 | py |
GATNE | GATNE-master/src/main_pytorch.py | import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from numpy import random
from torch.nn.parameter import Parameter
from utils import *
def get_batches(pairs, neighbors, batch_size):
n_batches = (len(pairs) + (batch_size - 1)) // batch_size
for idx in range(n... | 10,920 | 36.400685 | 169 | py |
Viola-Unet | Viola-Unet-main/main.py | import argparse, os
import time
import numpy as np
import torch
from load_model import load_model, infer_seg, nibout, infer_seg_3
from load_data import load_data, post_process, read_raw_image
from monai.transforms import SaveImaged
from monai.data import decollate_batch
if __name__ == '__main__':
parser = argpa... | 6,412 | 49.496063 | 150 | py |
Viola-Unet | Viola-Unet-main/load_model.py | import os
import torch
import nibabel as nib
from monai.inferers import sliding_window_inference
from monai.transforms.utils import map_spatial_axes
from monai.data import decollate_batch
from viola_unet import ViolaUNet
from monai.networks.nets import DynUNet
wind_levels = [[0,100], [-15, 200],[-100, 1300]]
spacin... | 9,563 | 43.691589 | 130 | py |
Viola-Unet | Viola-Unet-main/viola_unet.py | # ViolaUNet is based on DynUNet
# Copyright (c) MONAI Consortium
# 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://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable... | 31,635 | 41.23765 | 122 | py |
BlockGCL | BlockGCL-master/dataloader.py | import os.path as osp
import numpy as np
import torch
from sklearn.model_selection import train_test_split
from torch_geometric.data import Data
from torch_geometric.datasets import Planetoid, Amazon, Coauthor, WikiCS
from torch_geometric.transforms import Compose, NormalizeFeatures, ToUndirected
from ogb.nodeproppred... | 5,008 | 37.236641 | 81 | py |
BlockGCL | BlockGCL-master/loss.py | import torch
import torch.nn.functional as F
def inv_dec_loss(h1, h2, lambd):
N = h1.size(0)
c = torch.mm(h1.T, h2)
c1 = torch.mm(h1.T, h1)
c2 = torch.mm(h2.T, h2)
c = c / N
c1 = c1 / N
c2 = c2 / N
loss_inv = -torch.diagonal(c).sum()
iden = torch.eye(c.shape[0]).to(h1.device)
... | 471 | 19.521739 | 53 | py |
BlockGCL | BlockGCL-master/utils.py | import os
import random
import numpy as np
import torch
import torch.nn.functional as F
from torch_sparse import SparseTensor
def set_random_seeds(random_seed=0):
r"""Set the seed for generating random numbers."""
torch.manual_seed(random_seed)
torch.cuda.manual_seed(random_seed)
torch.cuda.manual_see... | 658 | 27.652174 | 55 | py |
BlockGCL | BlockGCL-master/model.py | import torch
import torch.nn as nn
from torch_geometric.nn import BatchNorm, GCNConv, LayerNorm, SAGEConv, Sequential
def get_activation(name='ReLU'):
if name == 'ReLU':
return nn.ReLU()
elif name == "PReLU":
return nn.PReLU()
else:
raise NotImplementedError("Acitivation {} not impl... | 2,427 | 28.975309 | 106 | py |
BlockGCL | BlockGCL-master/logger.py | import functools
import logging
import os
import sys
import torch
from typing import Optional
from termcolor import colored
__all__ = ["setup_logger", "get_logger"]
# cache the opened file object, so that different calls to `setup_logger`
# with the same file name can safely write to the same file.
@functools.lru_c... | 6,665 | 33.184615 | 89 | py |
BlockGCL | BlockGCL-master/eval.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
def test(embeds, data, num_classes, FLAGS, device="cpu"):
return node_cls_downstream_task_eval(
input_emb=embeds, data=data, num_classes=num_classes,
lr=FLAGS.lr_cls, wd=FLAGS.wd_cls,
... | 4,642 | 31.468531 | 109 | py |
BlockGCL | BlockGCL-master/train.py | import copy
import os.path as osp
import numpy as np
import torch
import torch.nn.functional as F
from absl import app, flags
from torch.optim import AdamW
# custom modules
from logger import setup_logger
from utils import set_random_seeds, edgeidx2sparse
from transforms import get_graph_drop_transform
from model imp... | 7,308 | 37.267016 | 122 | py |
BlockGCL | BlockGCL-master/transforms.py | import copy
import torch
from torch_geometric.utils.dropout import dropout_adj
from torch_geometric.transforms import Compose
class DropFeatures:
r"""Drops node features with probability p."""
def __init__(self, p=None):
assert 0. < p < 1., \
'Dropout probability has to be between 0 and 1... | 2,025 | 27.942857 | 83 | py |
RecSys_PyTorch | RecSys_PyTorch-master/main.py | # Import packages
import os
import torch
import models
from data.dataset import UIRTDataset
from evaluation.evaluator import Evaluator
from experiment.early_stop import EarlyStop
from loggers import FileLogger, CSVLogger
from utils.general import make_log_dir, set_random_seed
from config import load_config
"""
C... | 1,665 | 22.8 | 103 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/RP3b.py | """
Bibek Paudel et al., Updatable, accurate, diverse, and scalablerecommendations for interactive applications. TiiS 2017.
https://www.zora.uzh.ch/id/eprint/131338/1/TiiS_2016.pdf
Main model codes from https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation
"""
import torch
import torch.nn.functional as F
im... | 4,686 | 36.496 | 130 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/PureSVD.py | import numpy as np
import scipy.sparse as sp
from sklearn.utils.extmath import randomized_svd
import torch
import torch.nn.functional as F
from models.BaseModel import BaseModel
class PureSVD(BaseModel):
def __init__(self, dataset, hparams, device):
super(PureSVD, self).__init__()
self.num_users = ... | 2,227 | 33.8125 | 100 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/ItemKNN.py | """
Jun Wang et al., Unifying user-based and item-based collaborative filtering approaches by similarity fusion. SIGIR 2006.
http://web4.cs.ucl.ac.uk/staff/jun.wang/papers/2006-sigir06-unifycf.pdf
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import scipy.sparse as sp
from tq... | 6,781 | 36.677778 | 146 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/MultVAE.py | """
Dawen Liang et al., Variational Autoencoders for Collaborative Filtering. WWW 2018.
https://arxiv.org/pdf/1802.05814
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from .BaseModel import BaseModel
from data.generators import MatrixGenerator
class MultVAE(BaseModel):
... | 5,994 | 37.429487 | 123 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/P3a.py | """
Colin Cooper et al., Random Walks in Recommender Systems: Exact Computation and Simulations. WWW 2014.
http://wwwconference.org/proceedings/www2014/companion/p811.pdf
Main model codes from https://github.com/MaurizioFD/RecSys2019_DeepLearning_Evaluation
"""
import torch
import torch.nn.functional as F
import numpy... | 4,840 | 35.954198 | 130 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/CDAE.py | """
Yao Wu et al., Collaborative denoising auto-encoders for top-n recommender systems. WSDM 2016.
https://alicezheng.org/papers/wsdm16-cdae.pdf
"""
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .BaseModel import BaseModel
from data.gene... | 4,533 | 38.086207 | 142 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/DAE.py | """
Yao Wu et al., Collaborative denoising auto-encoders for top-n recommender systems. WSDM 2016.
https://alicezheng.org/papers/wsdm16-cdae.pdf
"""
from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .BaseModel import BaseModel
from data.gene... | 4,313 | 36.513043 | 123 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/LightGCN.py | """
LightGCN: Simplifying and Powering Graph Convolution Network for Recommendation,
Xiangnan He et al.,
SIGIR 2020.
"""
import os
import math
import time
import numpy as np
import scipy.sparse as sp
import torch
import torch.nn as nn
import torch.nn.functional as F
from .BaseModel import BaseModel
from data.generat... | 9,931 | 36.198502 | 109 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/NGCF.py | """
Neural Graph Collaborative Filtering,
Xiang Wang et al.,
SIGIR 2019.
[Official tensorflow]: https://github.com/xiangwang1223/neural_graph_collaborative_filtering
[PyTorch reference]: https://github.com/huangtinglin/NGCF-PyTorch
"""
import os
import math
import time
import numpy as np
import scipy.sparse as sp
impo... | 10,926 | 37.748227 | 118 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/MF.py | """
Steffen Rendle et al., BPR: Bayesian Personalized Ranking from Implicit Feedback. UAI 2009.
https://arxiv.org/pdf/1205.2618
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .BaseModel import BaseModel
from data.generators import PointwiseGenerator, PairwiseGenerator
... | 5,277 | 38.38806 | 109 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/BaseModel.py | import torch.nn as nn
class BaseModel(nn.Module):
def __init__(self):
super(BaseModel, self).__init__()
def forward(self, *input):
pass
def fit(self, *input):
pass
def predict(self, eval_users, eval_pos, test_batch_size):
pass | 278 | 18.928571 | 61 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/SLIMElastic.py | """
Xia Ning et al., SLIM: Sparse Linear Methods for Top-N Recommender Systems. ICDM 2011.
http://glaros.dtc.umn.edu/gkhome/fetch/papers/SLIM2011icdm.pdf
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import scipy.sparse as sp
from tqdm import tqdm
from sklearn.linear_model im... | 5,363 | 38.441176 | 142 | py |
RecSys_PyTorch | RecSys_PyTorch-master/models/EASE.py | """
Harald Steck, Embarrassingly Shallow Autoencoders for Sparse Data. WWW 2019.
https://arxiv.org/pdf/1905.03375
"""
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from .BaseModel import BaseModel
class EASE(BaseModel):
def __init__(self, dataset, hparams, device):
s... | 2,379 | 30.733333 | 97 | py |
RecSys_PyTorch | RecSys_PyTorch-master/loggers/base.py | import abc
from typing import MutableMapping
from argparse import Namespace
import torch
import numpy as np
class Logger(abc.ABC):
def __init__(self):
super().__init__()
def setup_logger(self):
pass
# @abc.abstractmethod
# def log_hparams(self, hparams):
# raise NotImplem... | 3,641 | 33.685714 | 112 | py |
RecSys_PyTorch | RecSys_PyTorch-master/loggers/tensorboard.py | import torch
from torch.utils.tensorboard import SummaryWriter
from torch.utils.tensorboard.summary import hparams as hparams_tb
from logger.base import Logger
class TensorboardLogger(Logger):
def __init__(self,
log_dir:str,
experiment_name:str,
hparams:dict,
... | 2,333 | 34.907692 | 111 | py |
RecSys_PyTorch | RecSys_PyTorch-master/utils/general.py | import os
import math
import time
import datetime
import random
import numpy as np
import torch
def make_log_dir(save_dir):
if not os.path.exists(save_dir):
os.makedirs(save_dir)
existing_dirs = os.listdir(save_dir)
if len(existing_dirs) == 0:
idx = 0
else:
idx_list = sorted([... | 1,163 | 24.866667 | 72 | py |
RecSys_PyTorch | RecSys_PyTorch-master/data/generators.py | import torch
import numpy as np
class MatrixGenerator:
def __init__(self, input_matrix, return_index=False, batch_size=32, shuffle=True,
matrix_as_numpy=False, index_as_numpy=False, device=None):
super().__init__()
self.input_matrix = input_matrix
self.return_index ... | 8,480 | 36.861607 | 154 | py |
RecSys_PyTorch | RecSys_PyTorch-master/data/data_batcher.py | import torch
import numpy as np
class BatchSampler:
def __init__(self, data_size, batch_size, drop_remain=False, shuffle=False):
self.data_size = data_size
self.batch_size = batch_size
self.drop_remain = drop_remain
self.shuffle = shuffle
def __iter__(self):
if self.shu... | 2,085 | 30.606061 | 100 | py |
paac | paac-master/networks.py | import tensorflow as tf
import logging
import numpy as np
def flatten(_input):
shape = _input.get_shape().as_list()
dim = shape[1]*shape[2]*shape[3]
return tf.reshape(_input, [-1,dim], name='_flattened')
def conv2d(name, _input, filters, size, channels, stride, padding = 'VALID', init = "torch"):
w ... | 5,972 | 34.135294 | 117 | py |
brainiak | brainiak-master/docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# toolkit documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 17 16:45:35 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
# au... | 9,448 | 30.708054 | 79 | py |
DMGI | DMGI-master/main.py | import numpy as np
np.random.seed(0)
import torch
torch.autograd.set_detect_anomaly(True)
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import argparse
def parse_args():
# input arguments
parser = argparse.ArgumentParser(desc... | 2,131 | 33.95082 | 84 | py |
DMGI | DMGI-master/evaluate.py | import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
from models import LogReg
import torch.nn as nn
import numpy as np
np.random.seed(0)
from sklearn.metrics import f1_score
from sklearn.cluster import KMeans
from sklearn.metri... | 4,571 | 34.71875 | 115 | py |
DMGI | DMGI-master/embedder.py | import time
import numpy as np
import torch
from utils import process
import torch.nn as nn
from layers import AvgReadout
class embedder:
def __init__(self, args):
args.batch_size = 1
args.sparse = True
args.metapaths_list = args.metapaths.split(",")
args.gpu_num_ = args.gpu_num
... | 1,994 | 35.272727 | 108 | py |
DMGI | DMGI-master/models/logreg.py | import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
import torch.nn.functional as F
class LogReg(nn.Module):
def __init__(self, ft_in, nb_classes):
super(LogReg, self).__init__()
self.... | 697 | 24.851852 | 56 | py |
DMGI | DMGI-master/models/DMGI.py | import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
from embedder import embedder
from layers import GCN, Discriminator, Attention
import numpy as np
np.random.seed(0)
from evaluate import evaluate
from mo... | 5,373 | 34.826667 | 146 | py |
DMGI | DMGI-master/models/DGI.py | # Code based on https://github.com/PetarV-/DGI/blob/master/models/dgi.py
import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
from embedder import embedder
from layers import GCN, Discriminator
import numpy... | 3,756 | 35.125 | 139 | py |
DMGI | DMGI-master/layers/discriminator.py | import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
class Discriminator(nn.Module):
def __init__(self, n_h):
super(Discriminator, self).__init__()
self.f_k_bilinear = nn.Bilinear(n_h,... | 1,143 | 30.777778 | 87 | py |
DMGI | DMGI-master/layers/readout.py | import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
class AvgReadout(nn.Module):
def __init__(self):
super(AvgReadout, self).__init__()
def forward(self, seq):
return torch.mean(s... | 326 | 24.153846 | 42 | py |
DMGI | DMGI-master/layers/gcn.py | import torch
torch.manual_seed(0)
torch.cuda.manual_seed_all(0)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import torch.nn as nn
import torch.nn.functional as F
import pdb
import math
class GCN(nn.Module):
def __init__(self, in_ft, out_ft, act, drop_prob, isBias=False):
... | 2,239 | 28.473684 | 76 | py |
DMGI | DMGI-master/layers/attention.py | import torch.nn as nn
import torch
import torch.nn.functional as F
class Attention(nn.Module):
def __init__(self, args):
super(Attention, self).__init__()
self.args = args
self.A = nn.ModuleList([nn.Linear(args.hid_units, 1) for _ in range(args.nb_graphs)])
self.weight_init()
... | 1,865 | 37.875 | 114 | py |
DMGI | DMGI-master/utils/process.py | import numpy as np
import pickle as pkl
import networkx as nx
import scipy.sparse as sp
import sys
import torch
import torch.nn as nn
import scipy.io as sio
import pdb
def load_data_dblp(args):
dataset = args.dataset
metapaths = args.metapaths_list
sc = args.sc
if dataset == 'acm':
data = sio.... | 8,988 | 33.178707 | 110 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.