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 |
|---|---|---|---|---|---|---|
HGB | HGB-master/NC/benchmark/methods/GNN/run.py | import sys
sys.path.append('../../')
import time
import argparse
import torch
import torch.nn.functional as F
import numpy as np
from utils.pytorchtools import EarlyStopping
from utils.data import load_data
#from utils.tools import index_generator, evaluate_results_nc, parse_minibatch
from GNN import GCN, GAT
import ... | 7,346 | 41.964912 | 158 | py |
HGB | HGB-master/NC/benchmark/methods/GNN/run_multi.py | import sys
sys.path.append('../../')
import time
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from utils.pytorchtools import EarlyStopping
from utils.data import load_data
#from utils.tools import index_generator, evaluate_results_nc, parse_minibatch
from GNN i... | 7,187 | 41.282353 | 158 | py |
HGB | HGB-master/NC/benchmark/methods/GNN/utils/pytorchtools.py | import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience, verbose=False, delta=0, save_path='checkpoint.pt'):
"""
Args:
patience (int): How long to wait after last time... | 1,824 | 36.244898 | 111 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/RSHN.py | import argparse
from scipy.sparse import coo, find
from torch_geometric.data import Data
from build_coarsened_line_graph import relation_graph
from torch_geometric.utils import remove_self_loops
from torch_geometric.nn import NNConv, RelationConv
from torch_geometric.datasets import Entities
from torch.nn import Sequen... | 12,024 | 32.968927 | 157 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/build_coarsened_line_graph/utils.py | from tokenize import Comment
import scipy.sparse as sp
import numpy as np
from numba import jit
import torch
import random
random.seed(1233)
def score_matrix_from_random_walks(random_walks, N, symmetric=True):
"""
Compute the transition scores, i.e. how often a transition occurs, for all node pairs from
... | 5,434 | 30.970588 | 114 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/build_coarsened_line_graph/relation_graph.py | from build_coarsened_line_graph import utils
import numpy as np
import scipy.sparse as sp
from torch_geometric.data import Data
import torch
def build_relation_adj(org_graph, num_relations, rw_len=3, batch_size=3):
'''build a AIFB-relation graph adjacency based on random walk from the original graph'''
# grap... | 3,066 | 39.893333 | 96 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/nn/conv/nn_conv.py | import torch
from torch.nn import Parameter
from torch_geometric.nn.conv import MessagePassing
from ..inits import reset, uniform
class NNConv(MessagePassing):
def __init__(self,
in_channels,
out_channels,
nn,
aggr="add",
root_w... | 1,903 | 28.75 | 82 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/nn/conv/relation_conv.py | import torch
from torch.nn import Parameter
import torch.nn.functional as F
from torch_sparse import spmm
from torch_geometric.utils import remove_self_loops, add_self_loops, softmax, add_self_edge_attr_loops
class RelationConv(torch.nn.Module):
def __init__(self, eps=0, train_eps=False, requires_grad=True):
... | 1,967 | 30.741935 | 102 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/nn/conv/message_passing.py | import inspect
import torch
from torch_geometric.utils import scatter_
class MessagePassing(torch.nn.Module):
def __init__(self, aggr='add'):
super(MessagePassing, self).__init__()
self.message_args = inspect.getargspec(self.message)[0][1:]
self.update_args = inspect.getargspec(self.upda... | 1,335 | 28.688889 | 67 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/datasets/entities.py | import os
from collections import Counter
import gzip
import rdflib as rdf
import pandas as pd
import numpy as np
import torch
from torch_scatter import scatter_add
from torch_geometric.data import (InMemoryDataset, Data, download_url,
extract_tar)
from torch_geometric.utils import o... | 6,012 | 36.58125 | 78 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/softmax.py | from torch_scatter import scatter_max, scatter_add
from .num_nodes import maybe_num_nodes
def softmax(src, index, num_nodes=None):
r"""Sparse softmax of all values from the :attr:`src` tensor at the indices
specified in the :attr:`index` tensor along the first dimension.
Args:
src (Tensor): The ... | 1,162 | 29.605263 | 79 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/one_hot.py | import torch
from .repeat import repeat
def one_hot(src, num_classes=None, dtype=None):
src = src.to(torch.long)
src = src.unsqueeze(-1) if src.dim() == 1 else src
assert src.dim() == 2
if num_classes is None:
num_classes = src.max(dim=0)[0] + 1
else:
num_classes = torch.tensor(
... | 730 | 26.074074 | 72 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/undirected.py | import torch
from torch_sparse import coalesce
from .num_nodes import maybe_num_nodes
def is_undirected(edge_index, num_nodes=None):
num_nodes = maybe_num_nodes(edge_index, num_nodes)
edge_index, _ = coalesce(edge_index, None, num_nodes, num_nodes)
undirected_edge_index = to_undirected(edge_index, num_no... | 743 | 31.347826 | 74 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/to_batch.py | import torch
from torch_scatter import scatter_add
def to_batch(x, batch, fill_value=0):
num_nodes = scatter_add(batch.new_ones(x.size(0)), batch, dim=0)
batch_size, max_num_nodes = num_nodes.size(0), num_nodes.max().item()
cum_nodes = torch.cat([batch.new_zeros(1), num_nodes.cumsum(dim=0)], dim=0)
i... | 707 | 34.4 | 79 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/loop.py | import torch
from .num_nodes import maybe_num_nodes
def contains_self_loops(edge_index):
row, col = edge_index
mask = row == col
return mask.sum().item() > 0
def remove_self_loops(edge_index, edge_attr=None):
row, col = edge_index
mask = row != col
edge_attr = edge_attr if edge_attr is None... | 1,066 | 27.837838 | 67 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/isolated.py | import torch
from .num_nodes import maybe_num_nodes
from .loop import remove_self_loops
def contains_isolated_nodes(edge_index, num_nodes=None):
num_nodes = maybe_num_nodes(edge_index, num_nodes)
(row, _), _ = remove_self_loops(edge_index)
return torch.unique(row).size(0) < num_nodes
| 300 | 26.363636 | 56 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/sparse.py | import torch
from torch_sparse import coalesce
from .num_nodes import maybe_num_nodes
def dense_to_sparse(tensor):
index = tensor.nonzero().t().contiguous()
value = tensor[index[0], index[1]]
index, value = coalesce(index, value, tensor.size(0), tensor.size(1))
return index, value
def sparse_to_den... | 514 | 26.105263 | 76 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/scatter.py | import torch_scatter
def scatter_(name, src, index, dim_size=None):
r"""Aggregates all values from the :attr:`src` tensor at the indices
specified in the :attr:`index` tensor along the first dimension.
If multiple indices reference the same location, their contributions
are aggregated according to :at... | 1,467 | 30.234043 | 78 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/degree.py | import torch
from .num_nodes import maybe_num_nodes
def degree(index, num_nodes=None, dtype=None):
"""Computes the degree of a given index tensor.
Args:
index (LongTensor): Source or target indices of edges.
num_nodes (int, optional): The number of nodes in :attr:`index`.
(defaul... | 851 | 25.625 | 74 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/grid.py | import torch
from torch_sparse import coalesce
def grid(height, width, dtype=None, device=None):
edge_index = grid_index(height, width, device)
pos = grid_pos(height, width, dtype, device)
return edge_index, pos
def grid_index(height, width, device=None):
w = width
kernel = [-w - 1, -1, w - 1, -... | 1,289 | 31.25 | 78 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/convert.py | import torch
import scipy.sparse
import networkx as nx
from .num_nodes import maybe_num_nodes
def to_scipy_sparse_matrix(edge_index, edge_attr=None, num_nodes=None):
row, col = edge_index.cpu()
if edge_attr is None:
edge_attr = torch.ones(row.size(0))
else:
edge_attr = edge_attr.view(-1)... | 1,395 | 29.347826 | 78 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/normalized_cut.py | from torch_geometric.utils import degree
def normalized_cut(edge_index, edge_attr, num_nodes=None):
row, col = edge_index
deg = 1 / degree(row, num_nodes, edge_attr.dtype)
deg = deg[row] + deg[col]
cut = edge_attr * deg
return cut
| 253 | 24.4 | 58 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/utils/metric.py | from __future__ import division
import torch
def accuracy(pred, target):
return (pred == target).sum().item() / target.numel()
def true_positive(pred, target, num_classes):
out = []
for i in range(num_classes):
out.append(((pred == i) & (target == i)).sum())
return torch.tensor(out)
def ... | 1,583 | 21.628571 | 66 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/data/in_memory_dataset.py | from itertools import repeat, product
import torch
from torch_geometric.data import Dataset, Data
class InMemoryDataset(Dataset):
@property
def raw_file_names(self):
""""""
raise NotImplementedError
@property
def processed_file_names(self):
""""""
raise NotImplemented... | 3,026 | 29.27 | 79 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/data/batch.py | import torch
from torch_geometric.data import Data
class Batch(Data):
def __init__(self, batch=None, **kwargs):
super(Batch, self).__init__(**kwargs)
self.batch = batch
@staticmethod
def from_data_list(data_list):
""""""
keys = [set(data.keys) for data in data_list]
... | 1,300 | 27.282609 | 78 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/data/dataloader.py | import torch.utils.data
from torch.utils.data.dataloader import default_collate
from torch_geometric.data import Batch
class DataLoader(torch.utils.data.DataLoader):
def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):
super(DataLoader, self).__init__(
dataset,
batch... | 894 | 32.148148 | 77 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/data/dataset.py | import collections
import os.path as osp
import torch.utils.data
from .makedirs import makedirs
def to_list(x):
if not isinstance(x, collections.Iterable) or isinstance(x, str):
x = [x]
return x
def files_exist(files):
return all([osp.exists(f) for f in files])
class Dataset(torch.utils.data... | 2,415 | 22.456311 | 71 | py |
HGB | HGB-master/NC/benchmark/methods/RSHN/torch_geometric/data/data.py | import torch
from torch_geometric.utils import (contains_isolated_nodes,
contains_self_loops, is_undirected)
from ..utils.num_nodes import maybe_num_nodes
class Data(object):
""""""
def __init__(self,
x=None,
edge_index=None,
... | 3,271 | 24.968254 | 77 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/train_hgt.py | import scipy.io
import urllib.request
import dgl
import math
import numpy as np
from model import *
import torch
from data_loader import data_loader
from utils.data import load_data
from utils.pytorchtools import EarlyStopping
import argparse
import time
# data_url = 'https://s3.us-east-2.amazonaws.com/dgl.ai/dataset/A... | 8,105 | 41 | 283 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/model.py | import dgl
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class HGTLayer(nn.Module):
def __init__(self, in_dim, out_dim, num_types, num_relations, n_heads, dropout = 0.2, use_norm = False):
super(HGTLayer, self).__init__()
self.in_dim = in_dim
self.ou... | 5,348 | 45.513043 | 117 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/GNN.py | import torch
import torch.nn as nn
import dgl
from dgl.nn.pytorch import GraphConv
import dgl.function as fn
from dgl.nn.pytorch import edge_softmax, GATConv
from conv import myGATConv
class myGAT(nn.Module):
def __init__(self,
g,
edge_dim,
num_etypes,
... | 8,353 | 38.220657 | 169 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/run_hgt.py | import sys
sys.path.append('../../')
import time
import argparse
import torch
import torch.nn.functional as F
import numpy as np
from utils.pytorchtools import EarlyStopping
from utils.data import load_data
#from utils.tools import index_generator, evaluate_results_nc, parse_minibatch
from GNN import myGAT
import dgl... | 7,725 | 41.218579 | 183 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/gpu_memory_log.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################
# File name : gpu_mem.py
# Create date : 2019-06-02 16:56
# Modified date : 2019-06-02 16:59
# Author : DARREN
# Describe : not set
# Email : lzygzh@126.com
#####################################
from __future__ import division
from __future... | 2,719 | 33.871795 | 108 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/utils/pytorchtools.py | import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience, verbose=False, delta=0, save_path='checkpoint.pt'):
"""
Args:
patience (int): How long to wait after last time... | 1,824 | 36.244898 | 111 | py |
HGB | HGB-master/NC/benchmark/methods/HGT/utils/tools.py | import torch
import dgl
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.metrics import f1_score, normalized_mutual_info_score, adjusted_rand_score
from sklearn.cluster import KMeans
from sklearn.svm import LinearSVC
def idx_to_one_hot(idx_arr):
one_hot = np.zeros((idx_arr.shap... | 11,404 | 46.128099 | 174 | py |
HGB | HGB-master/NC/HAN/main.py | import torch
from sklearn.metrics import f1_score
import dgl
from utils import load_data, EarlyStopping
import torch.nn.functional as F
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '3'
def score(logits, labels):
_, indices = torch.max(logits, dim=1)
prediction = indices.long().cpu().numpy()
labels = labe... | 5,005 | 37.806202 | 151 | py |
HGB | HGB-master/NC/HAN/model_hetero.py | """This model shows an example of using dgl.metapath_reachable_graph on the original heterogeneous
graph.
Because the original HAN implementation only gives the preprocessed homogeneous graph, this model
could not reproduce the result in HAN as they did not provide the preprocessing code, and we
constructed another da... | 3,815 | 35 | 102 | py |
HGB | HGB-master/NC/HAN/utils.py | import datetime
import dgl
import errno
import numpy as np
import os
import pickle
import random
import torch
from dgl.data.utils import download, get_download_dir, _get_dgl_url
from pprint import pprint
from scipy import sparse
from scipy import io as sio
def set_random_seed(seed=0):
"""Set random seed.
Para... | 8,497 | 30.827715 | 89 | py |
HGB | HGB-master/NC/HAN/model.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn.pytorch import GATConv
class SemanticAttention(nn.Module):
def __init__(self, in_size, hidden_size=128):
super(SemanticAttention, self).__init__()
self.project = nn.Sequential(
nn.Linear(in_size, hidden_siz... | 2,829 | 32.690476 | 102 | py |
HGB | HGB-master/NC/HAN/GNN.py | import torch.nn as nn
import dgl
from dgl.nn.pytorch import GraphConv
import dgl.function as fn
from dgl.nn.pytorch import edge_softmax, GATConv
class GAT(nn.Module):
def __init__(self,
in_dim,
num_hidden,
num_classes,
num_layers,
... | 2,749 | 32.13253 | 84 | py |
HGB | HGB-master/NC/RSHN/build_coarsened_line_graph/utils.py | import scipy.sparse as sp
import numpy as np
from numba import jit
import torch
import random
random.seed(1233)
def score_matrix_from_random_walks(random_walks, N, symmetric=True):
"""
Compute the transition scores, i.e. how often a transition occurs, for all node pairs from
the random walks provided.
... | 5,396 | 31.125 | 114 | py |
HGB | HGB-master/NC/RSHN/build_coarsened_line_graph/relation_graph.py | from build_coarsened_line_graph import utils
import numpy as np
import scipy.sparse as sp
from torch_geometric.data import Data
import torch
def build_relation_adj(org_graph, num_relations, rw_len=3, batch_size=3):
'''build a AIFB-relation graph adjacency based on random walk from the original graph'''
# grap... | 3,042 | 41.263889 | 102 | py |
HGB | HGB-master/NC/RSHN/model/RSHN_gnn.py | import sys
sys.path.insert(0, '../')
import os.path as osp
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential, Linear
from torch_geometric.datasets import Entities
from torch_geometric.nn import NNConv, RelationConv
from torch_geometric.utils import remove_self_loops
fro... | 6,154 | 34.784884 | 151 | py |
HGB | HGB-master/NC/RSHN/model/GNN.py | import torch.nn as nn
import dgl
from dgl.nn.pytorch import GraphConv
import dgl.function as fn
from dgl.nn.pytorch import edge_softmax, GATConv
class GAT(nn.Module):
def __init__(self,
g,
num_layers,
in_dim,
num_hidden,
num_cl... | 3,112 | 31.768421 | 84 | py |
HGB | HGB-master/NC/RSHN/model/RSHN.py | import sys
sys.path.insert(0, '../')
import os.path as osp
import torch
import torch.nn.functional as F
from torch.nn import Sequential, Linear
from torch_geometric.datasets import Entities
from torch_geometric.nn import NNConv, RelationConv
from torch_geometric.utils import remove_self_loops
from build_coarsened_line... | 4,423 | 32.263158 | 104 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/nn/conv/nn_conv.py | import torch
from torch.nn import Parameter
from torch_geometric.nn.conv import MessagePassing
from ..inits import reset, uniform
class NNConv(MessagePassing):
def __init__(self,
in_channels,
out_channels,
nn,
aggr="add",
root_w... | 1,903 | 28.75 | 82 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/nn/conv/relation_conv.py | import torch
from torch.nn import Parameter
import torch.nn.functional as F
from torch_sparse import spmm
from torch_geometric.utils import remove_self_loops, add_self_loops, softmax, add_self_edge_attr_loops
class RelationConv(torch.nn.Module):
def __init__(self, eps=0, train_eps=False, requires_grad=True):
... | 1,967 | 30.741935 | 102 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/nn/conv/message_passing.py | import inspect
import torch
from torch_geometric.utils import scatter_
class MessagePassing(torch.nn.Module):
def __init__(self, aggr='add'):
super(MessagePassing, self).__init__()
self.message_args = inspect.getargspec(self.message)[0][1:]
self.update_args = inspect.getargspec(self.upda... | 1,335 | 28.688889 | 67 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/datasets/entities.py | import os
from collections import Counter
import gzip
import rdflib as rdf
import pandas as pd
import numpy as np
import torch
from torch_scatter import scatter_add
from torch_geometric.data import (InMemoryDataset, Data, download_url,
extract_tar)
from torch_geometric.utils import o... | 6,012 | 36.58125 | 78 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/softmax.py | from torch_scatter import scatter_max, scatter_add
from .num_nodes import maybe_num_nodes
def softmax(src, index, num_nodes=None):
r"""Sparse softmax of all values from the :attr:`src` tensor at the indices
specified in the :attr:`index` tensor along the first dimension.
Args:
src (Tensor): The ... | 1,162 | 29.605263 | 79 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/one_hot.py | import torch
from .repeat import repeat
def one_hot(src, num_classes=None, dtype=None):
src = src.to(torch.long)
src = src.unsqueeze(-1) if src.dim() == 1 else src
assert src.dim() == 2
if num_classes is None:
num_classes = src.max(dim=0)[0] + 1
else:
num_classes = torch.tensor(
... | 730 | 26.074074 | 72 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/undirected.py | import torch
from torch_sparse import coalesce
from .num_nodes import maybe_num_nodes
def is_undirected(edge_index, num_nodes=None):
num_nodes = maybe_num_nodes(edge_index, num_nodes)
edge_index, _ = coalesce(edge_index, None, num_nodes, num_nodes)
undirected_edge_index = to_undirected(edge_index, num_no... | 743 | 31.347826 | 74 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/to_batch.py | import torch
from torch_scatter import scatter_add
def to_batch(x, batch, fill_value=0):
num_nodes = scatter_add(batch.new_ones(x.size(0)), batch, dim=0)
batch_size, max_num_nodes = num_nodes.size(0), num_nodes.max().item()
cum_nodes = torch.cat([batch.new_zeros(1), num_nodes.cumsum(dim=0)], dim=0)
i... | 707 | 34.4 | 79 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/loop.py | import torch
from .num_nodes import maybe_num_nodes
def contains_self_loops(edge_index):
row, col = edge_index
mask = row == col
return mask.sum().item() > 0
def remove_self_loops(edge_index, edge_attr=None):
row, col = edge_index
mask = row != col
edge_attr = edge_attr if edge_attr is None... | 1,066 | 27.837838 | 67 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/isolated.py | import torch
from .num_nodes import maybe_num_nodes
from .loop import remove_self_loops
def contains_isolated_nodes(edge_index, num_nodes=None):
num_nodes = maybe_num_nodes(edge_index, num_nodes)
(row, _), _ = remove_self_loops(edge_index)
return torch.unique(row).size(0) < num_nodes
| 300 | 26.363636 | 56 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/sparse.py | import torch
from torch_sparse import coalesce
from .num_nodes import maybe_num_nodes
def dense_to_sparse(tensor):
index = tensor.nonzero().t().contiguous()
value = tensor[index[0], index[1]]
index, value = coalesce(index, value, tensor.size(0), tensor.size(1))
return index, value
def sparse_to_den... | 514 | 26.105263 | 76 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/scatter.py | import torch_scatter
def scatter_(name, src, index, dim_size=None):
r"""Aggregates all values from the :attr:`src` tensor at the indices
specified in the :attr:`index` tensor along the first dimension.
If multiple indices reference the same location, their contributions
are aggregated according to :at... | 1,467 | 30.234043 | 78 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/degree.py | import torch
from .num_nodes import maybe_num_nodes
def degree(index, num_nodes=None, dtype=None):
"""Computes the degree of a given index tensor.
Args:
index (LongTensor): Source or target indices of edges.
num_nodes (int, optional): The number of nodes in :attr:`index`.
(defaul... | 851 | 25.625 | 74 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/grid.py | import torch
from torch_sparse import coalesce
def grid(height, width, dtype=None, device=None):
edge_index = grid_index(height, width, device)
pos = grid_pos(height, width, dtype, device)
return edge_index, pos
def grid_index(height, width, device=None):
w = width
kernel = [-w - 1, -1, w - 1, -... | 1,289 | 31.25 | 78 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/convert.py | import torch
import scipy.sparse
import networkx as nx
from .num_nodes import maybe_num_nodes
def to_scipy_sparse_matrix(edge_index, edge_attr=None, num_nodes=None):
row, col = edge_index.cpu()
if edge_attr is None:
edge_attr = torch.ones(row.size(0))
else:
edge_attr = edge_attr.view(-1)... | 1,395 | 29.347826 | 78 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/normalized_cut.py | from torch_geometric.utils import degree
def normalized_cut(edge_index, edge_attr, num_nodes=None):
row, col = edge_index
deg = 1 / degree(row, num_nodes, edge_attr.dtype)
deg = deg[row] + deg[col]
cut = edge_attr * deg
return cut
| 253 | 24.4 | 58 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/utils/metric.py | from __future__ import division
import torch
def accuracy(pred, target):
return (pred == target).sum().item() / target.numel()
def true_positive(pred, target, num_classes):
out = []
for i in range(num_classes):
out.append(((pred == i) & (target == i)).sum())
return torch.tensor(out)
def ... | 1,583 | 21.628571 | 66 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/data/in_memory_dataset.py | from itertools import repeat, product
import torch
from torch_geometric.data import Dataset, Data
class InMemoryDataset(Dataset):
@property
def raw_file_names(self):
""""""
raise NotImplementedError
@property
def processed_file_names(self):
""""""
raise NotImplemented... | 3,026 | 29.27 | 79 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/data/batch.py | import torch
from torch_geometric.data import Data
class Batch(Data):
def __init__(self, batch=None, **kwargs):
super(Batch, self).__init__(**kwargs)
self.batch = batch
@staticmethod
def from_data_list(data_list):
""""""
keys = [set(data.keys) for data in data_list]
... | 1,300 | 27.282609 | 78 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/data/dataloader.py | import torch.utils.data
from torch.utils.data.dataloader import default_collate
from torch_geometric.data import Batch
class DataLoader(torch.utils.data.DataLoader):
def __init__(self, dataset, batch_size=1, shuffle=True, **kwargs):
super(DataLoader, self).__init__(
dataset,
batch... | 894 | 32.148148 | 77 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/data/dataset.py | import collections
import os.path as osp
import torch.utils.data
from .makedirs import makedirs
def to_list(x):
if not isinstance(x, collections.Iterable) or isinstance(x, str):
x = [x]
return x
def files_exist(files):
return all([osp.exists(f) for f in files])
class Dataset(torch.utils.data... | 2,415 | 22.456311 | 71 | py |
HGB | HGB-master/NC/RSHN/torch_geometric/data/data.py | import torch
from torch_geometric.utils import (contains_isolated_nodes,
contains_self_loops, is_undirected)
from ..utils.num_nodes import maybe_num_nodes
class Data(object):
""""""
def __init__(self,
x=None,
edge_index=None,
... | 3,271 | 24.968254 | 77 | py |
HGB | HGB-master/Recom/baseline/Model/main.py | '''
Modified on Jan. 1, 2021
Pytorch implementation of new baseline model for recommendation.
@author: Qingsong Lv (lqs19@mails.tsinghua.edu.cn, lqs@mail.bnu.edu.cn)
Created on Dec 18, 2018
Tensorflow Implementation of Knowledge Graph Attention Network (KGAT) model in:
Wang Xiang et al. KGAT: Knowledge Graph Attention... | 9,157 | 36.379592 | 247 | py |
HGB | HGB-master/Recom/baseline/Model/GNN.py | import numpy as np
import torch
import torch.nn as nn
import dgl
from dgl.nn.pytorch import GraphConv
import dgl.function as fn
from dgl.nn.pytorch import edge_softmax, GATConv
from conv import myGATConv
class myGAT(nn.Module):
def __init__(self,
num_entity,
edge_dim,
... | 3,070 | 38.883117 | 105 | py |
HGB | HGB-master/Recom/baseline/Model/conv.py | """Torch modules for graph attention networks(GAT)."""
# pylint: disable= no-member, arguments-differ, invalid-name
import torch as th
from torch import nn
from dgl import function as fn
from dgl.nn.pytorch import edge_softmax
from dgl._ffi.base import DGLError
from dgl.nn.pytorch.utils import Identity
from dgl.utils ... | 6,466 | 44.865248 | 92 | py |
HGB | HGB-master/Recom/baseline/Model/utility/batch_test.py | '''
Created on Dec 18, 2018
Tensorflow Implementation of Knowledge Graph Attention Network (KGAT) model in:
Wang Xiang et al. KGAT: Knowledge Graph Attention Network for Recommendation. In KDD 2019.
@author: Xiang Wang (xiangwang@u.nus.edu)
'''
import utility.metrics as metrics
from utility.parser import parse_args
imp... | 7,909 | 28.405204 | 101 | py |
NeRO | NeRO-main/extract_mesh.py | import argparse
from pathlib import Path
import torch
import trimesh
from network.field import extract_geometry
from network.renderer import name2renderer
from utils.base_utils import load_cfg
def main():
cfg = load_cfg(flags.cfg)
network = name2renderer[cfg['network']](cfg, training=False)
ckpt = tor... | 1,239 | 30 | 125 | py |
NeRO | NeRO-main/eval_synthetic_shape.py | from pathlib import Path
import torch
import numpy as np
import argparse
import trimesh
from skimage.io import imsave
from tqdm import tqdm
from dataset.database import parse_database_name, get_database_split, get_database_eval_points, GlossySyntheticDatabase
from utils.base_utils import mask_depth_to_pts, project_p... | 4,186 | 38.130841 | 119 | py |
NeRO | NeRO-main/extract_materials.py | import argparse
from pathlib import Path
import numpy as np
import torch
from network.renderer import NeROMaterialRenderer
from utils.base_utils import load_cfg
from utils.raw_utils import linear_to_srgb
def main():
cfg = load_cfg(flags.cfg)
network = NeROMaterialRenderer(cfg, False)
ckpt = torch.load(... | 1,646 | 41.230769 | 156 | py |
NeRO | NeRO-main/dataset/train_dataset.py | from torch.utils.data import Dataset
from dataset.database import get_database_split, parse_database_name
class DummyDataset(Dataset):
default_cfg={
'database_name': '',
}
def __init__(self, cfg, is_train):
self.cfg={**self.default_cfg,**cfg}
if not is_train:
database = ... | 820 | 29.407407 | 76 | py |
NeRO | NeRO-main/network/renderer.py | import cv2
import raytracing
import open3d
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dataset.database import parse_database_name, get_database_split, BaseDatabase
from network.field import SDFNetwork, SingleVarianceNetwork, NeRFNetwork, AppShadingNetwork, get_intersect... | 41,400 | 44.14831 | 174 | py |
NeRO | NeRO-main/network/field.py | import torch.nn.functional as F
import torch.nn as nn
import torch
import numpy as np
import nvdiffrast.torch as dr
import mcubes
from utils.base_utils import az_el_to_points, sample_sphere
from utils.raw_utils import linear_to_srgb
from utils.ref_utils import generate_ide_fn
# Positional encoding embedding. Code wa... | 46,683 | 41.171635 | 180 | py |
NeRO | NeRO-main/network/loss.py | import numpy as np
import torch
class Loss:
def __call__(self, data_pr, data_gt, step, **kwargs):
pass
class NeRFRenderLoss(Loss):
def __init__(self, cfg):
pass
def __call__(self, data_pr, data_gt, step, *args, **kwargs):
outputs={}
if 'loss_rgb' in data_pr: outputs['loss_r... | 5,128 | 37.56391 | 109 | py |
NeRO | NeRO-main/colmap/crawl_camera_specs.py | # Copyright (c) 2018, ETH Zurich and UNC Chapel Hill.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this ... | 5,449 | 39.073529 | 94 | py |
NeRO | NeRO-main/train/train_tools.py | import os
from collections import OrderedDict
import torch
import numpy as np
from tensorboardX import SummaryWriter
import torch.nn as nn
def load_model(model, optim, model_dir, epoch=-1):
if not os.path.exists(model_dir):
return 0
pths = [int(pth.split('.')[0]) for pth in os.listdir(model_dir)]
... | 5,352 | 29.764368 | 101 | py |
NeRO | NeRO-main/train/train_valid.py | import time
import torch
import numpy as np
from tqdm import tqdm
from network.metrics import name2key_metrics
from train.train_tools import to_cuda
class ValidationEvaluator:
default_cfg={}
def __init__(self,cfg):
self.cfg={**self.default_cfg,**cfg}
self.key_metric_name=cfg['key_metric_name... | 1,742 | 31.886792 | 96 | py |
NeRO | NeRO-main/train/trainer.py | import os
import random
from pathlib import Path
import torch
import numpy as np
from torch.optim import Adam, SGD
from torch.utils.data import DataLoader
from tqdm import tqdm
from dataset.name2dataset import name2dataset
from network.loss import name2loss
from network.renderer import name2renderer
from train.lr_com... | 8,143 | 37.415094 | 119 | py |
NeRO | NeRO-main/raytracing/raytracer.py |
import numpy as np
import torch
# CUDA extension
import _raytracing as _backend
class RayTracer():
def __init__(self, vertices, triangles):
# vertices: np.ndarray, [N, 3]
# triangles: np.ndarray, [M, 3]
if torch.is_tensor(vertices): vertices = vertices.detach().cpu().numpy()
if t... | 1,732 | 30.509091 | 83 | py |
NeRO | NeRO-main/utils/base_utils.py | import math
import os
import cv2
import h5py
import torch
import numpy as np
import pickle
import yaml
from numpy import ndarray
from plyfile import PlyData
from skimage.io import imread
#######################io#########################################
from torch import Tensor
from tqdm import tqdm
from transforms... | 27,045 | 32.023199 | 135 | py |
NeRO | NeRO-main/utils/dataset_utils.py | import numpy as np
import time
import random
import torch
def dummy_collate_fn(data_list):
return data_list[0]
def simple_collate_fn(data_list):
ks=data_list[0].keys()
outputs={k:[] for k in ks}
for k in ks:
for data in data_list:
outputs[k].append(data[k])
outputs[k]=torch... | 740 | 27.5 | 68 | py |
NeRO | NeRO-main/utils/ref_utils.py | import math
import torch
import numpy as np
def generalized_binomial_coeff(a, k):
"""Compute generalized binomial coefficients."""
return np.prod(a - np.arange(k)) / np.math.factorial(k)
def assoc_legendre_coeff(l, m, k):
"""Compute associated Legendre polynomial coefficients.
Returns the coeff... | 4,433 | 33.640625 | 107 | py |
NeRO | NeRO-main/utils/raw_utils.py | import torch
import numpy as np
def linear_to_srgb(linear):
if isinstance(linear, torch.Tensor):
"""Assumes `linear` is in [0, 1], see https://en.wikipedia.org/wiki/SRGB."""
eps = torch.finfo(torch.float32).eps
srgb0 = 323 / 25 * linear
srgb1 = (211 * torch.clamp(linear, min=eps)**(... | 4,085 | 39.455446 | 84 | py |
cerl | cerl-master/main.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 15,840 | 39.002525 | 222 | py |
cerl | cerl-master/core/neuroevolution.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 10,596 | 31.506135 | 141 | py |
cerl | cerl-master/core/off_policy_algo.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 6,536 | 36.568966 | 242 | py |
cerl | cerl-master/core/buffer.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 3,379 | 32.465347 | 197 | py |
cerl | cerl-master/core/runner.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 3,444 | 37.707865 | 176 | py |
cerl | cerl-master/core/models.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 4,395 | 24.12 | 82 | py |
cerl | cerl-master/core/mod_utils.py | # ******************************************************************************
# Copyright 2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.o... | 7,561 | 24.547297 | 121 | py |
Prompt-Free-Diffusion | Prompt-Free-Diffusion-master/app.py | ################################################################################
# Copyright (C) 2023 Xingqian Xu - All Rights Reserved #
# #
# Please visit Prompt-Free-Diffusion's arXiv paper for more details, link at ... | 19,111 | 37.147705 | 203 | py |
Prompt-Free-Diffusion | Prompt-Free-Diffusion-master/tools/get_controlnet.py | # A tool to get and slim downloaded controlnet
import torch
from safetensors.torch import load_file, save_file
from collections import OrderedDict
import os.path as osp
in_path = 'pretrained/controlnet/sdwebui_compatible/control_v11p_sd15_canny.pth'
out_path = 'pretrained/controlnet/control_v11p_sd15_canny_slimmed.s... | 473 | 30.6 | 81 | py |
Prompt-Free-Diffusion | Prompt-Free-Diffusion-master/tools/model_conversion.py | # A tool to convert sdwebui/huggingface model to pfd or vice versa
import os.path as osp
import torch
from collections import OrderedDict
from safetensors.torch import load_file, save_file
class sdwebui_diffuser_to_pfd_mover():
def __init__(self):
pass
def move_tembed_blocks(self):
mapping = ... | 49,721 | 68.444134 | 164 | py |
Prompt-Free-Diffusion | Prompt-Free-Diffusion-master/lib/log_service.py | import timeit
import numpy as np
import os
import os.path as osp
import shutil
import copy
import torch
import torch.nn as nn
import torch.distributed as dist
from .cfg_holder import cfg_unique_holder as cfguh
from . import sync
def print_log(*console_info):
grank, lrank, _ = sync.get_rank('all')
if lrank!=0:
... | 4,960 | 28.885542 | 80 | py |
Prompt-Free-Diffusion | Prompt-Free-Diffusion-master/lib/utils.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
# cudnn.enabled = True
# cudnn.benchmark = True
import torch.distributed as dist
import torch.multiprocessing as mp
import os
import os.path as osp
import sys
import numpy as np
import random
import pprint
import ti... | 23,356 | 34.82362 | 102 | py |
Prompt-Free-Diffusion | Prompt-Free-Diffusion-master/lib/sync.py | from multiprocessing import shared_memory
# import multiprocessing
# if hasattr(multiprocessing, "shared_memory"):
# from multiprocessing import shared_memory
# else:
# # workaround for single gpu inference on colab
# shared_memory = None
import random
import pickle
import time
import copy
import torch
imp... | 8,035 | 30.637795 | 89 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.