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 |
|---|---|---|---|---|---|---|
ResiDualGAN-DRDG | ResiDualGAN-DRDG-main/core/datasets/dual_dataset.py | import torch.utils.data as D
import random
from PIL import Image
import numpy as np
class DualDataset(D.Dataset):
def __init__(self, dsa_path, dsb_path, transform_imgs=None, transform_dsms=None, random_seed=666, in_memory=True):
super(DualDataset, self).__init__()
self.dsa_path = dsa_path
... | 4,959 | 31.847682 | 119 | py |
ResiDualGAN-DRDG | ResiDualGAN-DRDG-main/core/utils/utils.py | import numpy as np
from torch import FloatTensor
from torch.autograd import Variable
import torch.autograd as autograd
import torch
import math
import segmentation_models_pytorch as smp
import logging
import sys
import os
import torch.nn as nn
def get_model(model_type, encoder_name="resnet34", encoder_weights="imagene... | 6,272 | 32.725806 | 113 | py |
ResiDualGAN-DRDG | ResiDualGAN-DRDG-main/core/utils/data_display.py | import os
import sys
import PIL
from matplotlib import pyplot as plt
import torch
from torchvision import transforms
from PIL import Image, ImageDraw
import numpy as np
from .utils import *
import albumentations as A
from ..datasets.seg_dataset import SegDataset
import segmentation_models_pytorch as smp
from ..models.r... | 2,955 | 26.37037 | 98 | py |
3D-IWGAN | 3D-IWGAN-master/scripts/global_variables.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import socket
g_render4cnn_root_folder = os.path.dirname(os.path.abspath(__file__))
# ------------------------------------------------------------
# PATHS
# ------------------------------------------------------------
g_blender_executable_path = 'blender' #!! MODIF... | 5,852 | 52.697248 | 149 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/main.py | """
forked from https://github.com/juntang-zhuang/Adabelief-Optimizer/tree/update_0.2.0/PyTorch_Experiments/wgan/main.py
"""
from __future__ import print_function
import argparse
import os
import random
import wandb
import uuid
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as ... | 13,951 | 40.278107 | 199 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/optimizers/set_optim.py | from optimizers import *
import torch.optim as optim
import torch
import sys
import os
from util import build_optimizer, OptimizerSetting
def set_optimizers(optimizer, model, lr, momentum, beta1, beta2, eps, beta_momentum_coeff):
if optimizer == 'adam':
optimizer = optim.Adam(model.parameters(), lr=lr, b... | 3,198 | 37.083333 | 91 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/lr_scheduler.py | from torch.optim import lr_scheduler
import math
# ================
# Set LR Scheduler
# Reference https://github.com/christiancosgrove/pytorch-spectral-normalization-gan/blob/12dcf945a6359301d63d1e0da3708cd0f0590b19/main.py#L55
# ================
def build_scheduler(opt, optimizerD, optimizerG):
if opt.schedul... | 1,690 | 33.510204 | 141 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/set_model.py | import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.utils.data
import torchvision.datasets as dset
import torchvision.transforms as transforms
import torchvision.utils as vutils
import torch.nn.functional as F
def set_models(weights_init, model="GAN", netG_path... | 7,074 | 44.352564 | 118 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/inception.py | """
forked from https://github.com/mseitzer/pytorch-fid/blob/master/inception.py
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
try:
from torchvision.models.utils import load_state_dict_from_url, load_state_dict
except ImportError:
from torch.utils.model_z... | 11,769 | 36.845659 | 82 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/data_utils.py | import torch
import torchvision.datasets as datasets
import torchvision.transforms as transforms
def build_dataset(opt):
if opt.dataset in ['imagenet', 'folder', 'lfw']:
# folder dataset
dataset = datasets.ImageFolder(root=opt.dataroot,
transform=transforms.Compose([... | 2,828 | 41.223881 | 91 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/lib_version.py | import sys
import torch
import torchvision
import numpy as np
import PIL
def print_libs_version():
print("Environment:")
print("\tPython: {}".format(sys.version.split(" ")[0]))
print("\tPyTorch: {}".format(torch.__version__))
print("\tTorchvision: {}".format(torchvision.__version__))
print("\tCUDA:... | 511 | 33.133333 | 63 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/fid_score.py | """
forked from https://github.com/mseitzer/pytorch-fid/blob/master/inception.py
"""
import os
import pathlib
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
import numpy as np
import torch
from scipy import linalg
from torch.nn.functional import adaptive_avg_pool2d
from PIL import Image
try:
... | 7,548 | 35.119617 | 79 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/utils/metric.py | import torch
class TensorMetric(object):
def __init__(self, name):
self.name = name
self.sum = torch.tensor(0.)
self.n = torch.tensor(0.)
def update(self, val):
self.sum += val.detach().cpu()
self.n += 1
@property
def avg(self):
return self.sum / self.n... | 582 | 19.103448 | 38 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/jupyter/toy_example/set_optimizer.py | # coding: utf-8
import attr
import torch.optim as optim
from cg_optimizer import ConjugateGradientOptimizer
@attr.s
class OptimizerSetting:
name = attr.ib()
lr = attr.ib()
weight_decay = attr.ib()
model = attr.ib()
momentum = attr.ib(default=0.9) # sgd, sgd_nesterov
eps = attr.ib(default=0.00... | 2,082 | 35.54386 | 153 | py |
ConjugateGradient_GAN | ConjugateGradient_GAN-master/jupyter/toy_example/cg_optimizer.py | """ Conjugate Gradient method in PyTorch! """
import torch
from torch.optim.optimizer import Optimizer, required
class ConjugateGradientOptimizer(Optimizer):
"""
Conjugate Gradient method
Notation:
d_buffer: update vector
alpha_buffer: alpha
beta_buffer: beta
"""
def ... | 6,671 | 39.436364 | 141 | py |
spektral | spektral-master/spektral/models/gnn_explainer.py | import networkx as nx
import numpy as np
import tensorflow as tf
from scipy.sparse import csr_matrix
from spektral.layers import MessagePassing
from spektral.layers.convolutional.conv import Conv
from spektral.layers.ops import dot
from spektral.utils.sparse import sp_matrix_to_sp_tensor
class GNNExplainer:
"""
... | 13,348 | 34.981132 | 109 | py |
spektral | spektral-master/spektral/models/general_gnn.py | from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import (
Activation,
Add,
BatchNormalization,
Concatenate,
Dense,
Dropout,
PReLU,
)
from spektral.layers import GeneralConv
from spektral.layers.pooling import global_pool
def get_act(identifier):
if identifie... | 6,997 | 29.426087 | 85 | py |
spektral | spektral-master/spektral/models/gcn.py | import tensorflow as tf
from spektral.layers.convolutional import gcn_conv
class GCN(tf.keras.Model):
"""
This model, with its default hyperparameters, implements the architecture
from the paper:
> [Semi-Supervised Classification with Graph Convolutional Networks](https://arxiv.org/abs/1609.02907)<b... | 2,705 | 29.75 | 110 | py |
spektral | spektral-master/spektral/datasets/qm9.py | import os
import os.path as osp
import numpy as np
from joblib import Parallel, delayed
from tensorflow.keras.utils import get_file
from tqdm import tqdm
from spektral.data import Dataset, Graph
from spektral.utils import label_to_one_hot, sparse
from spektral.utils.io import load_csv, load_sdf
ATOM_TYPES = [1, 6, 7... | 3,361 | 28.491228 | 80 | py |
spektral | spektral-master/spektral/datasets/qm7.py | import os.path as osp
import numpy as np
import scipy.sparse as sp
from scipy.io import loadmat
from tensorflow.keras.utils import get_file
from spektral.data import Dataset, Graph
from spektral.utils import sparse
class QM7(Dataset):
"""
The QM7b dataset of molecules from the paper:
> [MoleculeNet: A ... | 1,562 | 25.948276 | 101 | py |
spektral | spektral-master/spektral/datasets/mnist.py | import numpy as np
import scipy.sparse as sp
from sklearn.neighbors import kneighbors_graph
from tensorflow.keras.datasets import mnist as m
from spektral.data import Dataset, Graph
MNIST_SIZE = 28
class MNIST(Dataset):
"""
The MNIST images used as node features for a grid graph, as described by
[Deffer... | 3,018 | 28.598039 | 80 | py |
spektral | spektral-master/spektral/layers/base.py | import numpy as np
import tensorflow as tf
from tensorflow.keras import activations
from tensorflow.keras import backend as K
from tensorflow.keras import constraints, initializers, regularizers
from tensorflow.keras.layers import Layer
from tensorflow.python.framework import smart_cond
from spektral.layers import ops... | 8,948 | 31.075269 | 88 | py |
spektral | spektral-master/spektral/layers/pooling/global_pool.py | import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras import constraints, initializers, regularizers
from tensorflow.keras.layers import Dense, Layer
from spektral.layers import ops
class GlobalPool(Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs)
... | 14,218 | 29.91087 | 93 | py |
spektral | spektral-master/spektral/layers/pooling/asym_cheeger_cut_pool.py | import tensorflow as tf
import tensorflow.keras.backend as K
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class AsymCheegerCutPool(SRCPool):
r"""
An Asymmetric Cheeger Cut Pooling layer from t... | 8,006 | 32.642857 | 128 | py |
spektral | spektral-master/spektral/layers/pooling/dmon_pool.py | import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class DMoNPool(SRCPool):
r"""
The DMoN pooling layer from the paper
> [Graph... | 6,994 | 32.151659 | 104 | py |
spektral | spektral-master/spektral/layers/pooling/diff_pool.py | import tensorflow as tf
from tensorflow.keras import activations
from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class DiffPool(SRCPool):
r"""
A DiffPool layer from the paper
> [Hierarchical Graph Representation Learning with Diff... | 5,706 | 30.357143 | 116 | py |
spektral | spektral-master/spektral/layers/pooling/sag_pool.py | import tensorflow as tf
from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.pooling.topk_pool import TopKPool
class SAGPool(TopKPool):
r"""
A self-attention graph pooling layer from the paper
> [Self-Attention Graph Pooling](https://arxiv.org/abs/1904.08082)<br... | 3,287 | 31.554455 | 88 | py |
spektral | spektral-master/spektral/layers/pooling/topk_pool.py | import tensorflow as tf
from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class TopKPool(SRCPool):
r"""
A gPool/Top-K layer from the papers
> [Graph U-Nets](https://arxiv.org/abs/1905.05178)<br>
> Hongyang Gao and Shuiwang Ji
... | 6,197 | 32.868852 | 92 | py |
spektral | spektral-master/spektral/layers/pooling/la_pool.py | import tensorflow as tf
from scipy import sparse
from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class LaPool(SRCPool):
r"""
A Laplacian pooling (LaPool) layer from the paper
> [Towards Interpretable Sparse Graph Representation Le... | 6,279 | 32.404255 | 127 | py |
spektral | spektral-master/spektral/layers/pooling/mincut_pool.py | import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class MinCutPool(SRCPool):
r"""
A MinCut pooling layer from the paper
> [Spe... | 6,106 | 31.142105 | 110 | py |
spektral | spektral-master/spektral/layers/pooling/just_balance_pool.py | import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from spektral.layers import ops
from spektral.layers.pooling.src import SRCPool
class JustBalancePool(SRCPool):
r"""
The Just Balance pooling layer from the pape... | 5,777 | 31.829545 | 95 | py |
spektral | spektral-master/spektral/layers/pooling/src.py | import inspect
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from spektral.utils.keras import (
deserialize_kwarg,
is_keras_kwarg,
is_layer_kwarg,
serialize_kwarg,
)
class SRCPool(Layer):
r"""
A general class for graph pooling lay... | 12,671 | 39.101266 | 112 | py |
spektral | spektral-master/spektral/layers/convolutional/diffusion_conv.py | import tensorflow as tf
import tensorflow.keras.layers as layers
from spektral.layers.convolutional.conv import Conv
from spektral.utils import normalized_adjacency
class DiffuseFeatures(layers.Layer):
r"""
Utility layer calculating a single channel of the diffusional convolution.
The procedure is based... | 5,944 | 31.664835 | 98 | py |
spektral | spektral-master/spektral/layers/convolutional/xenet_conv.py | from collections.abc import Iterable
import tensorflow as tf
from tensorflow.keras.layers import Concatenate, Dense, Multiply, PReLU, ReLU
from tensorflow.python.ops import gen_sparse_ops
from spektral.layers.convolutional.conv import Conv
from spektral.layers.convolutional.message_passing import MessagePassing
cla... | 13,762 | 36.603825 | 178 | py |
spektral | spektral-master/spektral/layers/convolutional/cheb_conv.py | from tensorflow.keras import backend as KB
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.utils import normalized_laplacian, rescale_laplacian
class ChebConv(Conv):
r"""
A Chebyshev convolutional layer from the paper
> [Convolutional Neural Networks on ... | 4,462 | 29.993056 | 91 | py |
spektral | spektral-master/spektral/layers/convolutional/appnp_conv.py | from tensorflow.keras import activations
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.models import Sequential
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.utils import gcn_filter
class APPNPConv(Conv):
r"""
The APPNP operator f... | 5,098 | 33.452703 | 118 | py |
spektral | spektral-master/spektral/layers/convolutional/agnn_conv.py | import tensorflow as tf
from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.convolutional.message_passing import MessagePassing
class AGNNConv(MessagePassing):
r"""
An Attention-based Graph Neural Network (AGNN) from the paper
> [Attention-based Graph Neural Ne... | 2,666 | 28.633333 | 111 | py |
spektral | spektral-master/spektral/layers/convolutional/arma_conv.py | from tensorflow.keras import activations
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dropout
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.utils import normalized_adjacency
class ARMAConv(Conv):
r"""
An Auto-Regressive Movi... | 8,048 | 34.148472 | 99 | py |
spektral | spektral-master/spektral/layers/convolutional/general_conv.py | import tensorflow as tf
from tensorflow.keras import activations
from tensorflow.keras.layers import BatchNormalization, Dropout, PReLU
from spektral.layers.convolutional.message_passing import MessagePassing
class GeneralConv(MessagePassing):
r"""
A general convolutional layer from the paper
> [Design ... | 5,435 | 32.975 | 84 | py |
spektral | spektral-master/spektral/layers/convolutional/gin_conv.py | import tensorflow as tf
from tensorflow.keras import activations
from tensorflow.keras.layers import BatchNormalization, Dense
from tensorflow.keras.models import Sequential
from spektral.layers import ops
from spektral.layers.convolutional.message_passing import MessagePassing
class GINConv(MessagePassing):
r""... | 5,345 | 32.4125 | 86 | py |
spektral | spektral-master/spektral/layers/convolutional/graphsage_conv.py | from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.convolutional.message_passing import MessagePassing
class GraphSageConv(MessagePassing):
r"""
A GraphSAGE layer from the paper
> [Inductive Representation Learning on Large Graphs](https://arxiv.org/abs/1706.0... | 3,941 | 31.04878 | 95 | py |
spektral | spektral-master/spektral/layers/convolutional/edge_conv.py | from tensorflow.keras import activations
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Sequential
from spektral.layers.convolutional.message_passing import MessagePassing
class EdgeConv(MessagePassing):
r"""
An edge convolutional layer... | 4,206 | 31.612403 | 92 | py |
spektral | spektral-master/spektral/layers/convolutional/gated_graph_conv.py | import tensorflow as tf
from tensorflow.keras.layers import GRUCell
from spektral.layers.convolutional.message_passing import MessagePassing
class GatedGraphConv(MessagePassing):
r"""
A gated graph convolutional layer from the paper
> [Gated Graph Sequence Neural Networks](https://arxiv.org/abs/1511.054... | 4,254 | 32.242188 | 82 | py |
spektral | spektral-master/spektral/layers/convolutional/ecc_conv.py | import warnings
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.layers.ops import modes
class ECCConv(Conv):
r"""
An edge-conditioned convolutional ... | 6,994 | 34.871795 | 82 | py |
spektral | spektral-master/spektral/layers/convolutional/gcn_conv.py | from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.utils import gcn_filter
class GCNConv(Conv):
r"""
A graph convolutional layer (GCN) from the paper
> [Semi-Supervised Classification with Graph Convolutional Networ... | 3,695 | 30.322034 | 110 | py |
spektral | spektral-master/spektral/layers/convolutional/gtv_conv.py | import tensorflow as tf
from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
class GTVConv(Conv):
r"""
A graph total variation convolutional layer (GTVConv) from the paper
> [Total Variation Graph Neural Networks](https://arxiv.org... | 6,767 | 30.774648 | 121 | py |
spektral | spektral-master/spektral/layers/convolutional/gcs_conv.py | from tensorflow.keras import backend as K
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.utils import normalized_adjacency
class GCSConv(Conv):
r"""
A `GraphConv` layer with a trainable skip connection.
**Mode**: single, disjoint, mixed, batch.
Thi... | 3,852 | 29.824 | 89 | py |
spektral | spektral-master/spektral/layers/convolutional/crystal_conv.py | from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from spektral.layers.convolutional.message_passing import MessagePassing
class CrystalConv(MessagePassing):
r"""
A crystal graph convolutional layer from the paper
> [Crystal Graph Convolutional Neural Networks for an Ac... | 3,725 | 32.567568 | 90 | py |
spektral | spektral-master/spektral/layers/convolutional/censnet_conv.py | import tensorflow as tf
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.utils.convolution import gcn_filter, incidence_matrix, line_graph
class CensNetConv(Conv):
r"""
A CensNet convolutional layer from the paper
> [Co-embedding of Nodes and Edges with G... | 10,489 | 39.346154 | 104 | py |
spektral | spektral-master/spektral/layers/convolutional/conv.py | import warnings
from functools import wraps
import tensorflow as tf
from tensorflow.keras.layers import Layer
from spektral.utils.keras import (
deserialize_kwarg,
is_keras_kwarg,
is_layer_kwarg,
serialize_kwarg,
)
class Conv(Layer):
r"""
A general class for convolutional layers.
You ca... | 2,918 | 26.280374 | 86 | py |
spektral | spektral-master/spektral/layers/convolutional/tag_conv.py | from tensorflow.keras import backend as K
from tensorflow.keras.layers import Dense
from spektral.layers.convolutional.message_passing import MessagePassing
from spektral.utils import normalized_adjacency
class TAGConv(MessagePassing):
r"""
A Topology Adaptive Graph Convolutional layer (TAG) from the paper
... | 3,772 | 29.92623 | 92 | py |
spektral | spektral-master/spektral/layers/convolutional/message_passing.py | import inspect
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from spektral.layers.ops.scatter import deserialize_scatter, serialize_scatter
from spektral.utils.keras import (
deserialize_kwarg,
is_keras_kwarg,
is_layer_kwarg,
serialize_kwar... | 7,175 | 34.176471 | 90 | py |
spektral | spektral-master/spektral/layers/convolutional/gat_conv.py | import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.keras import constraints, initializers, regularizers
from tensorflow.keras.layers import Dropout
from spektral.layers import ops
from spektral.layers.convolutional.conv import Conv
from spektral.layers.ops import modes
class GATConv(Co... | 10,279 | 36.933579 | 85 | py |
spektral | spektral-master/spektral/layers/ops/modes.py | import tensorflow as tf
from tensorflow.keras import backend as K
SINGLE = 1 # Single mode rank(x) = 2, rank(a) = 2
DISJOINT = SINGLE # Disjoint mode rank(x) = 2, rank(a) = 2
BATCH = 3 # Batch mode rank(x) = 3, rank(a) = 3
MIXED = 4 # Mixed mode rank(x) = 3, rank(a) = 2
def disjoint_signal_to_batch(X... | 3,567 | 32.345794 | 89 | py |
spektral | spektral-master/spektral/layers/ops/graph.py | import tensorflow as tf
from tensorflow.keras import backend as K
from . import ops
def normalize_A(A):
"""
Computes symmetric normalization of A, dealing with sparse A and batch mode
automatically.
:param A: Tensor or SparseTensor with rank k = {2, 3}.
:return: Tensor or SparseTensor of rank k.
... | 2,116 | 29.242857 | 82 | py |
spektral | spektral-master/spektral/layers/ops/matmul.py | import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow.python.ops.linalg.sparse import sparse as tfsp
from . import ops
def dot(a, b):
"""
Computes a @ b, for a, b of the same rank (both 2 or both 3).
If the rank is 2, then the innermost dimension of `a` must match the
out... | 6,354 | 33.726776 | 81 | py |
spektral | spektral-master/spektral/layers/ops/ops.py | import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
def transpose(a, perm=None, name=None):
"""
Transposes a according to perm, dealing automatically with sparsity.
:param a: Tensor or SparseTensor with rank k.
:param perm: permutation indices of size k.
:param nam... | 3,729 | 34.52381 | 78 | py |
spektral | spektral-master/spektral/utils/keras.py | from tensorflow.keras import activations, constraints, initializers, regularizers
LAYER_KWARGS = {"activation", "use_bias"}
KERAS_KWARGS = {
"trainable",
"name",
"dtype",
"dynamic",
"input_dim",
"input_shape",
"batch_input_shape",
"batch_size",
"weights",
"activity_regularizer",... | 1,372 | 23.517857 | 81 | py |
spektral | spektral-master/examples/other/explain_graph_predictions.py | import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.metrics import categorical_accuracy
from tensorflow.keras.optimizers import Adam
from spektral.data import DisjointLoader
from spektral.datasets import TUDataset
... | 2,857 | 29.084211 | 86 | py |
spektral | spektral-master/examples/other/explain_node_predictions.py | import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.optimizers import Adam
from spektral.data.loaders import SingleLoader
from spektral.datasets.citation import ... | 2,137 | 28.694444 | 81 | py |
spektral | spektral-master/examples/other/node_clustering_mincut.py | """
This example implements the experiments for node clustering on citation networks
from the paper:
Mincut pooling in Graph Neural Networks (https://arxiv.org/abs/1907.00481)
Filippo Maria Bianchi, Daniele Grattarola, Cesare Alippi
"""
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from s... | 3,447 | 30.345455 | 85 | py |
spektral | spektral-master/examples/other/graph_signal_classification_mnist.py | import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import SparseCategoricalCrossentropy
from tensorflow.keras.metrics import sparse_categorical_accuracy
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.re... | 4,254 | 30.058394 | 81 | py |
spektral | spektral-master/examples/other/node_clustering_tvgnn.py | """
This example implements the node clustering experiment on citation networks
from the paper:
Total Variation Graph Neural Networks (https://arxiv.org/abs/2211.06218)
Jonas Berg Hansen and Filippo Maria Bianchi
"""
import numpy as np
import tensorflow as tf
from sklearn.metrics.cluster import (
completeness_sco... | 3,374 | 23.816176 | 85 | py |
spektral | spektral-master/examples/graph_prediction/ogbg-mol-hiv_ecc.py | """
This example shows how to perform molecule classification with the
[Open Graph Benchmark](https://ogb.stanford.edu) `mol-hiv` dataset, using a
simple ECC-based GNN in disjoint mode. The model does not perform really well
but should give you a starting point if you want to implement a more
sophisticated one.
"""
im... | 3,971 | 34.783784 | 86 | py |
spektral | spektral-master/examples/graph_prediction/qm9_ecc_batch.py | """
This example shows how to perform regression of molecular properties with the
QM9 database, using a GNN based on edge-conditioned convolutions in batch mode.
"""
import numpy as np
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from... | 2,883 | 35.506329 | 85 | py |
spektral | spektral-master/examples/graph_prediction/custom_dataset.py | """
This example shows how to define your own dataset and use it to train a
non-trivial GNN with message-passing and pooling layers.
The script also shows how to implement fast training and evaluation functions
in disjoint mode, with early stopping and accuracy monitoring.
The dataset that we create is a simple synthe... | 6,894 | 33.133663 | 94 | py |
spektral | spektral-master/examples/graph_prediction/tud_mincut.py | import numpy as np
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import Dense
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from spektral.data import BatchLoader
from spektral.datasets import TUDataset
from spektral.layers import GCSConv, Glo... | 3,272 | 35.775281 | 80 | py |
spektral | spektral-master/examples/graph_prediction/general_gnn.py | """
This example implements the model from the paper
> [Design Space for Graph Neural Networks](https://arxiv.org/abs/2011.08843)<br>
> Jiaxuan You, Rex Ying, Jure Leskovec
using the PROTEINS dataset.
The configuration at the top of the file is the best one identified in the
paper, and should work well for m... | 3,934 | 34.133929 | 96 | py |
spektral | spektral-master/examples/graph_prediction/tud_gin.py | """
This example shows how to perform graph classification with a simple Graph
Isomorphism Network.
"""
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.losses import CategoricalCrossentropy
from tensorflow.keras.metrics import categorical_accuracy
fro... | 4,168 | 33.741667 | 86 | py |
spektral | spektral-master/examples/graph_prediction/qm9_ecc.py | """
This example shows how to perform regression of molecular properties with the
QM9 database, using a simple GNN in disjoint mode.
"""
import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense
from tensorflow.keras.losses import MeanSquaredError
from tens... | 3,524 | 33.223301 | 86 | py |
spektral | spektral-master/examples/node_prediction/citation_gat_custom.py | """
This script is an extension of the citation_gcn_custom.py script.
It shows how to train GAT (with the same experimental setting of the original
paper), using faster training and test functions.
"""
import tensorflow as tf
from tensorflow.keras.layers import Dropout, Input
from tensorflow.keras.losses import Catego... | 3,234 | 28.144144 | 88 | py |
spektral | spektral-master/examples/node_prediction/citation_gcn.py | """
This example implements the experiments on citation networks from the paper:
Semi-Supervised Classification with Graph Convolutional Networks (https://arxiv.org/abs/1609.02907)
Thomas N. Kipf, Max Welling
"""
import numpy as np
import tensorflow as tf
from tensorflow.keras.callbacks import EarlyStopping
from tenso... | 2,097 | 30.313433 | 99 | py |
spektral | spektral-master/examples/node_prediction/citation_cheby.py | """
This example implements the experiments on citation networks from the paper:
Semi-Supervised Classification with Graph Convolutional Networks (https://arxiv.org/abs/1609.02907)
Thomas N. Kipf, Max Welling
using the convolutional layers described in:
Convolutional Neural Networks on Graphs with Fast Localized Spe... | 3,207 | 33.494624 | 113 | py |
spektral | spektral-master/examples/node_prediction/citation_arma.py | """
This example implements the experiments on citation networks from the paper:
Graph Neural Networks with convolutional ARMA filters (https://arxiv.org/abs/1901.01343)
Filippo Maria Bianchi, Daniele Grattarola, Cesare Alippi, Lorenzo Livi
"""
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.kera... | 3,057 | 32.604396 | 88 | py |
spektral | spektral-master/examples/node_prediction/citation_gcn_custom.py | """
This script is a proof of concept to train GCN as fast as possible and with as
little lines of code as possible.
It uses a custom training function instead of the standard Keras fit(), and
can train GCN for 200 epochs in a few tenths of a second (~0.20 on a GTX 1050).
"""
import tensorflow as tf
from tensorflow.ker... | 1,637 | 32.428571 | 88 | py |
spektral | spektral-master/examples/node_prediction/citation_simple_gc.py | """
This example implements the experiments on citation networks from the paper:
Simplifying Graph Convolutional Networks (https://arxiv.org/abs/1902.07153)
Felix Wu, Tianyi Zhang, Amauri Holanda de Souza Jr., Christopher Fifty, Tao Yu, Kilian Q. Weinberger
To implement it, we define a custom transform for the adjace... | 2,774 | 31.267442 | 100 | py |
spektral | spektral-master/examples/node_prediction/ogbn-arxiv_gcn.py | """
This example implements the same GCN example for node classification provided
with the [Open Graph Benchmark](https://ogb.stanford.edu).
See https://github.com/snap-stanford/ogb/blob/master/examples/nodeproppred/arxiv/gnn.py
for the reference implementation.
"""
import numpy as np
import tensorflow as tf
from ogb.n... | 3,535 | 33 | 87 | py |
spektral | spektral-master/examples/node_prediction/citation_gat.py | """
This example implements the experiments on citation networks from the paper:
Graph Attention Networks (https://arxiv.org/abs/1710.10903)
Petar Veličković, Guillem Cucurull, Arantxa Casanova, Adriana Romero, Pietro Liò, Yoshua Bengio
"""
import numpy as np
from tensorflow.keras.callbacks import EarlyStopping
from t... | 3,212 | 30.194175 | 95 | py |
spektral | spektral-master/tests/test_layers/pooling/core.py | import numpy as np
import scipy.sparse as sp
import tensorflow as tf
from tensorflow.keras import Input, Model
from spektral.utils.sparse import sp_matrix_to_sp_tensor
from tests.test_layers.convolutional.core import _test_get_config
tf.keras.backend.set_floatx("float64")
MODES = {
"SINGLE": 0,
"BATCH": 1,
... | 5,234 | 29.086207 | 85 | py |
spektral | spektral-master/tests/test_layers/pooling/test_global_pooling.py | import numpy as np
import tensorflow as tf
from tensorflow.keras import Input, Model
from spektral.layers import (
GlobalAttentionPool,
GlobalAttnSumPool,
GlobalAvgPool,
GlobalMaxPool,
GlobalSumPool,
SortPool,
)
from tests.test_layers.convolutional.core import _test_get_config
tf.keras.backend... | 4,319 | 30.304348 | 87 | py |
spektral | spektral-master/tests/test_layers/convolutional/test_censnet_conv.py | import enum
import networkx as nx
import numpy as np
import pytest
from core import A, F, S, batch_size
from tensorflow.keras import Input, Model
from spektral.layers import CensNetConv
NODE_CHANNELS = 8
"""
Number of node output channels to use for testing.
"""
EDGE_CHANNELS = 10
"""
Number of edge output channels ... | 6,138 | 30.64433 | 83 | py |
spektral | spektral-master/tests/test_layers/convolutional/core.py | import itertools
import numpy as np
import tensorflow as tf
from tensorflow.keras import Input, Model
from spektral.utils.sparse import sp_matrix_to_sp_tensor
tf.keras.backend.set_floatx("float64")
MODES = {
"SINGLE": 0,
"BATCH": 1,
"MIXED": 2,
}
batch_size = 32
N = 11
F = 7
S = 3
A = np.ones((N, N))
X ... | 7,676 | 28.413793 | 87 | py |
spektral | spektral-master/tests/test_layers/convolutional/test_xenet_conv.py | import numpy as np
from tensorflow.keras.layers import Input
from tensorflow.keras.models import Model
from spektral.layers import XENetConv, XENetConvBatch
from spektral.utils.sparse import sp_matrix_to_sp_tensor
# Not using these tests because they assume certain behaviors that we
# don't follow
"""
dense_config = ... | 6,662 | 32.822335 | 124 | py |
spektral | spektral-master/tests/test_models/core.py | import numpy as np
import scipy.sparse as sp
import tensorflow as tf
from spektral.data import Dataset, Graph, loaders
tf.keras.backend.set_floatx("float64")
MODES = {"SINGLE": 0, "BATCH": 1, "MIXED": 2, "DISJOINT": 3}
batch_size = 16
n_nodes = 11
n_node_features = 7
n_edge_features = 3
def _get_graph(n_nodes, n_f... | 6,747 | 28.858407 | 87 | py |
NLI4CT | NLI4CT-main/pipeline/task1_entailment.py | import torch
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from transformers import Trainer, TrainingArguments
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from prepare_data import generate_nli_data
TRAIN_PATH = "data/train.json"
DEV_PATH = "data/dev... | 4,407 | 39.814815 | 97 | py |
NLI4CT | NLI4CT-main/pipeline/task2_evidence.py | import torch
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score
from transformers import Trainer, TrainingArguments
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from prepare_data import generate_evidence_data
TRAIN_PATH = "data/train.json"
DEV_PATH = "dat... | 4,437 | 40.092593 | 97 | py |
NLI4CT | NLI4CT-main/joint/main.py | import torch
import torch.nn as nn
from sklearn.metrics import f1_score, precision_score, recall_score
from tqdm import tqdm
from torch.utils.data import DataLoader
from transformers import AutoModel, AutoTokenizer, get_cosine_schedule_with_warmup, AdamW
from model import ModelForSequenceClassification
from prepare_j... | 11,141 | 39.369565 | 142 | py |
NLI4CT | NLI4CT-main/joint/prepare_joint.py | import json
import pandas as pd
TRAIN_DATA = "data/train.json"
def generate_multi_data(file_path):
df = pd.read_json(file_path)
df = df.transpose()
#Extract the claims and NLI labels (Entailment/Contradiction).
claims = df.Statement.tolist()
nli_labels = df.Label.tolist()
primary_indices = ... | 3,410 | 36.076087 | 94 | py |
NLI4CT | NLI4CT-main/joint/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
class ClassificationHead(nn.Module):
"""Head for sentence-level classification tasks."""
def __init__(self, hidden_dim, n_labels, hidden_dropout_prob = 0.1):
super().__init__()
self.dense = nn.Linear(hidden_dim, hidden_dim)
... | 9,675 | 42.390135 | 136 | py |
lm-evaluation-harness | lm-evaluation-harness-master/setup.py | from setuptools import setup, find_packages
from setuptools.command.install import install
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
dev_requires = (["black<=21.12b0", "coverage<=6.2", "mock>=4.0.3", "pytest"],)
install_requires = [
"datasets>=2.0.0",
"codecarbon"... | 1,863 | 27.676923 | 90 | py |
lm-evaluation-harness | lm-evaluation-harness-master/scripts/make_gpt2_test_cases.py | import transformers
import torch
import torch.nn.functional as F
import random
from lm_eval.api.utils import set_seed
data = [
"A multilayer perceptron (MLP) is a class of feedforward artificial neural network (ANN)",
"The term MLP is used ambiguously, sometimes loosely to any feedforward ANN, sometimes stri... | 3,587 | 78.733333 | 1,100 | py |
lm-evaluation-harness | lm-evaluation-harness-master/tests/test_models_huggingface.py | import unittest.mock as mock
import logging
import pytest
import lm_eval.models
from lm_eval.api.utils import set_seed
logger = logging.getLogger(__name__)
# Only use cpu to avoid non-deterministic CUDA settings.
# See: https://pytorch.org/docs/stable/notes/randomness.html
_DEVICE = "cpu"
@pytest.mark.parametriz... | 14,178 | 42.360856 | 1,045 | py |
lm-evaluation-harness | lm-evaluation-harness-master/tests/test_utils.py | import torch
from lm_eval.api.utils import (
get_rolling_token_windows,
make_disjoint_window,
select_continuation_from_batch_left_padding,
split_and_pad_windows,
)
# noinspection DuplicatedCode
def test_get_rolling_token_windows_v1():
gold = [
([-100, 0, 1, 2, 3, 4, 5, 6, 7, 8], [0, 1, 2,... | 9,180 | 31.101399 | 87 | py |
lm-evaluation-harness | lm-evaluation-harness-master/lm_eval/api/utils.py | import collections
import pathlib
import re
import sys
import torch
from typing import Callable, Final, Iterable, List, Optional, Tuple, Union
from collections.abc import MutableMapping
from transformers import set_seed as transformers_set_seed
# General Utils
class ExitCodeError(Exception):
pass
# Reproducib... | 10,944 | 29.572626 | 116 | py |
lm-evaluation-harness | lm-evaluation-harness-master/lm_eval/api/model.py | import abc
import hashlib
import json
import os
import torch
import torch.nn.functional as F
from tqdm import tqdm
from typing import Iterable, List, Optional, Tuple, Union
from transformers import BatchEncoding
from lm_eval.api import utils
class LM(abc.ABC):
def __init__(self):
self.cache_hook = CacheH... | 17,599 | 37.681319 | 119 | py |
lm-evaluation-harness | lm-evaluation-harness-master/lm_eval/models/huggingface.py | import math
import torch
import torch.nn.functional as F
import transformers
from typing import List, Mapping, NewType, Optional, Tuple, Union
from tqdm import tqdm
from lm_eval.api import utils
from lm_eval.api.model import TokenLM, TokenSequence
_DeviceMapping = NewType("DeviceMapping", Mapping[str, Union[int, str... | 26,068 | 39.860502 | 120 | py |
GradAug | GradAug-main/train_cifar.py | import os
import shutil
import time
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from models.wideresnet_ran... | 11,920 | 37.33119 | 131 | py |
GradAug | GradAug-main/train.py | import os
import shutil
import time
import importlib
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.nn.functional as F
import torch.optim
import torch.utils.data
import torch.utils.data.distributed
import torchvision.transforms as transforms
import torchvi... | 10,863 | 33.820513 | 125 | py |
GradAug | GradAug-main/models/randwidth_ops.py | # These operations are based on the implementation of https://github.com/JiahuiYu/slimmable_networks
import torch.nn as nn
from utils.config import FLAGS
def make_divisible(v, divisor=1, min_value=1):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * d... | 5,110 | 34.992958 | 100 | py |
GradAug | GradAug-main/models/resnet_randwidth.py | import torch.nn as nn
import math
from models.randwidth_ops import RWConv2d, RWLinear, RWBatchNorm2d, make_divisible
from utils.config import FLAGS
class Block(nn.Module):
def __init__(self, inp, outp, stride, tmp_ratio=1.0):
super(Block, self).__init__()
assert stride in [1, 2]
# midp =... | 4,581 | 33.451128 | 95 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.