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 |
|---|---|---|---|---|---|---|
Pytorch-implementation-of-SRNet | Pytorch-implementation-of-SRNet-master/utils/utils.py | """This module provides utility function for training."""
import os
import re
from typing import Any, Dict
import torch
from torch import nn
from opts.options import arguments
opt = arguments()
def saver(state: Dict[str, float], save_dir: str, epoch: int) -> None:
torch.save(state, save_dir + "net_" + str(epoch... | 1,504 | 29.714286 | 75 | py |
Pytorch-implementation-of-SRNet | Pytorch-implementation-of-SRNet-master/model/utils.py | """This module provide building blocks for SRNet."""
from torch import nn
from torch import Tensor
class ConvBn(nn.Module):
"""Provides utility to create different types of layers."""
def __init__(self, in_channels: int, out_channels: int) -> None:
"""Constructor.
Args:
in_channe... | 3,652 | 27.317829 | 68 | py |
Pytorch-implementation-of-SRNet | Pytorch-implementation-of-SRNet-master/model/model.py | """ This module creates SRNet model."""
import torch
from torch import Tensor
from torch import nn
from model.utils import Type1, Type2, Type3, Type4
class Srnet(nn.Module):
"""This is SRNet model class."""
def __init__(self) -> None:
"""Constructor."""
super().__init__()
self.type1s ... | 1,424 | 26.403846 | 74 | py |
Seq-Att-Affect | Seq-Att-Affect-master/utils.py | import numpy as np
import re
import cv2
from operator import truediv
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
from pathlib import Path
#import tensorflow as tf
import random
import csv
#from config import *
from scipy.integrate.quadrature import simps
import math
from scipy.stats import... | 78,260 | 31.676827 | 204 | py |
Seq-Att-Affect | Seq-Att-Affect-master/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from operator import truediv
class Combiner(nn.Module):
"""Combiner based on discriminator"""
def __init__(self, image_size=128, conv_dim=64, c_dim=5, repeat_num=4, inputC = 3):
super(Combiner, self).__init__()
... | 67,049 | 33.795018 | 137 | py |
Seq-Att-Affect | Seq-Att-Affect-master/main_red_test.py | import os
import argparse
from solver import Solver
from data_loader import get_loader
from torch.backends import cudnn
from model import Generator,Combiner
from model import Discriminator,DiscriminatorM,DiscriminatorMST, DiscriminatorMZ,\
DiscriminatorMZR, Combiner,CombinerSeq,CombinerSeqL,CombinerSeqAtt,CombinerSeqAt... | 40,371 | 38.972277 | 237 | py |
Seq-Att-Affect | Seq-Att-Affect-master/main_gan_single_reduction.py | import os
import argparse
from solver import Solver
from data_loader import get_loader
from torch.backends import cudnn
from model import Generator, Discriminator, GeneratorM, GeneratorMZ, GeneratorMZR, DiscriminatorM,
DiscriminatorMST,DiscriminatorMZ,DiscriminatorMZR,DiscriminatorMZRL,CombinerSeqAtt
from torch.autog... | 44,327 | 36.156748 | 237 | py |
Seq-Att-Affect | Seq-Att-Affect-master/FacialDataset.py | from math import sqrt
import re
from PIL import Image,ImageFilter
import torch
from torch.utils import data
import torchvision.transforms as transforms
import torchvision.utils as vutils
import csv
import torchvision.transforms.functional as F
import numbers
from torchvision.transforms import RandomRotation,RandomRes... | 111,306 | 37.381724 | 243 | py |
PROTES | PROTES-main/protes/protes.py | import jax
import jax.numpy as jnp
import optax
from time import perf_counter as tpc
def protes(f, d, n, m, k=100, k_top=10, k_gd=1, lr=5.E-2, r=5, seed=0,
is_max=False, log=False, log_ind=False, info={}, P=None,
with_info_i_opt_list=False, with_info_full=False):
time = tpc()
info.update... | 5,895 | 28.333333 | 78 | py |
PROTES | PROTES-main/protes/protes_general.py | import jax
import jax.numpy as jnp
import optax
from time import perf_counter as tpc
def protes_general(f, n, m, k=100, k_top=10, k_gd=1, lr=5.E-2, r=5, seed=0,
is_max=False, log=False, log_ind=False, info={}, P=None,
with_info_i_opt_list=False, with_info_full=False):
time = ... | 5,369 | 25.453202 | 78 | py |
PROTES | PROTES-main/protes/animation.py | import jax.numpy as jnp
import matplotlib as mpl
from matplotlib import cm
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter
from matplotlib.ticker import LinearLocator
import numpy as np
import os
from time import perf_counter as tpc
from ... | 4,670 | 30.993151 | 80 | py |
PROTES | PROTES-main/demo/demo_func.py | import jax.numpy as jnp
from time import perf_counter as tpc
from protes import protes
def func_build(d, n):
"""Ackley function. See https://www.sfu.ca/~ssurjano/ackley.html."""
a = -32.768 # Grid lower bound
b = +32.768 # Grid upper bound
par_a = 20. # Standard parameter v... | 2,206 | 30.084507 | 78 | py |
PROTES | PROTES-main/calc/calc_one.py | import numpy as np
import os
from time import perf_counter as tpc
from jax.config import config
config.update('jax_enable_x64', True)
os.environ['JAX_PLATFORM_NAME'] = 'cpu'
from protes import protes
from teneva_bm import BmQuboKnapAmba
from opti import *
Optis = {
'Our': OptiProtes,
'BS-1': OptiTTOpt,
... | 1,716 | 22.202703 | 75 | py |
PROTES | PROTES-main/calc/calc.py | import matplotlib as mpl
import numpy as np
import os
import pickle
import sys
from time import perf_counter as tpc
mpl.rcParams.update({
'font.family': 'normal',
'font.serif': [],
'font.sans-serif': [],
'font.monospace': [],
'font.size': 12,
'text.usetex': False,
})
import matplotlib.cm as ... | 7,201 | 25.477941 | 79 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/flux_utils.py | import torch
import numpy as np
from torch import nn
from torch import optim
import deblending_runjingdev.utils as utils
from deblending_runjingdev.simulated_datasets_lib import plot_one_star
from deblending_runjingdev.wake_lib import PlanarBackground
class FluxEstimator(nn.Module):
def __init__(self, observed_i... | 6,185 | 34.348571 | 104 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/image_utils.py | import torch
from torch import nn
import deblending_runjingdev.utils as utils
from deblending_runjingdev.which_device import device
# This function copied from
# https://gist.github.com/dem123456789/23f18fd78ac8da9615c347905e64fc78
def _extract_patches_2d(img,patch_shape,step=[1.0,1.0],batch_first=False):
patch... | 8,377 | 42.409326 | 126 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/daophot_catalog_lib.py | import torch
import numpy as np
from deblending_runjingdev.which_device import device
from deblending_runjingdev.sdss_dataset_lib import convert_mag_to_nmgy
from deblending_runjingdev.image_statistics_lib import get_locs_error
def load_daophot_results(data_file,
nelec_per_nmgy,
... | 2,859 | 38.178082 | 96 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/utils.py | import torch
import numpy as np
from torch.distributions import normal, categorical
from deblending_runjingdev.which_device import device
# Functions to work with n_stars
def get_is_on_from_n_stars(n_stars, max_stars):
assert len(n_stars.shape) == 1
batchsize = len(n_stars)
is_on_array = torch.zeros((ba... | 2,374 | 29.448718 | 95 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/starnet_lib.py | import torch
import torch.nn as nn
import numpy as np
import deblending_runjingdev.image_utils as image_utils
import deblending_runjingdev.utils as utils
from deblending_runjingdev.which_device import device
from itertools import product
from torch.distributions import poisson
class Flatten(nn.Module):
def fo... | 18,839 | 40.045752 | 130 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/elbo_lib.py | import torch
import numpy as np
import time
from torch import nn
import deblending_runjingdev.starnet_lib as starnet_lib
from deblending_runjingdev.which_device import device
def get_neg_elbo(simulator, full_image, locs, fluxes, n_stars, \
log_q_locs, log_q_fluxes, log_q_n_stars,
... | 8,194 | 40.180905 | 107 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/wake_lib.py | import torch
import torch.nn as nn
from torch import optim
import numpy as np
from deblending_runjingdev.simulated_datasets_lib import _get_mgrid, plot_multiple_stars
from deblending_runjingdev.psf_transform_lib import PowerLawPSF
import deblending_runjingdev.utils
from deblending_runjingdev.which_device import devic... | 18,610 | 36.147705 | 109 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/plotting_utils.py | import matplotlib.pyplot as plt
import torch
import numpy as np
import deblending_runjingdev.image_utils as image_utils
from deblending_runjingdev.which_device import device
def plot_image(fig, image,
true_locs = None, estimated_locs = None,
vmin = None, vmax = None,
a... | 4,500 | 35.593496 | 84 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/sdss_dataset_lib.py | import pathlib
import os
import pickle
import numpy as np
from scipy.interpolate import RegularGridInterpolator
import scipy.stats as stats
import torch
from torch.utils.data import Dataset
from astropy.io import fits
from astropy.wcs import WCS
import matplotlib.pyplot as plt
from deblending_runjingdev.simulated_d... | 10,043 | 37.482759 | 110 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/psf_transform_lib.py | import torch
import torch.nn as nn
from torch.nn.functional import unfold, softmax, pad
from astropy.io import fits
import deblending_runjingdev.image_utils as image_utils
from deblending_runjingdev.utils import eval_normal_logprob
from deblending_runjingdev.simulated_datasets_lib import _get_mgrid, plot_multiple_st... | 6,346 | 32.582011 | 101 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/simulated_datasets_lib.py | import numpy as np
import scipy.stats as stats
import torch
from torch.utils.data import Dataset, DataLoader
import torch
import torch.nn.functional as F
import deblending_runjingdev.utils as utils
from deblending_runjingdev.which_device import device
def _trim_psf(psf, slen):
# crop the psf to length slen x sl... | 10,604 | 30.751497 | 98 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/image_statistics_lib.py | import torch
import numpy as np
from deblending_runjingdev.sdss_dataset_lib import convert_nmgy_to_mag
from deblending_runjingdev.which_device import device
def filter_params(locs, fluxes, slen, pad = 5):
assert len(locs.shape) == 2
if fluxes is not None:
assert len(fluxes.shape) == 1
assert ... | 5,243 | 35.416667 | 97 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/sleep_lib.py | import torch
import numpy as np
import math
import time
from torch.distributions import normal
from torch.nn import CrossEntropyLoss
import deblending_runjingdev.utils as utils
import deblending_runjingdev.elbo_lib as elbo_lib
from deblending_runjingdev.which_device import device
from itertools import permutations... | 9,800 | 37.136187 | 127 | py |
DeblendingStarfields | DeblendingStarfields-master/deblending_runjingdev/which_device.py | import torch
device = torch.device("cuda:6" if torch.cuda.is_available() else "cpu")
# device = 'cpu'
| 102 | 24.75 | 71 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_sparse_field/sparse_field_lib.py | import numpy as np
import torch
import fitsio
from astropy.io import fits
from astropy.wcs import WCS
import deblending_runjingdev.sdss_dataset_lib as sdss_dataset_lib
from deblending_runjingdev.sdss_dataset_lib import _get_mgrid2
def load_data(catalog_file = '../coadd_field_catalog_runjing_liu.fit',
... | 2,936 | 33.151163 | 90 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_sparse_field/train_sleep-sparse_field.py | import numpy as np
import torch
import torch.optim as optim
from deblending_runjingdev import simulated_datasets_lib
from deblending_runjingdev import starnet_lib
from deblending_runjingdev import sleep_lib
from deblending_runjingdev import psf_transform_lib
from deblending_runjingdev import wake_lib
import json
im... | 4,469 | 29.827586 | 87 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_m2/train_wake_sleep.py | import numpy as np
import torch
import torch.optim as optim
import deblending_runjingdev.sdss_dataset_lib as sdss_dataset_lib
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.starnet_lib as starnet_lib
import deblending_runjingdev.sleep_lib as sleep_lib
from d... | 7,431 | 33.567442 | 112 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_m2/train_sleep.py | import numpy as np
import torch
import torch.optim as optim
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.sdss_dataset_lib as sdss_dataset_lib
import deblending_runjingdev.starnet_lib as starnet_lib
import deblending_runjingdev.sleep_lib as sleep_lib
import... | 3,978 | 28.474074 | 89 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_deblending/train_encoder.py | import numpy as np
import torch
import torch.optim as optim
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.starnet_lib as starnet_lib
import deblending_runjingdev.sleep_lib as sleep_lib
import deblending_runjingdev.psf_transform_lib as psf_transform_lib
imp... | 3,330 | 25.862903 | 89 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_elbo_vs_sleep/train_elbo.py | import numpy as np
import torch
import torch.optim as optim
import deblending_runjingdev.elbo_lib as elbo_lib
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.starnet_lib as starnet_lib
import deblending_runjingdev.psf_transform_lib as psf_transform_lib
impor... | 5,869 | 30.55914 | 90 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_elbo_vs_sleep/train_elbo-Copy1.py | import numpy as np
import torch
import torch.optim as optim
import deblending_runjingdev.elbo_lib as elbo_lib
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.starnet_lib as starnet_lib
import deblending_runjingdev.psf_transform_lib as psf_transform_lib
impor... | 5,279 | 33.509804 | 100 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_elbo_vs_sleep/simulate_test_images.py | import numpy as np
import torch
import json
import matplotlib.pyplot as plt
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.psf_transform_lib as psf_transform_lib
from deblending_runjingdev.which_device import device
np.random.seed(65765)
_ = torch.manual_... | 3,256 | 29.439252 | 97 | py |
DeblendingStarfields | DeblendingStarfields-master/experiments_elbo_vs_sleep/train_sleep.py | import numpy as np
import torch
import torch.optim as optim
import deblending_runjingdev.simulated_datasets_lib as simulated_datasets_lib
import deblending_runjingdev.starnet_lib as starnet_lib
import deblending_runjingdev.sleep_lib as sleep_lib
import deblending_runjingdev.psf_transform_lib as psf_transform_lib
impo... | 4,752 | 26.316092 | 89 | py |
lightkurve | lightkurve-main/docs/source/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
sys.path.appe... | 5,016 | 33.363014 | 326 | py |
miccai2022-roigan | miccai2022-roigan-main/main.py | import os
import argparse
import yaml
import collections
import itertools
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from torchvision import datasets
from sklearn.model_selection import train_test_split
from src import models, utils
def main(arg... | 10,158 | 36.487085 | 201 | py |
miccai2022-roigan | miccai2022-roigan-main/src/utils.py | import os
import sys
import h5py
import random
import numpy as np
import pandas as pd
import torch
from torch.autograd import Variable
from torchvision.utils import save_image, make_grid
from torch.utils.data import DataLoader
def write_flush(*text_args, stream=sys.stdout):
stream.write(', '.join(map(str, text_... | 7,345 | 32.543379 | 124 | py |
miccai2022-roigan | miccai2022-roigan-main/src/models.py | import torch
import torch.nn as nn
from torchvision.ops import RoIAlign
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)
if hasattr(m, 'bias') and m.bias is not None:
torch.nn.init.constant... | 5,076 | 31.132911 | 99 | py |
hgp | hgp-main/hgp/core/kernels.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 8,840 | 34.939024 | 121 | py |
hgp | hgp-main/hgp/core/flow.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 4,501 | 36.831933 | 115 | py |
hgp | hgp-main/hgp/core/constraint_likelihoods.py | import torch
import torch.nn as nn
from torch import distributions
from torch.nn import init
from hgp.misc.constraint_utils import invsoftplus, softplus
class Gaussian(nn.Module):
"""
Gaussian likelihood with an optionally trainable scale parameter
"""
def __init__(
self, d: int = 1, scale: ... | 2,282 | 29.44 | 85 | py |
hgp | hgp-main/hgp/core/dsvgp.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 12,813 | 39.169279 | 138 | py |
hgp | hgp-main/hgp/core/nn.py | import functorch
import torch
from torch import nn
from hgp.misc.ham_utils import build_J
def Linear(chin, chout, zero_bias=False, orthogonal_init=False):
linear = nn.Linear(chin, chout)
if zero_bias:
torch.nn.init.zeros_(linear.bias)
if orthogonal_init:
torch.nn.init.orthogonal_(linear.w... | 1,637 | 25.852459 | 84 | py |
hgp | hgp-main/hgp/core/states.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 10,358 | 31.990446 | 99 | py |
hgp | hgp-main/hgp/core/observation_likelihoods.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 2,157 | 33.253968 | 88 | py |
hgp | hgp-main/hgp/models/sequence.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 19,534 | 34.261733 | 118 | py |
hgp | hgp-main/hgp/models/initialization.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 11,106 | 37.835664 | 96 | py |
hgp | hgp-main/hgp/models/builder.py | # MIT License
# Copyright (c) 2021 Pashupati Hegde.
# Copyright (c) 2023 Magnus Ross.
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the r... | 31,938 | 30.716981 | 135 | py |
hgp | hgp-main/hgp/datasets/hamiltonians.py | # import numpy as np
import functorch
import numpy as np
import torch
from torchdiffeq import odeint
from hgp.misc.ham_utils import build_J
from hgp.misc.torch_utils import numpy2torch, torch2numpy
# from scipy.integrate import odeint
class Data:
def __init__(self, ys, ts):
self.ts = ts.astype(np.float3... | 6,888 | 26.890688 | 86 | py |
hgp | hgp-main/hgp/misc/plot_utils.py | from hgp.misc.torch_utils import torch2numpy, numpy2torch
import matplotlib.pyplot as plt
from matplotlib import cm
import matplotlib
import shutil
import numpy as np
from hgp.models.builder import compute_summary
def plot_predictions(data, test_pred, save=None, test_true=None, model_name="Model"):
test_ts, te... | 7,650 | 31.012552 | 88 | py |
hgp | hgp-main/hgp/misc/settings.py | import torch
import numpy
class Settings:
def __init__(self):
pass
@property
def torch_int(self):
return torch.int32
@property
def numpy_int(self):
return numpy.int32
@property
def device(self):
# return torch.device('cpu')
# return torch.device('... | 630 | 16.054054 | 77 | py |
hgp | hgp-main/hgp/misc/ham_utils.py | import torch
def build_J(D_in):
assert D_in % 2 == 0
I = torch.eye(D_in // 2)
zeros = torch.zeros((D_in // 2, D_in // 2))
zI = torch.hstack((zeros, I))
mIz = torch.hstack((-I, zeros))
return torch.vstack((zI, mIz))
| 241 | 21 | 47 | py |
hgp | hgp-main/hgp/misc/train_utils.py | import random
import numpy as np
import torch
def seed_everything(seed):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.use_deterministic_algorithms(True)
def get_logger(logpath, filepath, add_stdout=True):
logger = logging.getLogger()
l... | 2,731 | 23.836364 | 88 | py |
hgp | hgp-main/hgp/misc/torch_utils.py | from hgp.misc.settings import settings
import numpy as np
import torch
device = settings.device
dtype = settings.torch_float
def numpy2torch(x):
return (
torch.tensor(x, dtype=dtype).to(device)
if type(x) is np.ndarray
else x.to(device)
)
def torch2numpy(x):
return x if type(x) ... | 1,487 | 22.619048 | 85 | py |
hgp | hgp-main/hgp/misc/constraint_utils.py | import torch
import torch.nn.functional as F
def softplus(x):
lower = 1e-12
return F.softplus(x) + lower
def invsoftplus(x):
lower = 1e-12
xs = torch.max(x - lower, torch.tensor(torch.finfo(x.dtype).eps).to(x))
return xs + torch.log(-torch.expm1(-xs))
| 276 | 18.785714 | 75 | py |
hgp | hgp-main/hgp/misc/param.py | import numpy as np
import torch
from hgp.misc import transforms
from hgp.misc.settings import settings
class Param(torch.nn.Module):
"""
A class to handle contrained --> unconstrained optimization using variable transformations.
Similar to Parameter class in GPflow : https://github.com/GPflow/GPflow/blob... | 913 | 31.642857 | 103 | py |
hgp | hgp-main/hgp/misc/transforms.py | from hgp.misc.settings import settings
import numpy as np
import torch
import torch.nn.functional as F
class Identity:
def __init__(self):
pass
def __str__(self):
return "Identity transformation"
def forward_tensor(self, x):
return x
def backward_tensor(self, y):
re... | 3,936 | 27.323741 | 88 | py |
hgp | hgp-main/tests/test_kernels.py | import pytest
import hgp.core.kernels as kernels
import torch
@pytest.fixture()
def t():
return 1 * torch.randn(10, 4)
@pytest.fixture()
def kernel():
k = kernels.DerivativeRBF(4)
return k
def test_single_k(t, kernel):
K = kernel.K(t)
for i in range(10):
for j in range(10):
... | 3,261 | 24.286822 | 77 | py |
hgp | hgp-main/experiments/initial_pendulum/experiment.py | import logging
import os
import hydra
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import torch
from matplotlib import cm
from matplotlib.collections import LineCollection
from matplotlib.legend import _get_legend_handles_labels
from omegaconf import DictConfig
import hgp
from hgp.datasets.ham... | 6,928 | 31.078704 | 86 | py |
hgp | hgp-main/experiments/forward_trajectory/experiment.py | import logging
import os
import pickle
from distutils.dir_util import copy_tree
from pathlib import Path
import hydra
import numpy as np
import torch
from omegaconf import DictConfig
import hgp
from hgp.datasets.hamiltonians import load_system_from_name
from hgp.misc.plot_utils import (
plot_comparison_traces,
... | 4,625 | 30.469388 | 83 | py |
hgp | hgp-main/experiments/multiple_trajectory/experiment.py | import logging
import os
import pickle
from distutils.dir_util import copy_tree
from pathlib import Path
import hydra
import numpy as np
import torch
from omegaconf import DictConfig
import hgp
from hgp.datasets.hamiltonians import load_system_from_name
from hgp.misc.plot_utils import (
plot_comparison_traces,
... | 5,012 | 29.944444 | 83 | py |
SubGNN | SubGNN-main/SubGNN/anchor_patch_samplers.py | # General
import numpy as np
import random
from collections import defaultdict
import networkx as nx
import sys
import time
# Pytorch
import torch
# Our Methods
sys.path.insert(0, '..') # add config to path
import config
import subgraph_utils
#######################################################
# Triangular Rando... | 23,117 | 51.901602 | 179 | py |
SubGNN | SubGNN-main/SubGNN/subgraph_utils.py | # General
import typing
import sys
import numpy as np
#Networkx
import networkx as nx
# Sklearn
from sklearn.preprocessing import MultiLabelBinarizer
from sklearn.metrics import f1_score, accuracy_score
# Pytorch
import torch
import torch.nn.functional as F
import torch.nn as nn
from torch.nn.functional import one_h... | 10,206 | 41.886555 | 172 | py |
SubGNN | SubGNN-main/SubGNN/subgraph_mpn.py | # General
import numpy as np
import sys
from multiprocessing import Pool
import time
# Pytorch
import torch
import torch.nn as nn
import torch.nn.functional as F
# Pytorch Geometric
from torch_geometric.utils import add_self_loops
from torch_geometric.nn import MessagePassing
# Our methods
sys.path.insert(0, '..') #... | 12,371 | 50.123967 | 223 | py |
SubGNN | SubGNN-main/SubGNN/datasets.py | # Pytorch
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, Dataset
# Typing
from typing import List
class SubgraphDataset(Dataset):
'''
Stores subgraphs and their associated labels as well as precomputed similarities and border sets for the subgraphs
'''
def __init__(self, ... | 1,904 | 31.844828 | 130 | py |
SubGNN | SubGNN-main/SubGNN/train_config.py | # General
import numpy as np
import random
import argparse
import tqdm
import pickle
import json
import commentjson
import joblib
import os
import sys
import pathlib
from collections import OrderedDict
import random
import string
# Pytorch
import torch
from torch.utils.data import DataLoader
from torch.nn.functional i... | 11,383 | 39.226148 | 156 | py |
SubGNN | SubGNN-main/SubGNN/SubGNN.py | # General
import os
import numpy as np
from pathlib import Path
import typing
import time
import json
import copy
from typing import Dict, List
import multiprocessing
from multiprocessing import Pool
from itertools import accumulate
from collections import OrderedDict
import pickle
import sys
from functools import par... | 64,806 | 54.676117 | 326 | py |
SubGNN | SubGNN-main/SubGNN/gamma.py | # General
import sys
import time
import numpy as np
# Pytorch & Networkx
import torch
import networkx as nx
# Dynamic time warping
from fastdtw import fastdtw
# Our methods
sys.path.insert(0, '..') # add config to path
import config
###########################################
# DTW of degree sequences
def get_de... | 1,810 | 28.209677 | 126 | py |
SubGNN | SubGNN-main/SubGNN/attention.py | import torch
from torch.nn.parameter import Parameter
# All of the below code is taken from AllenAI's AllenNLP library
def tiny_value_of_dtype(dtype: torch.dtype):
"""
Returns a moderately tiny value for a given PyTorch data type that is used to avoid numerical
issues such as division by zero.
This is... | 6,880 | 47.801418 | 107 | py |
SubGNN | SubGNN-main/SubGNN/train.py | # General
import numpy as np
import random
import argparse
import tqdm
import pickle
import json
import joblib
import os
import time
import sys
import pathlib
import random
import string
# Pytorch
import torch
from torch.utils.data import DataLoader
from torch.nn.functional import one_hot
import pytorch_lightning as p... | 21,662 | 42.5 | 170 | py |
SubGNN | SubGNN-main/prepare_dataset/train_node_emb.py | # General
import numpy as np
import random
import argparse
import os
import config_prepare_dataset as config
import preprocess
import model as mdl
import utils
# Pytorch
import torch
from torch_geometric.utils.convert import to_networkx, to_scipy_sparse_matrix
from torch_geometric.data import Data, DataLoader, Neighb... | 9,326 | 48.611702 | 334 | py |
SubGNN | SubGNN-main/prepare_dataset/utils.py | # General
import random
import numpy as np
# Pytorch
import torch
import torch.nn.functional as F
from torch.nn import Sigmoid
from torch_geometric.data import Dataset
# Matplotlib
from matplotlib import pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
# Sci-kit Learn
from sklearn.metrics import ro... | 7,302 | 32.810185 | 144 | py |
SubGNN | SubGNN-main/prepare_dataset/model.py | # Pytorch
import torch
import torch.nn as nn
from torch.nn import Linear, LayerNorm, ReLU
from torch_geometric.nn import GINConv, GCNConv
import torch.nn.functional as F
# General
import numpy as np
import torch
import utils
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class TrainNet(nn.... | 1,045 | 27.27027 | 69 | py |
SubGNN | SubGNN-main/prepare_dataset/prepare_dataset.py | # General
import numpy as np
import random
import typing
import logging
from collections import Counter, defaultdict
import config_prepare_dataset as config
import os
if not os.path.exists(config.DATASET_DIR):
os.makedirs(config.DATASET_DIR)
import train_node_emb
# Pytorch
import torch
from torch_geometric.data ... | 36,300 | 42.63101 | 152 | py |
SubGNN | SubGNN-main/prepare_dataset/preprocess.py | # General
import numpy as np
import random
import pickle
from collections import Counter
# Pytorch
import torch
from torch_geometric.data import Data
from torch_geometric.utils import from_networkx, negative_sampling
from torch_geometric.utils.convert import to_networkx
# NetworkX
import networkx as nx
from networkx.... | 3,076 | 27.490741 | 152 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/main.py | import torch
import random
import copy
import numpy as np
import time
from BResidual import BResidual
from options import arg_parameter
from data_util import load_cifar10, load_mnist
from federated import Cifar10FedEngine
from aggregator import parameter_aggregate, read_out
from util import *
def main(args):
args... | 5,188 | 37.437037 | 120 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/BResidual.py | import torch.nn as nn
import torch
from collections import namedtuple
import numpy as np
union = lambda *dicts: {k: v for d in dicts for (k, v) in d.items()}
sep = '_'
RelativePath = namedtuple('RelativePath', ('parts'))
rel_path = lambda *parts: RelativePath(parts)
class BResidual(nn.Module):
def __init__(self,... | 6,919 | 32.756098 | 171 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/GraphConstructor.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class GraphConstructor(nn.Module):
def __init__(self, nnodes, k, dim, device, alpha=3, static_feat=None):
super(GraphConstructor, self).__init__()
self.nnodes = nnodes
if static_feat is not None:
xd = static_fea... | 2,074 | 31.421875 | 103 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/aggregator.py | import copy
import torch
import os
import pickle as pk
from util import sd_matrixing
from data_util import normalize_adj
from GraphConstructor import GraphConstructor
from optimiser import FedProx
import numpy as np
from scipy import linalg
def parameter_aggregate(args, A, w_server, global_model, server_state, client... | 6,429 | 34.921788 | 121 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/optimiser.py | import numpy as np
import torch
from collections import namedtuple
from util import PiecewiseLinear
from torch.optim.optimizer import Optimizer, required
import torch.distributed as dist
class TorchOptimiser():
def __init__(self, weights, optimizer, step_number=0, **opt_params):
self.weights = weights
... | 6,524 | 35.049724 | 97 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/data_util.py | import torch
import numpy as np
import scipy.sparse as sp
from torchvision import datasets
from collections import namedtuple
from torchvision import datasets, transforms
import pickle as pk
def load_image(args):
data_dir = "./data/" + str(args.dataset)
data_mean = (0.4914, 0.4822, 0.4465) # equals np.mean(t... | 11,858 | 36.647619 | 119 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/federated.py | import threading
import datetime
import torch
import time
import numpy as np
from BResidual import BResidual
from optimiser import SGD
from util import sd_matrixing, PiecewiseLinear, trainable_params, StatsLogger
class Cifar10FedEngine:
def __init__(self, args, dataloader, global_param, server_param, local_param,... | 5,404 | 35.033333 | 101 | py |
SFL-Structural-Federated-Learning | SFL-Structural-Federated-Learning-main/util.py | import datetime
import random
import os
import torch
import numpy as np
from collections import namedtuple
from functools import singledispatch
def print2file(buf, out_file, p=False):
if p:
print(buf)
outfd = open(out_file, 'a+')
outfd.write(str(datetime.datetime.now()) + '\t' + buf + '\n')
ou... | 2,561 | 24.366337 | 117 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/MGANet_test_LD37.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from numpy import *
# from scipy.misc import imresize
from skimage.measure import compare_ssim
import cv2
import glob
import time
import os
import argparse
import Net.MGANet as MGANet
import torch
import copy
def yuv_import(filename, dims ,startfrm,numf... | 9,952 | 41.900862 | 211 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/MGANet_test_AI37.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from numpy import *
# from scipy.misc import imresize
from skimage.measure import compare_ssim
import cv2
import glob
import time
import os
import argparse
import Net.MGANet as MGANet
import torch
import copy
def yuv_import(filename, dims ,startfrm,numf... | 9,464 | 41.443946 | 209 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/LSTM/functional.py | from functools import partial
import torch
import torch.nn.functional as F
from torch.nn._functions.thnn import rnnFusedPointwise as fusedBackend
from .utils import _single, _pair, _triple
def RNNReLUCell(input, hidden, w_ih, w_hh, b_ih=None, b_hh=None, linear_func=None):
""" Copied from torch.nn._functions.rnn... | 11,086 | 33.755486 | 113 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/LSTM/utils.py | import collections
from itertools import repeat
""" Copied from torch.nn.modules.utils """
def _ntuple(n):
def parse(x):
if isinstance(x, collections.Iterable):
return x
return tuple(repeat(x, n))
return parse
_single = _ntuple(1)
_pair = _ntuple(2)
_triple = _ntuple(3)
_quadru... | 337 | 15.9 | 47 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/LSTM/module.py | import math
from typing import Union, Sequence
import torch
from torch.nn import Parameter
from torch.nn.utils.rnn import PackedSequence
from .functional import AutogradConvRNN, _conv_cell_helper
from .utils import _single, _pair, _triple
class ConvNdRNNBase(torch.nn.Module):
def __init__(self,
... | 35,171 | 33.789318 | 109 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/LSTM/BiConvLSTM.py | import torch.nn as nn
from torch.autograd import Variable
import torch
torch.cuda.set_device(0)
class BiConvLSTMCell(nn.Module):
def __init__(self, input_size, input_dim, hidden_dim, kernel_size, bias):
"""
Initialize ConvLSTM cell.
Parameters
----------
input_size: (int, i... | 6,521 | 39.259259 | 130 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/Net/net_view.py | from graphviz import Digraph
from torch.autograd import Variable
import torch
def make_dot(var, params=None):
""" Produces Graphviz representation of PyTorch autograd graph
Blue nodes are the Variables that require grad, orange are Tensors
saved for backward in torch.autograd.Function
Args:
var:... | 2,016 | 37.788462 | 83 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/Net/multiscaleloss.py | import torch
import torch.nn as nn
def EPE(input_image, target_image,L_model=None):
loss_L2 = L_model(input_image,target_image)
return loss_L2
# EPE_map = torch.norm(target_image-input_image,2,1)
# batch_size = EPE_map.size(0)
#
# if mean:
# return EPE_map.mean()
# else:
# ... | 1,280 | 26.255319 | 131 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/Net/MGANet.py | import torch
import torch.nn as nn
from torch.nn.init import kaiming_normal
from LSTM.BiConvLSTM import BiConvLSTM
def conv(batchNorm, in_planes, out_planes, kernel_size=3, stride=1):
if batchNorm:
return nn.Sequential(
nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, ... | 7,816 | 41.483696 | 142 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/dataloader/read_h5.py | import numpy as np
import cv2
import torch.multiprocessing as mp
mp.set_start_method('spawn')
import h5py
f = h5py.File('../../train_b8_LD37.h5','r')
for key in f.keys():
print(f[key].name,f[key].shape)
# for i in range(1,100):
# cv2.imshow('1.jpg',f[key][i,0,...])
# cv2.waitKey(0)
| 301 | 20.571429 | 43 | py |
MGANet-DCC2020 | MGANet-DCC2020-master/codes/dataloader/h5_dataset_T.py | import torch.utils.data as data
import torch
import numpy as np
from torchvision import transforms, datasets
import h5py
def data_augmentation(image, mode):
if mode == 0:
# original
return image
elif mode == 1:
# flip up and down
return np.flipud(image)
elif mode == 2:
... | 3,692 | 38.287234 | 219 | py |
gwsky | gwsky-master/gwsky/utils.py | import numpy as np
import healpy as hp
from scipy.special import sph_harm
from functools import reduce
import quaternionic
import spherical
import matplotlib.pyplot as plt
from healpy.projaxes import HpxMollweideAxes
from typing import Tuple, Optional, List, Dict
from .typing import SHModes, Value
def ra_dec_to_th... | 4,056 | 32.254098 | 100 | py |
wgenpatex | wgenpatex-main/model.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Generator's convolutional blocks 2D
class Conv_block2D(nn.Module):
def __init__(self, n_ch_in, n_ch_out, m=0.1):
... | 3,143 | 33.173913 | 160 | py |
wgenpatex | wgenpatex-main/wgenpatex.py | import torch
from torch import nn
from torch.autograd.variable import Variable
import matplotlib.pyplot as plt
import numpy as np
import math
import time
import model
from os import mkdir
from os.path import isdir
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(DEVICE)
def imread(img_name)... | 14,073 | 34.185 | 157 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.