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 |
|---|---|---|---|---|---|---|
NBFNet | NBFNet-master/nbfnet/model.py | from collections.abc import Sequence
import torch
from torch import nn
from torch import autograd
from torch_scatter import scatter_add
from torchdrug import core, layers, utils
from torchdrug.layers import functional
from torchdrug.core import Registry as R
from . import layer
@R.register("model.NBFNet")
class N... | 11,950 | 44.441065 | 118 | py |
NBFNet | NBFNet-master/nbfnet/dataset.py | import os
import csv
import glob
from tqdm import tqdm
from ogb import linkproppred
import torch
from torch.utils import data as torch_data
from torchdrug import data, datasets, utils
from torchdrug.core import Registry as R
class InductiveKnowledgeGraphDataset(data.KnowledgeGraphDataset):
def load_inductive_t... | 14,201 | 39.005634 | 105 | py |
NBFNet | NBFNet-master/nbfnet/util.py | import os
import time
import logging
import argparse
import yaml
import jinja2
from jinja2 import meta
import easydict
import torch
from torch.utils import data as torch_data
from torch import distributed as dist
from torchdrug import core, utils
from torchdrug.utils import comm
logger = logging.getLogger(__file__... | 3,838 | 30.467213 | 119 | py |
gca-rom | gca-rom-main/main.py | import sys
sys.path.append('../')
import torch
from gca_rom import network, pde, loader, plotting, preprocessing, training, initialization, testing, error
import numpy as np
if __name__ == "__main__":
problem_name, variable, mu1_range, mu2_range = pde.problem(int(sys.argv[1]))
print("PROBLEM: ", problem_name... | 4,087 | 45.454545 | 157 | py |
gca-rom | gca-rom-main/gca_rom/preprocessing.py | import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.loader import DataLoader
from gca_rom import scaling
def graphs_dataset(dataset, AE_Params):
"""
graphs_dataset: function to process and scale the input dataset for graph autoencoder model.
Inputs:
dataset: an ... | 3,515 | 38.954545 | 112 | py |
gca-rom | gca-rom-main/gca_rom/network.py | import sys
import torch
from torch import nn
from gca_rom import gca, scaling, pde
problem_name, variable, mu1_range, mu2_range = pde.problem(int(sys.argv[1]))
class AE_Params():
"""Class that holds the hyperparameters for the autoencoder model.
Args:
sparse_method (str): The method to use for spar... | 5,946 | 39.732877 | 179 | py |
gca-rom | gca-rom-main/gca_rom/training.py | import torch
import torch.nn.functional as F
def train(model, optimizer, device, scheduler, params, train_loader, train_trajectories, AE_Params, history):
"""Trains the autoencoder model.
This function trains the autoencoder model using mean squared error (MSE) loss and a map loss, where the map loss
... | 5,063 | 48.647059 | 478 | py |
gca-rom | gca-rom-main/gca_rom/testing.py | import torch
from tqdm import tqdm
import numpy as np
def evaluate(VAR, model, loader, params, AE_Params, test):
"""
This function evaluates the performance of a trained Autoencoder (AE) model.
It encodes the input data using both the model's encoder and a mapping function,
and decodes the resulting l... | 2,071 | 44.043478 | 110 | py |
gca-rom | gca-rom-main/gca_rom/initialization.py | import os
import torch
import numpy as np
import random
import warnings
def set_device():
"""
Returns the device to be used (GPU or CPU)
Returns:
device (str): The device to be used ('cuda' if GPU is available, 'cpu' otherwise)
"""
device = 'cuda' if torch.cuda.is_available() else 'cpu'
... | 1,224 | 21.685185 | 89 | py |
gca-rom | gca-rom-main/gca_rom/loader.py | import sys
from torch_geometric.data import Dataset
import torch
import scipy
class LoadDataset(Dataset):
"""
A custom dataset class which loads data from a .mat file using scipy.io.loadmat.
data_mat : scipy.io.loadmat
The loaded data in a scipy.io.loadmat object.
U : torch.Tensor
The... | 1,488 | 41.542857 | 172 | py |
gca-rom | gca-rom-main/gca_rom/gca.py | import torch
from torch import nn
import torch.nn.functional as F
from torch_geometric.nn import GMMConv
class Encoder(torch.nn.Module):
"""
Encoder Class
The Encoder class is a subclass of torch.nn.Module that implements a deep neural network for encoding graph data.
It uses the Gaussian Mixture co... | 5,918 | 36.226415 | 139 | py |
gca-rom | gca-rom-main/gca_rom/scaling.py | from sklearn import preprocessing
import torch
import sys
def scaler_functions(k):
match k:
case 1:
sc_name = "minmax"
sc_fun = preprocessing.MinMaxScaler()
case 2:
sc_name = "robust"
sc_fun = preprocessing.RobustScaler()
case 3:
... | 2,869 | 41.205882 | 163 | py |
CRST | CRST-master/evaluate.py | import argparse
import scipy
from scipy import ndimage
import numpy as np
import sys
from packaging import version
import time
import util
import torch
import torchvision.models as models
import torch.nn.functional as F
from torch.utils import data, model_zoo
from deeplab.model import Res_Deeplab
from deeplab.datasets... | 11,168 | 39.762774 | 176 | py |
CRST | CRST-master/crst_seg.py | import argparse
import sys
from packaging import version
import time
import util
import os
import os.path as osp
import timeit
from collections import OrderedDict
import scipy.io
import torch
import torchvision.models as models
import torch.nn.functional as F
from torch.utils import data, model_zoo
import torch.backen... | 47,013 | 48.229319 | 225 | py |
CRST | CRST-master/train.py | import argparse
import torch
import torch.nn as nn
from torch.utils import data
import numpy as np
import pickle
import cv2
import torch.optim as optim
import scipy.misc
import torch.backends.cudnn as cudnn
import sys
import os
import os.path as osp
from deeplab.model import Res_Deeplab
from deeplab.loss import CrossE... | 10,806 | 39.324627 | 164 | py |
CRST | CRST-master/deeplab/loss.py | import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
class CrossEntropy2d(nn.Module):
def __init__(self, size_average=True, ignore_label=255):
super(CrossEntropy2d, self).__init__()
self.size_average = size_average
self.ignore_label = ignor... | 1,585 | 44.314286 | 103 | py |
CRST | CRST-master/deeplab/model.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
affine_par = True
def outS(i):
i = int(i)
i = (i+1)/2
i = int(np.ceil((i+1)/2.0))
i = (i+1)/2
return i
def conv3x3(in_planes, out_planes, stride=1):
"3x3 convolution with padding"
r... | 11,127 | 36.217391 | 139 | py |
CRST | CRST-master/deeplab/datasets.py | import os
import os.path as osp
import numpy as np
import random
import matplotlib.pyplot as plt
import collections
import torch
import torchvision.transforms as transforms
import torchvision
import cv2
from torch.utils import data
import sys
from PIL import Image
palette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102... | 62,075 | 43.276748 | 309 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/linear_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbedding(nn.Module):
def __init__(
self,
patch_size: int,
embed_dim: int,
channels: int
... | 3,644 | 26.613636 | 127 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/original_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbeddings(nn.Module):
def __init__(
self,
patch_size: int,
hidden_dim: int,
channels: int
... | 3,674 | 26.840909 | 93 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/img2img_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbedding(nn.Module):
def __init__(
self,
patch_size: int,
embed_dim: int,
channels: int
... | 3,618 | 27.054264 | 127 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/vit.py | '''
This code is modified from https://github.com/facebookresearch/convit. To adapt the vit/convit to image reconstruction, variable input sizes, and patch sizes for both spatial dimensions.
'''
import torch
import torch.nn as nn
from functools import partial
import torch.nn.functional as F
from timm.models.helpers im... | 15,082 | 39.007958 | 186 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/recon_net.py | import torch.nn as nn
import torch.nn.functional as F
from math import ceil, floor
class ReconNet(nn.Module):
def __init__(self, net):
super().__init__()
self.net = net
def pad(self, x):
_, _, h, w = x.shape
hp, wp = self.net.patch_size
f1 = ( (wp - w % wp) % wp ) / 2
... | 810 | 26.033333 | 90 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/unet.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT 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
class Unet(nn.Module):
"""
PyTorch implementation of a U-Net ... | 5,981 | 32.79661 | 88 | py |
imaging_MLPs | imaging_MLPs-master/ImageNet/networks/u_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbeddings(nn.Module):
def __init__(
self,
patch_size: int,
embed_dim: int,
channels: int
... | 6,516 | 28.488688 | 127 | py |
imaging_MLPs | imaging_MLPs-master/SIDD/networks/img2img_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbedding(nn.Module):
def __init__(
self,
patch_size: int,
embed_dim: int,
channels: int
... | 3,618 | 27.054264 | 127 | py |
imaging_MLPs | imaging_MLPs-master/SIDD/networks/vit.py | '''
This code is modified from https://github.com/facebookresearch/convit. To adapt the vit/convit to image reconstruction, variable input sizes, and patch sizes for both spatial dimensions.
'''
import torch
import torch.nn as nn
from functools import partial
import torch.nn.functional as F
from timm.models.helpers im... | 15,082 | 39.007958 | 186 | py |
imaging_MLPs | imaging_MLPs-master/SIDD/networks/recon_net.py | import torch.nn as nn
import torch.nn.functional as F
from math import ceil, floor
class ReconNet(nn.Module):
def __init__(self, net):
super().__init__()
self.net = net
def pad(self, x):
_, _, h, w = x.shape
hp, wp = self.net.patch_size
f1 = ( (wp - w % wp) % wp ) / 2
... | 810 | 26.033333 | 90 | py |
imaging_MLPs | imaging_MLPs-master/SIDD/networks/unet.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT 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
class Unet(nn.Module):
"""
PyTorch implementation of a U-Net ... | 5,981 | 32.79661 | 88 | py |
imaging_MLPs | imaging_MLPs-master/SIDD/networks/u_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbeddings(nn.Module):
def __init__(
self,
patch_size: int,
embed_dim: int,
channels: int
... | 6,516 | 28.488688 | 127 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/losses.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
class SSIMLoss(nn.Module):
"""
SSIM loss module.
"""
de... | 1,671 | 28.857143 | 87 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/coil_combine.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
import fastmri
def rss(data: torch.Tensor, dim: int = 0) -> torch.Tensor:
"""
Compute the Root Sum of Squares (RSS).
... | 996 | 22.186047 | 66 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/math.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import numpy as np
import torch
def complex_mul(x: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
"""
Complex multiplication.
... | 2,728 | 25.754902 | 77 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/__init__.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import torch
from packaging import version
from .coil_combine import rss, rss_complex
from .fftc import fftshift, ifftshift, roll
from .losse... | 758 | 26.107143 | 63 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/fftc.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import List, Optional
import torch
from packaging import version
if version.parse(torch.__version__) >= version.parse("1.7.0"):... | 5,535 | 25.236967 | 80 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/data/volume_sampler.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import List, Optional, Union
import torch
import torch.distributed as dist
from fastmri.data.mri_data import CombinedSliceDatase... | 4,332 | 36.678261 | 82 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/data/mri_data.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import logging
import os
import pickle
import random
import xml.etree.ElementTree as etree
from pathlib import Path
from typing import Callab... | 13,630 | 36.759003 | 116 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/data/subsample.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import contextlib
from typing import Optional, Sequence, Tuple, Union
import numpy as np
import torch
@contextlib.contextmanager
def temp_... | 8,448 | 36.887892 | 88 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/fastmri/data/transforms.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import Dict, Optional, Sequence, Tuple, Union
import fastmri
import numpy as np
import torch
from .subsample import MaskFunc
... | 12,887 | 30.205811 | 88 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/networks/img2img_mixer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init
import torch.nn.init as init
import numpy as np
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbedding(nn.Module):
def __init__(
self,
patch_size: int,
... | 3,714 | 26.932331 | 127 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/networks/vision_transformer.py | '''
This code is modified from https://github.com/facebookresearch/convit. To adapt the vit/convit to image reconstruction, variable input sizes, and patch sizes for both spatial dimensions.
'''
import torch
import torch.nn as nn
from functools import partial
import torch.nn.functional as F
from timm.models.helpers im... | 15,082 | 39.007958 | 186 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/networks/recon_net.py | import torch.nn as nn
import torch.nn.functional as F
from math import ceil, floor
from .unet import Unet
from .vision_transformer import VisionTransformer
class ReconNet(nn.Module):
def __init__(self, net):
super().__init__()
self.net = net
def pad(self, x):
_, _, h, w = x.shape
... | 1,932 | 25.847222 | 90 | py |
imaging_MLPs | imaging_MLPs-master/compressed_sensing/networks/unet.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT 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
class Unet(nn.Module):
"""
PyTorch implementation of a U-Net... | 5,979 | 31.677596 | 88 | py |
imaging_MLPs | imaging_MLPs-master/untrained/networks/original_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbeddings(nn.Module):
def __init__(
self,
patch_size: int,
hidden_dim: int,
channels: int
... | 3,674 | 26.840909 | 93 | py |
imaging_MLPs | imaging_MLPs-master/untrained/networks/img2img_mixer.py | import torch
import torch.nn as nn
from torch.nn import init
import torch.nn.init as init
import einops
from einops.layers.torch import Rearrange
from einops import rearrange
class PatchEmbedding(nn.Module):
def __init__(
self,
patch_size: int,
embed_dim: int,
channels: int
... | 3,618 | 27.054264 | 127 | py |
imaging_MLPs | imaging_MLPs-master/untrained/networks/vit.py | '''
This code is modified from https://github.com/facebookresearch/convit. To adapt the vit/convit to image reconstruction, variable input sizes, and patch sizes for both spatial dimensions.
'''
import torch
import torch.nn as nn
from functools import partial
import torch.nn.functional as F
from timm.models.helpers im... | 15,082 | 39.007958 | 186 | py |
imaging_MLPs | imaging_MLPs-master/untrained/networks/recon_net.py | import torch.nn as nn
import torch.nn.functional as F
from math import ceil, floor
class ReconNet(nn.Module):
def __init__(self, net):
super().__init__()
self.net = net
def pad(self, x):
_, _, h, w = x.shape
hp, wp = self.net.patch_size
f1 = ( (wp - w % wp) % wp ) / 2
... | 810 | 26.033333 | 90 | py |
imaging_MLPs | imaging_MLPs-master/untrained/networks/unet.py | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT 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
class Unet(nn.Module):
"""
PyTorch implementation of a U-Net ... | 5,981 | 32.79661 | 88 | py |
DeepIR | DeepIR-main/demo.py | #!/usr/bin/env python
import os
import sys
from pprint import pprint
# Pytorch requires blocking launch for proper working
if sys.platform == 'win32':
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
import numpy as np
from scipy import io
import torch
import torch.nn
torch.backends.cudnn.enabled = True
torch.backends... | 2,636 | 31.555556 | 80 | py |
DeepIR | DeepIR-main/modules/losses.py | #!/usr/bin/env python
import torch
class TVNorm():
def __init__(self, mode='l1'):
self.mode = mode
def __call__(self, img):
grad_x = img[..., 1:, 1:] - img[..., 1:, :-1]
grad_y = img[..., 1:, 1:] - img[..., :-1, 1:]
if self.mode == 'isotropic':
#return torc... | 1,586 | 30.117647 | 80 | py |
DeepIR | DeepIR-main/modules/utils.py | #!/usr/bin/env python
'''
Miscellaneous utilities that are extremely helpful but cannot be clubbed
into other modules.
'''
import torch
# Scientific computing
import numpy as np
import scipy.linalg as lin
from scipy import io
# Plotting
import cv2
import matplotlib.pyplot as plt
def nextpow2(x):
'''
... | 6,530 | 21.996479 | 85 | py |
DeepIR | DeepIR-main/modules/dataset.py | #!/usr/bin/env python
import os
import sys
import tqdm
import pdb
import math
import configparser
import numpy as np
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, Dataset
from PIL import Image
from torchvision.transforms import Resize, Compose, ToTensor, ... | 7,382 | 27.287356 | 81 | py |
DeepIR | DeepIR-main/modules/thermal.py | #!/usr/bin/env python
'''
Routines for dealing with thermal images
'''
import tqdm
import copy
import cv2
import numpy as np
from skimage.metrics import structural_similarity as ssim_func
import torch
import kornia
import torch.nn.functional as F
import utils
import losses
import motion
import deep_prior
def ... | 21,820 | 37.485009 | 84 | py |
DeepIR | DeepIR-main/modules/motion.py | #!/usr/bin/env python
'''
Subroutines for estimating motion between images
'''
import os
import sys
import tqdm
import pdb
import math
import numpy as np
from scipy import linalg
from scipy import interpolate
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoad... | 23,853 | 33.772595 | 137 | py |
DeepIR | DeepIR-main/modules/deep_prior.py | #!/usr/bin/env
'''
One single file for all things Deep Image Prior
'''
import os
import sys
import tqdm
import pdb
import numpy as np
import torch
from torch import nn
import torchvision
import cv2
from dmodels.skip import skip
from dmodels.texture_nets import get_texture_nets
from dmodels.resnet import ResNet... | 8,713 | 33.995984 | 138 | py |
DeepIR | DeepIR-main/modules/dmodels/skip.py | import torch
import torch.nn as nn
from .common import *
def skip(
num_input_channels=2, num_output_channels=3,
num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4],
filter_size_down=3, filter_size_up=3, filter_skip_size=1,
... | 3,744 | 36.079208 | 144 | py |
DeepIR | DeepIR-main/modules/dmodels/resnet.py | import torch
import torch.nn as nn
from numpy.random import normal
from numpy.linalg import svd
from math import sqrt
import torch.nn.init
from .common import *
class ResidualSequential(nn.Sequential):
def __init__(self, *args):
super(ResidualSequential, self).__init__(*args)
def forward(self, x):
... | 2,943 | 29.350515 | 195 | py |
DeepIR | DeepIR-main/modules/dmodels/downsampler.py | import numpy as np
import torch
import torch.nn as nn
class Downsampler(nn.Module):
'''
http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf
'''
def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False):
... | 5,379 | 30.83432 | 129 | py |
DeepIR | DeepIR-main/modules/dmodels/dcgan.py | import torch
import torch.nn as nn
def dcgan(inp=2,
ndf=32,
num_ups=4, need_sigmoid=True, need_bias=True, pad='zero', upsample_mode='nearest', need_convT = True):
layers= [nn.ConvTranspose2d(inp, ndf, kernel_size=3, stride=1, padding=0, bias=False),
nn.BatchNorm2d(ndf),
... | 1,244 | 35.617647 | 112 | py |
DeepIR | DeepIR-main/modules/dmodels/texture_nets.py | import torch
import torch.nn as nn
from .common import *
normalization = nn.BatchNorm2d
def conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero'):
if pad == 'zero':
return nn.Conv2d(in_f, out_f, kernel_size, stride, padding=(kernel_size - 1) / 2, bias=bias)
elif pad == 'reflection':
... | 2,315 | 27.95 | 146 | py |
DeepIR | DeepIR-main/modules/dmodels/common.py | import torch
import torch.nn as nn
import numpy as np
from .downsampler import Downsampler
def add_module(self, module):
self.add_module(str(len(self) + 1), module)
torch.nn.Module.add = add_module
class Concat(nn.Module):
def __init__(self, dim, *args):
super(Concat, self).__init__()
sel... | 3,531 | 27.483871 | 128 | py |
DeepIR | DeepIR-main/modules/dmodels/unet.py | import torch.nn as nn
import torch
import torch.nn as nn
import torch.nn.functional as F
from .common import *
class ListModule(nn.Module):
def __init__(self, *args):
super(ListModule, self).__init__()
idx = 0
for module in args:
self.add_module(str(idx), module)
id... | 7,324 | 36.953368 | 164 | py |
DeepIR | DeepIR-main/modules/dmodels/__init__.py | from .skip import skip
from .texture_nets import get_texture_nets
from .resnet import ResNet
from .unet import UNet
import torch.nn as nn
def get_net(input_depth, NET_TYPE, pad, upsample_mode, n_channels=3, act_fun='LeakyReLU', skip_n33d=128, skip_n33u=128, skip_n11=4, num_scales=5, downsample_mode='stride'):
if ... | 1,639 | 50.25 | 172 | py |
AdaptiveGCL | AdaptiveGCL-main/DataHandler.py | import pickle
import numpy as np
from scipy.sparse import csr_matrix, coo_matrix, dok_matrix
from Params import args
import scipy.sparse as sp
from Utils.TimeLogger import log
import torch as t
import torch.utils.data as data
import torch.utils.data as dataloader
class DataHandler:
def __init__(self):
if args.data ... | 3,205 | 29.245283 | 103 | py |
AdaptiveGCL | AdaptiveGCL-main/Main.py | import torch
import Utils.TimeLogger as logger
from Utils.TimeLogger import log
from Params import args
from Model import Model, vgae_encoder, vgae_decoder, vgae, DenoisingNet
from DataHandler import DataHandler
import numpy as np
from Utils.Utils import calcRegLoss, pairPredict
import os
from copy import deepcopy
impo... | 6,846 | 29.9819 | 143 | py |
AdaptiveGCL | AdaptiveGCL-main/Model.py | from torch import nn
import torch.nn.functional as F
import torch
from Params import args
from copy import deepcopy
import numpy as np
import math
import scipy.sparse as sp
from Utils.Utils import contrastLoss, calcRegLoss, pairPredict
import time
import torch_sparse
init = nn.init.xavier_uniform_
class Model(nn.Modu... | 11,377 | 29.180371 | 126 | py |
AdaptiveGCL | AdaptiveGCL-main/Utils/Utils.py | import torch as t
import torch.nn.functional as F
def innerProduct(usrEmbeds, itmEmbeds):
return t.sum(usrEmbeds * itmEmbeds, dim=-1)
def pairPredict(ancEmbeds, posEmbeds, negEmbeds):
return innerProduct(ancEmbeds, posEmbeds) - innerProduct(ancEmbeds, negEmbeds)
def calcRegLoss(model):
ret = 0
for W in model.par... | 694 | 29.217391 | 79 | py |
RG | RG-master/Image Classification/main.py | from __future__ import print_function
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torchvision
import torchvision.transforms as transforms
import os
import argparse
import random
from re... | 4,105 | 30.343511 | 109 | py |
RG | RG-master/Image Classification/resnet.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
import torch.nn.functional as F
from torch.autograd import Variable
cla... | 3,941 | 32.982759 | 102 | py |
RG | RG-master/pix2pix/pix2pix.py | import argparse
import os
import numpy as np
import math
import itertools
import time
import datetime
import sys
import random
import torchvision.transforms as transforms
from torchvision.utils import save_image
from torch.utils.data import DataLoader
from torchvision import datasets
from torch.autograd import Variab... | 7,224 | 36.827225 | 123 | py |
RG | RG-master/pix2pix/datasets.py | import glob
import random
import os
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
import torchvision.transforms as transforms
class ImageDataset(Dataset):
def __init__(self, root, transforms_=None, mode='train'):
self.transform = transforms.Compose(transforms_)
sel... | 1,056 | 28.361111 | 85 | py |
RG | RG-master/pix2pix/models.py | import torch.nn as nn
import torch.nn.functional as F
import torch
def weights_init_normal(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
torch.nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm2d') != -1:
torch.nn.init.normal_(m.weight.data, 1.0... | 4,289 | 32.515625 | 81 | py |
RG | RG-master/Semantic Segmentation/model.py | import torch.nn as nn
import math
import torch.utils.model_zoo as model_zoo
import torch
import numpy as np
affine_par = True
import torch.nn.functional as F
def outS(i):
i = int(i)
i = (i+1)/2
i = int(np.ceil((i+1)/2.0))
i = (i+1)/2
return i
def conv3x3(in_planes, out_planes, stride=1):
"3x3 ... | 11,339 | 36.549669 | 139 | py |
RG | RG-master/Semantic Segmentation/train.py | import datetime
import os
import random
import time
from math import sqrt
import torchvision.transforms as standard_transforms
import torchvision.utils as vutils
# from tensorboard import SummaryWriter
from torch import optim
from torch.autograd import Variable
from torch.backends import cudnn
from torch.optim.lr_sched... | 9,955 | 38.19685 | 219 | py |
CD-Flow | CD-Flow-main/main.py | import torch
from trainnet import trainNet
import pandas as pd
import argparse
def parse_config():
parser = argparse.ArgumentParser()
parser.add_argument("--seed", type=int, default=100)
parser.add_argument("--resume_path", type=str, default=None)
parser.add_argument("--learning_rate", type=float, defa... | 3,377 | 48.676471 | 175 | py |
CD-Flow | CD-Flow-main/test.py | import time
from EMA import EMA
import torch
from torch.utils.data import DataLoader
from model import CDFlow
from DataLoader import CD_128
from coeff_func import *
import os
from loss import createLossAndOptimizer
from torch.autograd import Variable
import torchvision
import torch.autograd as autograd
from function im... | 4,109 | 41.8125 | 117 | py |
CD-Flow | CD-Flow-main/flow.py | import torch
from torch import nn
from torch.nn import functional as F
from math import log, pi, exp
import numpy as np
from scipy import linalg as la
logabs = lambda x: torch.log(torch.abs(x))
class ActNorm(nn.Module):
def __init__(self, in_channel, logdet=True):
super().__init__()
self.loc = nn.... | 10,847 | 28.720548 | 88 | py |
CD-Flow | CD-Flow-main/DataLoader.py | import os
import torch
import random
import numpy as np
from torch.utils.data import Dataset
from PIL import Image
from torchvision import transforms
import torchvision
class CD_128(Dataset):
def __init__(self, jnd_info, root_dir, test=False):
self.ref_name = jnd_info[:, 0]
self.test_name = jnd_inf... | 1,425 | 30 | 81 | py |
CD-Flow | CD-Flow-main/loss.py | import torch
import numpy as np
import torch.optim as optim
import torch.nn as nn
import torch.nn.functional as F
def createLossAndOptimizer(net, learning_rate, scheduler_step, scheduler_gamma):
loss = LossFunc()
# optimizer = optim.Adam([{'params': net.parameters(), 'lr':learning_rate}], lr = learning_rate, w... | 909 | 34 | 119 | py |
CD-Flow | CD-Flow-main/model.py | import math
import time
import torch
import torch.nn as nn
from flow import *
import os
class CDFlow(nn.Module):
def __init__(self):
super(CDFlow, self).__init__()
self.glow = Glow(3, 8, 6, affine=True, conv_lu=True)
def coordinate_transform(self, x_hat, rev=False):
if not rev:
... | 3,702 | 47.090909 | 122 | py |
CD-Flow | CD-Flow-main/function.py | import shutil
import random
import torch
import numpy as np
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True
def copy_codes(trainpath1,trainpath2,trainpath3,trainpath4, path1,path2,path3,... | 484 | 25.944444 | 85 | py |
CD-Flow | CD-Flow-main/trainnet.py | import time
from EMA import EMA
import torch
from torch.utils.data import DataLoader
from model import CDFlow
from DataLoader import CD_128
from coeff_func import *
import os
from loss import createLossAndOptimizer
from torch.autograd import Variable
import torch.autograd as autograd
from function import setup_seed, co... | 11,783 | 44.85214 | 156 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/demo.py | import numpy as np
from arguments import get_args
from models import net
import torch
from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind
def get_tensors(obs):
obs = np.transpose(obs, (2, 0, 1))
obs = np.expand_dims(obs, 0)
obs = torch.tensor(obs, dtype=torch.float32)
return obs
i... | 1,134 | 30.527778 | 90 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# the convolution layer of deepmind
class deepmind(nn.Module):
def __init__(self):
super(deepmind, self).__init__()
self.conv1 = nn.Conv2d(4, 32, 8, stride=4)
self.conv2 = nn.Conv2d(32, 64, 4, stride=2)
self.conv3 = ... | 2,596 | 37.761194 | 88 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/dqn_algos/dqn_agent.py | import sys
import numpy as np
from models import net
from utils import linear_schedule, select_actions, reward_recorder
from rl_utils.experience_replay.experience_replay import replay_buffer
import torch
from datetime import datetime
import os
import copy
# define the dqn agent
class dqn_agent:
def __init__(self, ... | 5,646 | 43.81746 | 144 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/trpo/trpo_agent.py | import torch
import numpy as np
import os
from models import network
from rl_utils.running_filter.running_filter import ZFilter
from utils import select_actions, eval_actions, conjugated_gradient, line_search, set_flat_params_to
from datetime import datetime
class trpo_agent:
def __init__(self, env, args):
... | 9,299 | 52.142857 | 129 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/trpo/utils.py | import numpy as np
import torch
from torch.distributions.normal import Normal
# select actions
def select_actions(pi):
mean, std = pi
normal_dist = Normal(mean, std)
return normal_dist.sample().detach().numpy().squeeze()
# evaluate the actions
def eval_actions(pi, actions):
mean, std = pi
normal_d... | 2,026 | 33.355932 | 125 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/trpo/demo.py | import numpy as np
import torch
import gym
from arguments import get_args
from models import network
def denormalize(x, mean, std, clip=10):
x -= mean
x /= (std + 1e-8)
return np.clip(x, -clip, clip)
def get_tensors(x):
return torch.tensor(x, dtype=torch.float32).unsqueeze(0)
if __name__ == '__main__... | 1,383 | 31.952381 | 94 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/trpo/models.py | import torch
from torch import nn
from torch.nn import functional as F
class network(nn.Module):
def __init__(self, num_states, num_actions):
super(network, self).__init__()
# define the critic
self.critic = critic(num_states)
self.actor = actor(num_states, num_actions)
def for... | 1,376 | 28.297872 | 66 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/a2c/a2c_agent.py | import numpy as np
import torch
from models import net
from datetime import datetime
from utils import select_actions, evaluate_actions, discount_with_dones
import os
class a2c_agent:
def __init__(self, envs, args):
self.envs = envs
self.args = args
# define the network
self.net = n... | 6,370 | 47.633588 | 135 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/a2c/utils.py | import torch
import numpy as np
from torch.distributions.categorical import Categorical
# select - actions
def select_actions(pi, deterministic=False):
cate_dist = Categorical(pi)
if deterministic:
return torch.argmax(pi, dim=1).item()
else:
return cate_dist.sample().unsqueeze(-1)
# get th... | 749 | 29 | 92 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/a2c/demo.py | from arguments import get_args
from models import net
import torch
from utils import select_actions
import cv2
import numpy as np
from rl_utils.env_wrapper.frame_stack import VecFrameStack
from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind
# update the current observation
def get_tensors(obs):
... | 1,193 | 33.114286 | 95 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/a2c/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# the convolution layer of deepmind
class deepmind(nn.Module):
def __init__(self):
super(deepmind, self).__init__()
self.conv1 = nn.Conv2d(4, 32, 8, stride=4)
self.conv2 = nn.Conv2d(32, 64, 4, stride=2)
self.conv3 = ... | 1,959 | 37.431373 | 88 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ddpg/utils.py | import numpy as np
import torch
# add ounoise here
class ounoise():
def __init__(self, std, action_dim, mean=0, theta=0.15, dt=1e-2, x0=None):
self.std = std
self.mean = mean
self.action_dim = action_dim
self.theta = theta
self.dt = dt
self.x0 = x0
# reset t... | 686 | 27.625 | 84 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ddpg/demo.py | from arguments import get_args
import gym
from models import actor
import torch
import numpy as np
def normalize(obs, mean, std, clip):
return np.clip((obs - mean) / std, -clip, clip)
if __name__ == '__main__':
args = get_args()
env = gym.make(args.env_name)
# get environment infos
obs_dims = env.... | 1,518 | 34.325581 | 90 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ddpg/ddpg_agent.py | import numpy as np
from models import actor, critic
import torch
import os
from datetime import datetime
from mpi4py import MPI
from rl_utils.mpi_utils.normalizer import normalizer
from rl_utils.mpi_utils.utils import sync_networks, sync_grads
from rl_utils.experience_replay.experience_replay import replay_buffer
from... | 8,833 | 45.494737 | 142 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ddpg/models.py | import torch
import torch.nn as nn
import torch.nn.functional as F
# define the actor network
class actor(nn.Module):
def __init__(self, obs_dims, action_dims):
super(actor, self).__init__()
self.fc1 = nn.Linear(obs_dims, 400)
self.fc2 = nn.Linear(400, 300)
self.action_out = nn.Line... | 950 | 28.71875 | 53 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ppo/utils.py | import numpy as np
import torch
from torch.distributions.normal import Normal
from torch.distributions.beta import Beta
from torch.distributions.categorical import Categorical
import random
def select_actions(pi, dist_type, env_type):
if env_type == 'atari':
actions = Categorical(pi).sample()
else:
... | 1,370 | 35.078947 | 78 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ppo/demo.py | from arguments import get_args
from models import cnn_net, mlp_net
import torch
import cv2
import numpy as np
import gym
from rl_utils.env_wrapper.frame_stack import VecFrameStack
from rl_utils.env_wrapper.atari_wrapper import make_atari, wrap_deepmind
# denormalize
def normalize(x, mean, std, clip=10):
x -= mean
... | 2,641 | 35.694444 | 112 | py |
reinforcement-learning-algorithms | reinforcement-learning-algorithms-master/rl_algorithms/ppo/models.py | import torch
from torch import nn
from torch.nn import functional as F
"""
this network also include gaussian distribution and beta distribution
"""
class mlp_net(nn.Module):
def __init__(self, state_size, num_actions, dist_type):
super(mlp_net, self).__init__()
self.dist_type = dist_type
... | 3,913 | 37 | 88 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.