instruction stringclasses 100
values | code stringlengths 78 193k | response stringlengths 259 170k | file stringlengths 59 203 |
|---|---|---|---|
Document functions with clear intent |
from __future__ import absolute_import
import numpy as np
from numba import njit, prange
from .utils import common
from .my_neuron_coverage import MyNeuronCoverage
from pdb import set_trace as st
class StrongNeuronActivationCoverage(MyNeuronCoverage):
def __init__(self, k=5):
super(StrongNeuronActivatio... | --- +++ @@ -1,3 +1,6 @@+"""
+Provides a class for model neuron coverage evaluation.
+"""
from __future__ import absolute_import
@@ -19,6 +22,29 @@ @staticmethod
@njit(parallel=True)
def _calc_1(intermediate_layer_output, features_index, k):
+ """Calculate the mean of each output from each neur... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/strong_neuron_activation_coverage.py |
Generate documentation strings for clarity |
from __future__ import absolute_import
import os
import time
import numpy as np
def readable_time_str():
return time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
def user_home_dir():
return os.path.expanduser("~")
def to_numpy(data):
if 'mxnet' in str(type(data)):
data = data.asnumpy()
... | --- +++ @@ -1,3 +1,6 @@+"""
+Provides some useful functions.
+"""
from __future__ import absolute_import
@@ -8,18 +11,45 @@
def readable_time_str():
+ """Get readable time string based on current local time.
+
+ The time string will be formatted as %Y-%m-%d %H:%M:%S.
+
+ Returns
+ -------
+ str
... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/utils/common.py |
Write docstrings for data processing functions |
from __future__ import absolute_import
import warnings
from functools import partial
import torch
from .utils import common
from pdb import set_trace as st
class PyTorchModel:
def __init__(self, model, intermedia_mode=""):
assert isinstance(model, torch.nn.Module)
self._model = model
s... | --- +++ @@ -1,3 +1,6 @@+"""
+Provides a class for torch model evaluation.
+"""
from __future__ import absolute_import
@@ -10,6 +13,23 @@ from pdb import set_trace as st
class PyTorchModel:
+ """ Class for torch model evaluation.
+
+ Provide predict, intermediate_layer_outputs and adversarial_attack
+ m... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/pytorch_wrapper.py |
Write docstrings for data processing functions |
from __future__ import absolute_import
import random
import gluoncv
import mxnet
import numpy as np
from evaldnn.utils import common
class ImageNetValDataset(mxnet.gluon.data.Dataset):
mean = (0.485, 0.456, 0.406)
std = (0.229, 0.224, 0.225)
def __init__(self, resize_size, center_crop_size, preproce... | --- +++ @@ -1,3 +1,6 @@+"""
+Provides some useful utils for mxnet model evaluation.
+"""
from __future__ import absolute_import
@@ -11,6 +14,30 @@
class ImageNetValDataset(mxnet.gluon.data.Dataset):
+ """ Class for loading and preprocessing imagenet validation set.
+
+ One can download the imagenet valid... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/ReMoS/CV_adv/nc_prune/coverage/utils/mxnet.py |
Generate docstrings with examples | from base.loss import adv_loss, CORAL, kl_js, mmd, mutual_info, cosine, pairwise_dist
class TransferLoss(object):
def __init__(self, loss_type='cosine', input_dim=512):
self.loss_type = loss_type
self.input_dim = input_dim
def compute(self, X, Y):
if self.loss_type == 'mmd_lin' or sel... | --- +++ @@ -3,10 +3,22 @@
class TransferLoss(object):
def __init__(self, loss_type='cosine', input_dim=512):
+ """
+ Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
+ """
self.loss_type = loss_type
self.input_dim = input_dim
def compute(s... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/base/loss_transfer.py |
Add verbose docstrings with examples | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tst.multiHeadAttention import MultiHeadAttention, MultiHeadAttentionChunk, MultiHeadAttentionWindow
from tst.positionwiseFeedForward import PositionwiseFeedForward
class Decoder(nn.Module):
def __init__(self,
... | --- +++ @@ -8,6 +8,31 @@
class Decoder(nn.Module):
+ """Decoder block from Attention is All You Need.
+
+ Apply two Multi Head Attention block followed by a Point-wise Feed Forward block.
+ Residual sum and normalization are applied at each step.
+
+ Parameters
+ ----------
+ d_model:
+ Di... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/decoder.py |
Add docstrings for production code | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tst.multiHeadAttention import MultiHeadAttention, MultiHeadAttentionChunk, MultiHeadAttentionWindow
from tst.positionwiseFeedForward import PositionwiseFeedForward
class Encoder(nn.Module):
def __init__(self,
... | --- +++ @@ -8,6 +8,31 @@
class Encoder(nn.Module):
+ """Encoder block from Attention is All You Need.
+
+ Apply Multi Head Attention block followed by a Point-wise Feed Forward block.
+ Residual sum and normalization are applied at each step.
+
+ Parameters
+ ----------
+ d_model:
+ Dimensi... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/encoder.py |
Help me write clear docstrings | # A wrapper of Visdom for visualization
import visdom
import numpy as np
import time
class Visualize(object):
def __init__(self, port=8097, env='env'):
self.port = port
self.env = env
self.vis = visdom.Visdom(port=self.port, env=self.env)
def plot_line(self, Y, global_step, title='tit... | --- +++ @@ -11,6 +11,11 @@ self.vis = visdom.Visdom(port=self.port, env=self.env)
def plot_line(self, Y, global_step, title='title', legend=['legend']):
+ """ Plot line
+ Inputs:
+ Y (list): values to plot, a list
+ global_step (int): global step
+ """
... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/utils/visualize.py |
Write reusable docstrings | import collections
import torch
import os
import pandas as pd
import torch.nn as nn
from tqdm import tqdm
import numpy as np
EPS = 1e-12
class AverageMeter(object):
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
... | --- +++ @@ -59,6 +59,11 @@
def test_ic(model_list, data_list, device, verbose=True, ic_type='spearman'):
+ '''
+ model_list: [model1, model2, ...]
+ datalist: [loader1, loader2, ...]
+ return: unified ic, specific ic (all values), loss
+ '''
spec_ic = []
loss_test = AverageMeter()
loss... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/utils/utils.py |
Add verbose docstrings with examples | import torch
import torch.nn as nn
from tst.encoder import Encoder
from tst.decoder import Decoder
from tst.utils import generate_original_PE, generate_regular_PE
from base.loss_transfer import TransferLoss
class Transformer(nn.Module):
def __init__(self,
d_input: int,
d_model: ... | --- +++ @@ -7,6 +7,50 @@ from base.loss_transfer import TransferLoss
class Transformer(nn.Module):
+ """Transformer model from Attention is All You Need.
+
+ A classic transformer model adapted for sequential data.
+ Embedding has been replaced with a fully connected layer,
+ the last layer softmax is no... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/transformer.py |
Generate docstrings with examples | # encoding=utf-8
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.metrics
import sklearn.neighbors
from sklearn import metrics
from sklearn import svm
def kernel(ker, X1, X2, gamma):
K = None
if not ker or ker == 'primal':
K = X1
elif ker == 'linear':
if X2 is not Non... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 9:52 2018/11/14
+ @author: Jindong Wang
+"""
import numpy as np
import scipy.io
@@ -30,6 +34,9 @@
def proxy_a_distance(source_X, target_X):
+ """
+ Compute the Proxy-A-Distance of a source/target representation
+ """
nb_source = np.... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/BDA/BDA.py |
Add return value explanations in docstrings | # encoding=utf-8
import gzip
import pickle
from scipy.io import loadmat
import torch.utils.data as data
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
import torch
## For loading datasets of MNIST, USPS, and SVHN.
class GetDataset(data.Dataset):
def __init__(self, data, l... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 10:35 2018/12/29
+ @author: Jindong Wang
+"""
import gzip
import pickle
@@ -14,6 +18,15 @@
class GetDataset(data.Dataset):
+ """Args:
+ transform (callable, optional): A function/transform that takes in an PIL image
+ and re... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/feature_extractor/for_digit_data/digit_data_loader.py |
Add docstrings that explain inputs and outputs | from typing import Optional, Union
import numpy as np
import torch
def generate_original_PE(length: int, d_model: int) -> torch.Tensor:
PE = torch.zeros((length, d_model))
pos = torch.arange(length).unsqueeze(1)
PE[:, 0::2] = torch.sin(
pos / torch.pow(1000, torch.arange(0, d_model, 2, dtype=tor... | --- +++ @@ -5,6 +5,19 @@
def generate_original_PE(length: int, d_model: int) -> torch.Tensor:
+ """Generate positional encoding as described in original paper. :class:`torch.Tensor`
+
+ Parameters
+ ----------
+ length:
+ Time window length, i.e. K.
+ d_model:
+ Dimension of the model ... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/utils.py |
Add inline docstrings for readability | from typing import Optional
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tst.utils import generate_local_map_mask
class MultiHeadAttention(nn.Module):
def __init__(self,
d_model: int,
q: int,
v: int,
... | --- +++ @@ -9,6 +9,26 @@
class MultiHeadAttention(nn.Module):
+ """Multi Head Attention block from Attention is All You Need.
+
+ Given 3 inputs of shape (batch_size, K, d_model), that will be used
+ to compute query, keys and values, we output a self attention
+ tensor of shape (batch_size, K, d_model)... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/multiHeadAttention.py |
Add docstrings explaining edge cases | from typing import Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
class PositionwiseFeedForward(nn.Module):
def __init__(self,
d_model: int,
d_ff: Optional[int] = 2048):
super().__init__()
self._linear1 = nn.Linear(d_model, d_ff)
... | --- +++ @@ -6,14 +6,41 @@
class PositionwiseFeedForward(nn.Module):
+ """Position-wise Feed Forward Network block from Attention is All You Need.
+
+ Apply two linear transformations to each input, separately but indetically. We
+ implement them as 1D convolutions. Input and output have a shape (batch_size... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/positionwiseFeedForward.py |
Generate missing documentation strings | import torch
import torch.nn as nn
class OZELoss(nn.Module):
def __init__(self, reduction: str = 'mean', alpha: float = 0.3):
super().__init__()
self.alpha = alpha
self.reduction = reduction
self.base_loss = nn.MSELoss(reduction=self.reduction)
def forward(self,
... | --- +++ @@ -3,6 +3,23 @@
class OZELoss(nn.Module):
+ """Custom loss for TRNSys metamodel.
+
+ Compute, for temperature and consumptions, the intergral of the squared differences
+ over time. Sum the log with a coeficient ``alpha``.
+
+ .. math::
+ \Delta_T = \sqrt{\int (y_{est}^T - y^T)^2}
+
+ ... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/deep/adarnn/tst/loss.py |
Generate missing documentation strings | # encoding=utf-8
import numpy as np
import scipy.io
import bob.learn
import bob.learn.linear
import bob.math
from sklearn.neighbors import KNeighborsClassifier
class GFK:
def __init__(self, dim=20):
self.dim = dim
self.eps = 1e-20
def fit(self, Xs, Xt, norm_inputs=None):
if norm_inpu... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 17:25 2018/11/13
+ @author: Jindong Wang
+"""
import numpy as np
import scipy.io
@@ -10,10 +14,21 @@
class GFK:
def __init__(self, dim=20):
+ '''
+ Init func
+ :param dim: dimension after GFK
+ '''
self.dim... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/GFK/GFK.py |
Help me add docstrings to my project |
import argparse
import data_load
import models
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import time
import copy
import os
# Command setting
parser = argparse.ArgumentParser(description='Finetune')
parser.add_argument('--model_name', type=str,
... | --- +++ @@ -1,3 +1,12 @@+"""
+Extract features from pre-trained networks.
+The main procedures are finetune and extract features.
+Finetune: Given an Imagenet pretrained model (such as ResNet50), finetune it on a dataset (we call it source)
+Extractor: After fine-tune, extract features on the target domain using finetu... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/feature_extractor/for_image_data/main.py |
Add docstrings with type hints explained | # encoding=utf-8
import numpy as np
import scipy.io
from sklearn import metrics
from sklearn import svm
from sklearn.neighbors import KNeighborsClassifier
import GFK
def kernel(ker, X1, X2, gamma):
K = None
if not ker or ker == 'primal':
K = X1
elif ker == 'linear':
if X2 is not None:
... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 10:40 2018/11/14
+ @author: Jindong Wang
+"""
import numpy as np
import scipy.io
@@ -27,6 +31,9 @@
def proxy_a_distance(source_X, target_X):
+ """
+ Compute the Proxy-A-Distance of a source/target representation
+ """
nb_source = np... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/MEDA/MEDA.py |
Add docstrings to make code maintainable | # Compute MMD (maximum mean discrepancy) using numpy and scikit-learn.
import numpy as np
from sklearn import metrics
def mmd_linear(X, Y):
delta = X.mean(0) - Y.mean(0)
return delta.dot(delta.T)
def mmd_rbf(X, Y, gamma=1.0):
XX = metrics.pairwise.rbf_kernel(X, X, gamma)
YY = metrics.pairwise.rbf_k... | --- +++ @@ -5,11 +5,39 @@
def mmd_linear(X, Y):
+ """MMD using linear kernel (i.e., k(x,y) = <x,y>)
+ Note that this is not the original linear MMD, only the reformulated and faster version.
+ The original version is:
+ def mmd_linear(X, Y):
+ XX = np.dot(X, X.T)
+ YY = np.dot(... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/distance/mmd_numpy_sklearn.py |
Add docstrings for utility scripts | # coding: utf-8
from __future__ import unicode_literals
import logging
import time
from collections import Counter
from wxpy.utils import match_attributes, match_name
from wxpy.compatible import *
logger = logging.getLogger(__name__)
class Chats(list):
def __init__(self, chat_list=None, source=None):
... | --- +++ @@ -12,6 +12,9 @@
class Chats(list):
+ """
+ 多个聊天对象的合集,可用于搜索或统计
+ """
def __init__(self, chat_list=None, source=None):
if chat_list:
@@ -22,6 +25,19 @@ return Chats(super(Chats, self).__add__(other or list()))
def search(self, keywords=None, **attributes):
+ ""... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/chats/chats.py |
Document this module using docstrings | import numpy as np
import scipy as sp
import sklearn
from sklearn import linear_model
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
class SCL(object):
def __init__(self, l2=1.0, num_pivots=10, base_classifer=LinearSVC()):
self.l2 = l2
self.num_pivots = num_pivots
... | --- +++ @@ -6,6 +6,9 @@ from sklearn.metrics import accuracy_score
class SCL(object):
+ '''
+ class of structural correspondence learning
+ '''
def __init__(self, l2=1.0, num_pivots=10, base_classifer=LinearSVC()):
self.l2 = l2
self.num_pivots = num_pivots
@@ -14,6 +17,14 @@ ... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/SCL.py |
Add docstrings with type hints explained | # coding: utf-8
from __future__ import unicode_literals
import logging
from wxpy.utils import handle_response
from .chat import Chat
logger = logging.getLogger(__name__)
class User(Chat):
def __init__(self, raw, bot):
super(User, self).__init__(raw, bot)
@property
def remark_name(self):
... | --- +++ @@ -10,16 +10,27 @@
class User(Chat):
+ """
+ 好友(:class:`Friend`)、群聊成员(:class:`Member`),和公众号(:class:`MP`) 的基础类
+ """
def __init__(self, raw, bot):
super(User, self).__init__(raw, bot)
@property
def remark_name(self):
+ """
+ 备注名称
+ """
retur... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/chats/user.py |
Write Python docstrings for this snippet | # encoding=utf-8
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.metrics
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
def kernel(ker, X1, X2, gamma):
K = None
if not ker or ker == 'primal':
K = X1
elif ker == 'linear'... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 21:29 2018/11/12
+ @author: Jindong Wang
+"""
import numpy as np
import scipy.io
import scipy.linalg
@@ -29,12 +33,25 @@
class TCA:
def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1):
+ '''
+ Init func
+ :par... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/TCA/TCA.py |
Help me document legacy Python code | # encoding=utf-8
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.metrics
import sklearn.neighbors
class CORAL:
def __init__(self):
super(CORAL, self).__init__()
def fit(self, Xs, Xt):
cov_src = np.cov(Xs.T) + np.eye(Xs.shape[1])
cov_tar = np.cov(Xt.T) + np.eye(X... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 16:31 2018/11/13
+ @author: Jindong Wang
+"""
import numpy as np
import scipy.io
@@ -12,6 +16,12 @@ super(CORAL, self).__init__()
def fit(self, Xs, Xt):
+ '''
+ Perform CORAL on the source domain features
+ :param ... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/CORAL/CORAL.py |
Add well-formatted docstrings |
import numpy as np
import sklearn.metrics
from cvxopt import matrix, solvers
import os
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--norm', action='store_true')
args = parser.parse_args()
def ker... | --- +++ @@ -1,3 +1,8 @@+"""
+Kernel Mean Matching
+# 1. Gretton, Arthur, et al. "Covariate shift by kernel mean matching." Dataset shift in machine learning 3.4 (2009): 5.
+# 2. Huang, Jiayuan, et al. "Correcting sample selection bias by unlabeled data." Advances in neural information processing systems. 2006.
+"""
... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/KMM.py |
Add docstrings for internal functions | # encoding=utf-8
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.metrics
from sklearn.neighbors import KNeighborsClassifier
def kernel(ker, X1, X2, gamma):
K = None
if not ker or ker == 'primal':
K = X1
elif ker == 'linear':
if X2:
K = sklearn.metrics.pair... | --- +++ @@ -1,4 +1,8 @@ # encoding=utf-8
+"""
+ Created on 21:29 2018/11/12
+ @author: Jindong Wang
+"""
import numpy as np
import scipy.io
import scipy.linalg
@@ -25,6 +29,14 @@
class JDA:
def __init__(self, kernel_type='primal', dim=30, lamb=1, gamma=1, T=10):
+ '''
+ Init func
+ ... | https://raw.githubusercontent.com/jindongwang/transferlearning/HEAD/code/traditional/JDA/JDA.py |
Add docstrings explaining edge cases | # coding: utf-8
from __future__ import unicode_literals
import datetime
import logging
import re
import time
from functools import partial, wraps
from wxpy.api.consts import ATTACHMENT, PICTURE, TEXT, VIDEO
from wxpy.compatible import *
from wxpy.compatible.utils import force_encoded_string_output
from wxpy.utils imp... | --- +++ @@ -16,6 +16,9 @@
def wrapped_send(msg_type):
+ """
+ send() 系列方法较为雷同,因此采用装饰器方式完成发送,并返回 SentMessage 对象
+ """
def decorator(func):
@wraps(func)
@@ -77,6 +80,9 @@
class Chat(object):
+ """
+ 单个用户 (:class:`User`) 和群聊 (:class:`Group`) 的基础类
+ """
def __init__(self, ra... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/chats/chat.py |
Expand my code with proper documentation strings | # coding: utf-8
from __future__ import unicode_literals
import logging
from wxpy.utils import get_receiver
logger = logging.getLogger(__name__)
class WeChatLoggingHandler(logging.Handler):
def __init__(self, receiver=None):
super(WeChatLoggingHandler, self).__init__()
self.receiver = get_recei... | --- +++ @@ -10,6 +10,14 @@
class WeChatLoggingHandler(logging.Handler):
def __init__(self, receiver=None):
+ """
+ 可向指定微信聊天对象发送日志的 Logging Handler
+
+ :param receiver:
+ * 当为 `None`, `True` 或字符串时,将以该值作为 `cache_path` 参数启动一个新的机器人,并发送到该机器人的"文件传输助手"
+ * 当为 :class:`机器人 <Bot>... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/ext/logging_with_wechat.py |
Create docstrings for API functions | # coding: utf-8
from __future__ import unicode_literals
import atexit
import functools
import logging
import os.path
import tempfile
import time
from pprint import pformat
from threading import Thread
try:
import queue
except ImportError:
# noinspection PyUnresolvedReferences,PyPep8Naming
import Queue as ... | --- +++ @@ -31,11 +31,40 @@
class Bot(object):
+ """
+ 机器人对象,用于登陆和操作微信账号,涵盖大部分 Web 微信的功能::
+
+ from wxpy import *
+ bot = Bot()
+
+ # 机器人账号自身
+ myself = bot.self
+
+ # 向文件传输助手发送消息
+ bot.file_helper.send('Hello from wxpy!')
+
+
+ """
... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/bot.py |
Add docstrings to improve code quality | # coding: utf-8
from __future__ import unicode_literals
import logging
from wxpy.utils import ensure_list, get_user_name, handle_response, wrap_user_name
from .chat import Chat
from .chats import Chats
from .member import Member
logger = logging.getLogger(__name__)
class Group(Chat):
def __init__(self, raw, b... | --- +++ @@ -12,12 +12,18 @@
class Group(Chat):
+ """
+ 群聊对象
+ """
def __init__(self, raw, bot):
super(Group, self).__init__(raw, bot)
@property
def members(self):
+ """
+ 群聊的成员列表
+ """
def raw_member_list(update=False):
if update:
@@ ... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/chats/group.py |
Write docstrings for utility functions | # coding: utf-8
from __future__ import unicode_literals
import threading
from wxpy.utils import match_attributes, match_text
class Messages(list):
def __init__(self, msg_list=None, max_history=200):
if msg_list:
super(Messages, self).__init__(msg_list)
self.max_history = max_history
... | --- +++ @@ -6,6 +6,9 @@
class Messages(list):
+ """
+ 多条消息的合集,可用于记录或搜索
+ """
def __init__(self, msg_list=None, max_history=200):
if msg_list:
@@ -14,12 +17,23 @@ self._thread_lock = threading.Lock()
def append(self, msg):
+ """
+ 仅当 self.max_history 为 int 类型,且大于... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/messages/messages.py |
Generate docstrings for exported functions | # coding: utf-8
from __future__ import unicode_literals
import logging
import os
import tempfile
import weakref
from datetime import datetime
from xml.etree import ElementTree as ETree
try:
import html
except ImportError:
# Python 2.6-2.7
# noinspection PyUnresolvedReferences,PyUnresolvedReferences,PyComp... | --- +++ @@ -28,6 +28,15 @@
class Message(object):
+ """
+ 单条消息对象,包括:
+
+ * 来自好友、群聊、好友请求等聊天对象的消息
+ * 使用机器人账号在手机微信中发送的消息
+
+ | 但 **不包括** 代码中通过 .send/reply() 系列方法发出的消息
+ | 此类消息请参见 :class:`SentMessage`
+ """
def __init__(self, raw, bot):
self.raw = raw
@@ -53,15 +62,49 @@
... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/messages/message.py |
Help me document legacy Python code | # coding: utf-8
from __future__ import unicode_literals
import inspect
import logging
import random
import re
import threading
import weakref
from functools import wraps
import requests
from requests.adapters import HTTPAdapter
from wxpy.compatible import PY2
from wxpy.exceptions import ResponseError
if PY2:
fr... | --- +++ @@ -20,6 +20,11 @@
def decode_text_from_webwx(text):
+ """
+ 解码从 Web 微信获得到的中文乱码
+
+ :param text: 从 Web 微信获得到的中文乱码
+ """
if isinstance(text, str):
try:
text = text.encode('raw_unicode_escape').decode()
@@ -29,6 +34,11 @@
def check_response_body(response_body):
+ ... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/utils/misc.py |
Create documentation for each function signature | # coding: utf-8
from __future__ import unicode_literals
import weakref
from wxpy.api.consts import SYSTEM
class Registered(list):
def __init__(self, bot):
super(Registered, self).__init__()
self.bot = weakref.proxy(bot)
def get_config(self, msg):
for conf in self[::-1]:
... | --- +++ @@ -8,10 +8,21 @@
class Registered(list):
def __init__(self, bot):
+ """
+ 保存当前机器人所有已注册的消息配置
+
+ :param bot: 所属的机器人
+ """
super(Registered, self).__init__()
self.bot = weakref.proxy(bot)
def get_config(self, msg):
+ """
+ 获取给定消息的注册配置。每条消息... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/api/messages/registered.py |
Fill in missing docstrings in my code | # coding: utf-8
from __future__ import unicode_literals
import logging
import time
from functools import wraps
from wxpy.exceptions import ResponseError
logger = logging.getLogger(__name__)
def dont_raise_response_error(func):
@wraps(func)
def wrapped(*args, **kwargs):
try:
return func... | --- +++ @@ -11,6 +11,9 @@
def dont_raise_response_error(func):
+ """
+ 装饰器:用于避免被装饰的函数在运行过程中抛出 ResponseError 错误
+ """
@wraps(func)
def wrapped(*args, **kwargs):
@@ -23,6 +26,14 @@
def ensure_one(found):
+ """
+ 确保列表中仅有一个项,并返回这个项,否则抛出 `ValueError` 异常
+
+ 通常可用在查找聊天对象时,确保查找结果的唯一性,并直接获取... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/utils/tools.py |
Add docstrings explaining edge cases | # coding: utf-8
from __future__ import unicode_literals
# created by: Han Feng (https://github.com/hanx11)
import collections
import hashlib
import logging
import requests
from wxpy.api.messages import Message
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_wi... | --- +++ @@ -18,9 +18,19 @@ from wxpy.compatible import *
class XiaoI(object):
+ """
+ 与 wxpy 深度整合的小 i 机器人
+ """
# noinspection SpellCheckingInspection
def __init__(self, key, secret):
+ """
+ | 需要通过注册获得 key 和 secret
+ | 免费申请: http://cloud.xiaoi.com/
+
+ :param key: 你申... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/ext/xiaoi.py |
Add docstrings that explain inputs and outputs | # coding: utf-8
from __future__ import unicode_literals
import atexit
import os
import pickle
import threading
from wxpy.compatible import PY2
if PY2:
from UserDict import UserDict
else:
from collections import UserDict
"""
# puid
尝试用聊天对象已知的属性,来查找对应的持久固定并且唯一的 用户 id
## 数据结构
PuidMap 中包含 4 个 dict,分别为
1. u... | --- +++ @@ -42,6 +42,11 @@
class PuidMap(object):
def __init__(self, path):
+ """
+ 用于获取聊天对象的 puid (持续有效,并且稳定唯一的用户ID),和保存映射关系
+
+ :param path: 映射数据的保存/载入路径
+ """
self.path = path
self.user_names = TwoWayDict()
@@ -71,6 +76,13 @@ return bool(self.path)
... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/utils/puid_map.py |
Write docstrings for algorithm functions | # coding: utf-8
from __future__ import unicode_literals
import logging
import pprint
import requests
from wxpy.ext.talk_bot_utils import get_context_user_id, next_topic
from wxpy.utils.misc import get_text_without_at_bot
from wxpy.utils import enhance_connection
from wxpy.compatible import *
logger = logging.getLogg... | --- +++ @@ -14,6 +14,9 @@
class Tuling(object):
+ """
+ 与 wxpy 深度整合的图灵机器人
+ """
'API 文档: http://tuling123.com/help/h_cent_webapi.jhtml'
@@ -22,6 +25,12 @@ url = 'http://www.tuling123.com/openapi/api'
def __init__(self, api_key=None):
+ """
+ | 内置的 api key 存在调用限制,建议自行申请。
+ ... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/ext/tuling.py |
Add inline docstrings for readability | # coding: utf-8
from __future__ import unicode_literals
import functools
import json
import itchat.config
import itchat.returnvalues
from .misc import handle_response
class BaseRequest(object):
def __init__(self, bot, uri, params=None):
self.bot = bot
self.url = self.bot.core.loginInfo['url'] +... | --- +++ @@ -12,6 +12,18 @@
class BaseRequest(object):
def __init__(self, bot, uri, params=None):
+ """
+ 基本的 Web 微信请求模板,可用于修改后发送请求
+
+ 可修改属性包括:
+
+ * url (会通过 url 参数自动拼接好)
+ * data (默认仅包含 BaseRequest 部分)
+ * headers
+
+ :param bot: 所使用的机器人对... | https://raw.githubusercontent.com/youfou/wxpy/HEAD/wxpy/utils/base_request.py |
Add professional docstrings to my codebase | import inspect
import json
import os
import pickle
import shutil
import time
import zipfile
from functools import partial, reduce, wraps
from timeit import default_timer
import dgl
import numpy as np
import pandas
import requests
import torch
from ogb.nodeproppred import DglNodePropPredDataset
def _download(url, pa... | --- +++ @@ -40,6 +40,9 @@
def thread_wrapped_func(func):
+ """
+ Wraps a process entry point to make it work with OpenMP.
+ """
@wraps(func)
def decorated_function(*args, **kwargs):
@@ -370,6 +373,48 @@
def parametrize(param_name, params):
+ """Decorator for benchmarking over a set of pa... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/utils.py |
Generate docstrings for this script | import itertools
import time
import dgl
import dgl.nn.pytorch as dglnn
import torch as th
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from dgl.nn import RelGraphConv
from torch.utils.data import DataLoader
from .. import utils
class EntityClas... | --- +++ @@ -15,6 +15,28 @@
class EntityClassify(nn.Module):
+ """Entity classification class for RGCN
+ Parameters
+ ----------
+ device : int
+ Device to run the layer.
+ num_nodes : int
+ Number of nodes.
+ h_dim : int
+ Hidden dim size.
+ out_dim : int
+ Output di... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/model_acc/bench_rgcn_ns.py |
Write docstrings for data processing functions | import itertools
import time
import dgl
import dgl.nn.pytorch as dglnn
import torch as th
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from dgl.nn import RelGraphConv
from torch.utils.data import DataLoader
from .. import utils
class EntityClas... | --- +++ @@ -15,6 +15,28 @@
class EntityClassify(nn.Module):
+ """Entity classification class for RGCN
+ Parameters
+ ----------
+ device : int
+ Device to run the layer.
+ num_nodes : int
+ Number of nodes.
+ h_dim : int
+ Hidden dim size.
+ out_dim : int
+ Output di... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/model_speed/bench_rgcn_homogeneous_ns.py |
Document this script properly | import argparse
import pickle
import time
import dgl
import dgl.function as fn
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, IterableDataset
from .. import utils
def _init_input_modules(g, ntype, textset, hidden_dims):
# We initia... | --- +++ @@ -67,6 +67,10 @@ disable_grad(self.emb)
def forward(self, x, length):
+ """
+ x: (batch_size, max_length) LongTensor
+ length: (batch_size,) LongTensor
+ """
x = self.emb(x).sum(1) / length.unsqueeze(1).float()
return self.proj(x)
@@ -104,6 +108,1... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/model_speed/bench_pinsage.py |
Add docstrings for production code | import itertools
import time
import traceback
import dgl
import dgl.nn.pytorch as dglnn
import torch as th
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from .. import utils
class RelGraphConvLayer(nn.Modu... | --- +++ @@ -15,6 +15,29 @@
class RelGraphConvLayer(nn.Module):
+ r"""Relational graph convolution layer.
+
+ Parameters
+ ----------
+ in_feat : int
+ Input feature size.
+ out_feat : int
+ Output feature size.
+ rel_names : list[str]
+ Relation names.
+ num_bases : int, op... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/model_speed/bench_rgcn_hetero_ns.py |
Generate docstrings for exported functions | import time
import dgl
import dgl.nn.pytorch as dglnn
import torch as th
import torch.multiprocessing as mp
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.utils.data import DataLoader
from .. import utils
class SAGE(nn.Module):
def __init__(
self, in_feats, ... | --- +++ @@ -38,6 +38,14 @@ return h
def inference(self, g, x, batch_size, device):
+ """
+ Inference with the GraphSAGE model on full neighbors (i.e. without neighbor sampling).
+ g : the entire graph.
+ x : the input of entire node set.
+
+ The inference code is writte... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/model_acc/bench_sage_ns.py |
Add docstrings including usage examples | from typing import List
import dgl.function as fn
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from dgl.nn import AvgPooling, SumPooling
from ogb.graphproppred.mol_encoder import AtomEncoder
def aggregate_mean(h):
return torch.mean(h, dim=1)
def aggregate_max(h):
re... | --- +++ @@ -10,22 +10,27 @@
def aggregate_mean(h):
+ """mean aggregation"""
return torch.mean(h, dim=1)
def aggregate_max(h):
+ """max aggregation"""
return torch.max(h, dim=1)[0]
def aggregate_min(h):
+ """min aggregation"""
return torch.min(h, dim=1)[0]
def aggregate_sum(h):... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/dglgo/dglgo/model/graph_encoder/pna.py |
Create docstrings for each class method | import dgl
import torch as th
import torch.nn as nn
class BaseRGCN(nn.Module):
def __init__(
self,
num_nodes,
h_dim,
out_dim,
num_rels,
num_bases,
num_hidden_layers=1,
dropout=0,
use_self_loop=False,
use_cuda=False,
):
sup... | --- +++ @@ -66,6 +66,25 @@
class RelGraphEmbedLayer(nn.Module):
+ r"""Embedding layer for featureless heterograph.
+ Parameters
+ ----------
+ dev_id : int
+ Device to run the layer.
+ num_nodes : int
+ Number of nodes.
+ node_tides : tensor
+ Storing the node type id for each... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/multigpu/rgcn_model.py |
Add concise docstrings to each method | import time
import dgl
import dgl.function as fn
import dgl.nn.pytorch as dglnn
import numpy as np
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from .. import utils
class NegativeSampler(object):
def __init__(self, g, k, neg_share=False):
self.wei... | --- +++ @@ -32,6 +32,9 @@
def load_subtensor(g, input_nodes, device):
+ """
+ Copys features and labels of a set of nodes onto GPU.
+ """
batch_inputs = g.ndata["features"][input_nodes].to(device)
return batch_inputs
@@ -63,6 +66,9 @@
def load_subtensor(g, input_nodes, device):
+ """
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/benchmarks/benchmarks/model_speed/bench_sage_unsupervised_ns.py |
Help me write clear docstrings | # pylint: disable=invalid-name
from __future__ import absolute_import
import ctypes
from ..base import _LIB, c_str, check_call
from ..runtime_ctypes import DGLArrayHandle
from .types import (
_return_handle,
_wrap_arg_func,
C_TO_PY_ARG_SWITCH,
RETURN_SWITCH,
)
DGLPyCapsuleDestructor = ctypes.CFUNCTYP... | --- +++ @@ -1,4 +1,5 @@ # pylint: disable=invalid-name
+"""Runtime NDArray api"""
from __future__ import absolute_import
import ctypes
@@ -62,10 +63,18 @@
class NDArrayBase(object):
+ """A simple Device/CPU Array object in runtime."""
__slots__ = ["handle", "is_view"]
# pylint: disable=no-member
... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/_ctypes/ndarray.py |
Generate documentation strings for clarity | # coding: utf-8
# pylint: disable=invalid-name, protected-access, too-many-branches, global-statement
from __future__ import absolute_import
import ctypes
import traceback
from numbers import Integral, Number
from ..base import _LIB, c_str, check_call, string_types
from ..object_generic import convert_to_object, Obje... | --- +++ @@ -1,5 +1,6 @@ # coding: utf-8
# pylint: disable=invalid-name, protected-access, too-many-branches, global-statement
+"""Function configuration API."""
from __future__ import absolute_import
import ctypes
@@ -28,6 +29,7 @@
def _ctypes_free_resource(rhandle):
+ """callback to free resources when it ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/_ctypes/function.py |
Generate docstrings for this script | from __future__ import absolute_import
import ctypes
from ..base import _LIB, c_str, check_call
from ..object_generic import _set_class_object_base
from .types import (
_wrap_arg_func,
C_TO_PY_ARG_SWITCH,
DGLValue,
RETURN_SWITCH,
TypeCode,
)
ObjectHandle = ctypes.c_void_p
__init_by_constructor__ ... | --- +++ @@ -1,3 +1,4 @@+"""ctypes object API."""
from __future__ import absolute_import
import ctypes
@@ -20,10 +21,12 @@
def _register_object(index, cls):
+ """register object class in python"""
OBJECT_TYPE[index] = cls
def _return_object(x):
+ """Construct a object object from the given DGLVal... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/_ctypes/object.py |
Add docstrings including usage examples | # pylint: disable=invalid-name, unused-import
from __future__ import absolute_import
import ctypes
import sys
import numpy as np
from .base import _FFI_MODE, _LIB, c_array, c_str, check_call, string_types
from .runtime_ctypes import (
dgl_shape_index_t,
DGLArray,
DGLArrayHandle,
DGLContext,
DGLDa... | --- +++ @@ -1,4 +1,5 @@ # pylint: disable=invalid-name, unused-import
+"""Runtime NDArray api"""
from __future__ import absolute_import
import ctypes
@@ -50,6 +51,32 @@
def context(dev_type, dev_id=0):
+ """Construct a DGL context with given device type and id.
+
+ Parameters
+ ----------
+ dev_type... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/ndarray.py |
Insert docstrings into my code | # pylint: disable=unused-import
from __future__ import absolute_import
from numbers import Integral, Number
from .. import _api_internal
from .base import string_types
# Object base class
_CLASS_OBJECT_BASE = None
def _set_class_object_base(cls):
global _CLASS_OBJECT_BASE
_CLASS_OBJECT_BASE = cls
class O... | --- +++ @@ -1,3 +1,4 @@+"""Common implementation of Object generic related logic"""
# pylint: disable=unused-import
from __future__ import absolute_import
@@ -16,12 +17,26 @@
class ObjectGeneric(object):
+ """Base class for all classes that can be converted to object."""
def asobject(self):
+ "... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/object_generic.py |
Generate consistent documentation across files | # pylint: disable=unused-import
from __future__ import absolute_import
import ctypes
import sys
from .. import _api_internal
from .base import _FFI_MODE, _LIB, c_str, check_call, py_str
from .object_generic import convert_to_object, ObjectGeneric
# pylint: disable=invalid-name
IMPORT_EXCEPT = RuntimeError if _FFI_MO... | --- +++ @@ -1,3 +1,4 @@+"""Object namespace"""
# pylint: disable=unused-import
from __future__ import absolute_import
@@ -24,10 +25,18 @@
def _new_object(cls):
+ """Helper function for pickle"""
return cls.__new__(cls)
class ObjectBase(_ObjectBase):
+ """ObjectBase is the base class of all DGL C... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/object.py |
Please document this code using docstrings | # coding: utf-8
# pylint: disable=invalid-name
from __future__ import absolute_import
import ctypes
import logging
import os
import sys
import numpy as np
from . import libinfo
# ----------------------------
# library loading
# ----------------------------
if sys.version_info[0] == 3:
string_types = (str,)
... | --- +++ @@ -1,5 +1,6 @@ # coding: utf-8
# pylint: disable=invalid-name
+"""ctypes library and helper functions """
from __future__ import absolute_import
import ctypes
@@ -27,11 +28,13 @@
class DGLError(Exception):
+ """Error thrown by DGL function"""
pass # pylint: disable=unnecessary-pass
def... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/base.py |
Add docstrings to improve collaboration | # pylint: disable=invalid-name, unused-import
from __future__ import absolute_import
import ctypes
from .base import _FFI_MODE, _LIB, check_call
from .runtime_ctypes import DGLStreamHandle
def to_dgl_stream_handle(cuda_stream):
return ctypes.c_void_p(cuda_stream.cuda_stream)
def _dgl_get_stream(ctx):
curr... | --- +++ @@ -1,4 +1,7 @@ # pylint: disable=invalid-name, unused-import
+"""Runtime stream APIs which are mainly for internal test use only.
+For applications, please use PyTorch's stream management, of which DGL is aware.
+"""
from __future__ import absolute_import
import ctypes
@@ -8,14 +11,36 @@
def to_dgl_str... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/streams.py |
Add docstrings to incomplete code | # pylint: disable=invalid-name, super-init-not-called
from __future__ import absolute_import
import ctypes
import json
import numpy as np
from .. import _api_internal
from .base import _LIB, check_call
dgl_shape_index_t = ctypes.c_int64
class TypeCode(object):
INT = 0
UINT = 1
FLOAT = 2
HANDLE = ... | --- +++ @@ -1,3 +1,4 @@+"""Common runtime ctypes."""
# pylint: disable=invalid-name, super-init-not-called
from __future__ import absolute_import
@@ -13,6 +14,7 @@
class TypeCode(object):
+ """Type code used in API calls"""
INT = 0
UINT = 1
@@ -32,6 +34,7 @@
class DGLByteArray(ctypes.Structur... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/runtime_ctypes.py |
Write docstrings for this repository | # pylint: disable= invalid-name
from __future__ import absolute_import
from . import backend as F, ndarray as nd
from ._ffi.function import _init_api
from .base import DGLError
def infer_broadcast_shape(op, shp1, shp2):
pad_shp1, pad_shp2 = shp1, shp2
if op == "dot":
if shp1[-1] != shp2[-1]:
... | --- +++ @@ -1,3 +1,4 @@+"""Module for sparse matrix operators."""
# pylint: disable= invalid-name
from __future__ import absolute_import
@@ -7,6 +8,29 @@
def infer_broadcast_shape(op, shp1, shp2):
+ r"""Check the shape validity, and infer the output shape given input shape and operator.
+ Note the both :a... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_sparse_ops.py |
Write documentation strings for class attributes | import mxnet as mx
import numpy as np
from mxnet import nd
from ..._sparse_ops import (
_bwd_segment_cmp,
_csrmask,
_csrmm,
_csrsum,
_gsddmm,
_gspmm,
_scatter_add,
_segment_reduce,
)
from ...base import ALL, dgl_warning, is_all
from ...heterograph_index import create_unitgraph_from_csr... | --- +++ @@ -36,6 +36,7 @@
def _scatter_nd(index, src, n_rows):
+ """Similar to PyTorch's scatter nd on first dimension."""
assert index.shape == src.shape
dgl_warning("MXNet do not support scatter_add, fallback to numpy.")
ctx = context(src)
@@ -68,6 +69,7 @@
def _gather_nd(index, src):
+ "... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/backend/mxnet/sparse.py |
Document functions with clear intent | # pylint: disable=invalid-name, unused-import
from __future__ import absolute_import
import ctypes
import sys
from .base import _FFI_MODE, _LIB, c_str, check_call, py_str, string_types
IMPORT_EXCEPT = RuntimeError if _FFI_MODE == "cython" else ImportError
try:
# pylint: disable=wrong-import-position
if _FFI... | --- +++ @@ -1,4 +1,5 @@ # pylint: disable=invalid-name, unused-import
+"""Function namespace."""
from __future__ import absolute_import
import ctypes
@@ -39,11 +40,34 @@
class Function(_FunctionBase):
+ """The PackedFunc object.
+
+ Function plays an key role to bridge front and backend in DGL.
+ Funct... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/_ffi/function.py |
Document this module using docstrings | # Copyright (c) 2022, NVIDIA Corporation
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unl... | --- +++ @@ -1,3 +1,4 @@+"""API wrapping HugeCTR gpu_cache."""
# Copyright (c) 2022, NVIDIA Corporation
# All rights reserved.
#
@@ -21,6 +22,7 @@
class GPUCache(object):
+ """High-level wrapper for GPU embedding cache"""
def __init__(self, num_items, num_feats, idtype=F.int64):
assert id... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/cuda/gpu_cache.py |
Add verbose docstrings with examples | import numpy as np
import tensorflow as tf
from ..._sparse_ops import (
_bwd_segment_cmp,
_csrmask,
_csrmm,
_csrsum,
_gsddmm,
_gspmm,
_scatter_add,
_segment_reduce,
)
from ...base import ALL, is_all
from ...heterograph_index import create_unitgraph_from_csr
from .tensor import asnumpy,... | --- +++ @@ -82,6 +82,20 @@
def _reduce_grad(grad, shape):
+ """Reduce gradient on the broadcast dimension
+ If there is broadcast in forward pass, gradients need to be reduced on
+ broadcast dimension. This function checks the input tensor shape and
+ gradient shape and perform the reduction.
+ Param... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/backend/tensorflow/sparse.py |
Write clean docstrings for readability | import os
import numpy as np
from ..convert import graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url
class ActorDataset(DGLBuiltinDataset):
def __init__(
self, raw_dir=None, force_reload=False, verbose=True, transform=None
):
super(ActorDataset, self).__init__... | --- +++ @@ -1,3 +1,6 @@+"""
+Actor-only induced subgraph of the film-directoractor-writer network.
+"""
import os
import numpy as np
@@ -8,6 +11,49 @@
class ActorDataset(DGLBuiltinDataset):
+ r"""Actor-only induced subgraph of the film-directoractor-writer network
+ from `Social Influence Analysis in Larg... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/actor.py |
Document functions with detailed explanations |
import json
import os
import numpy as np
from .. import backend as F
from ..base import DGLError
from ..convert import graph as create_dgl_graph
from ..sampling.negative import _calc_redundancy
from . import utils
from .dgl_dataset import DGLDataset
__all__ = ["AsNodePredDataset", "AsLinkPredDataset", "AsGraphPredD... | --- +++ @@ -1,3 +1,4 @@+"""Dataset adapters for re-purposing a dataset for a different kind of training task."""
import json
import os
@@ -15,6 +16,66 @@
class AsNodePredDataset(DGLDataset):
+ """Repurpose a dataset for a standard semi-supervised transductive
+ node prediction task.
+
+ The class conve... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/adapter.py |
Improve documentation using docstrings | import math
import os
import networkx as nx
import numpy as np
from .. import backend as F
from ..convert import from_networkx
from ..transforms import add_self_loop
from .dgl_dataset import DGLDataset
from .utils import load_graphs, makedirs, save_graphs
__all__ = ["MiniGCDataset"]
class MiniGCDataset(DGLDataset)... | --- +++ @@ -1,3 +1,4 @@+"""A mini synthetic dataset for graph classification benchmark."""
import math
import os
@@ -14,6 +15,71 @@
class MiniGCDataset(DGLDataset):
+ """The synthetic graph classification dataset class.
+
+ The datset contains 8 different types of graphs.
+
+ - class 0 : cycle graph
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/minigc.py |
Add professional docstrings to my codebase | # pylint: disable=not-callable
import numpy as np
from . import backend as F, function as fn, ops
from .base import ALL, dgl_warning, DGLError, EID, is_all, NID
from .frame import Frame
from .udf import EdgeBatch, NodeBatch
def is_builtin(func):
return isinstance(func, fn.BuiltinFunction)
def invoke_node_udf(g... | --- +++ @@ -1,3 +1,4 @@+"""Implementation for core graph computation."""
# pylint: disable=not-callable
import numpy as np
@@ -8,10 +9,33 @@
def is_builtin(func):
+ """Return true if the function is a DGL builtin function."""
return isinstance(func, fn.BuiltinFunction)
def invoke_node_udf(graph, ni... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/core.py |
Include argument descriptions in docstrings |
import torch
import torch.distributed as dist
def sparse_all_to_all_push(idx, value, partition):
if not dist.is_initialized() or dist.get_world_size() == 1:
return idx, value
assert (
dist.get_backend() == "nccl"
), "requires NCCL backend to communicate CUDA tensors."
perm, send_spli... | --- +++ @@ -1,9 +1,63 @@+"""API wrapping NCCL primitives."""
import torch
import torch.distributed as dist
def sparse_all_to_all_push(idx, value, partition):
+ """Perform an all-to-all-v operation, where by all processors send out
+ a set of indices and corresponding values. Indices and values,
+ corr... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/cuda/nccl.py |
Provide docstrings following PEP 257 |
###############################################################################
# Tensor, data type and context interfaces
def data_type_dict():
pass
def cpu():
pass
def tensor(data, dtype=None):
pass
def as_scalar(data):
pass
def get_preferred_sparse_format():
pass
def sparse_matrix(da... | --- +++ @@ -1,81 +1,368 @@+"""This file defines the unified tensor framework interface required by DGL.
+
+The principles of this interface:
+* There should be as few interfaces as possible.
+* The interface is used by DGL system so it is more important to have
+ clean definition rather than convenient usage.
+* Defau... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/backend/backend.py |
Auto-generate documentation strings for this file |
from collections import defaultdict
from collections.abc import Mapping
import networkx as nx
import numpy as np
from scipy.sparse import spmatrix
from . import backend as F, graph_index, heterograph_index, utils
from .base import DGLError, EID, ETYPE, NID, NTYPE
from .heterograph import combine_frames, DGLBlock, DG... | --- +++ @@ -1,3 +1,4 @@+"""Module for converting graph from/to other object."""
from collections import defaultdict
from collections.abc import Mapping
@@ -37,6 +38,116 @@ row_sorted=False,
col_sorted=False,
):
+ """Create a graph and return.
+
+ Parameters
+ ----------
+ data : graph data
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/convert.py |
Add verbose docstrings with examples | from __future__ import absolute_import as _abs
from . import _api_internal
from ._ffi.object import ObjectBase, register_object
from ._ffi.object_generic import convert_to_object
@register_object
class List(ObjectBase):
def __getitem__(self, i):
if isinstance(i, slice):
start = i.start if i.... | --- +++ @@ -1,3 +1,6 @@+"""Container data structures used in DGL runtime.
+reference: tvm/python/tvm/collections.py
+"""
from __future__ import absolute_import as _abs
from . import _api_internal
@@ -7,6 +10,13 @@
@register_object
class List(ObjectBase):
+ """List container of DGL.
+
+ You do not need to c... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/container.py |
Generate helpful docstrings for debugging | import datetime
import gzip
import os
import shutil
import numpy as np
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import check_sha1, download, load_graphs, makedirs, save_graphs
class BitcoinOTCDataset(DGLBuiltinDataset):
_url = "... | --- +++ @@ -1,3 +1,4 @@+""" BitcoinOTC dataset for fraud detection """
import datetime
import gzip
import os
@@ -12,6 +13,61 @@
class BitcoinOTCDataset(DGLBuiltinDataset):
+ r"""BitcoinOTC dataset for fraud detection
+
+ This is who-trusts-whom network of people who trade using Bitcoin on
+ a platform c... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/bitcoinotc.py |
Create docstrings for API functions | import enum
import inspect
import logging
from abc import ABC, abstractmethod, abstractstaticmethod
from pathlib import Path
from typing import Callable, Dict, List, Optional, Tuple, Union
import yaml
from dgl.dataloading.negative_sampler import GlobalUniform, PerSourceUniform
from numpydoc import docscrape
from pydan... | --- +++ @@ -248,6 +248,7 @@
class PipelineFactory:
+ """The factory class for creating executors"""
registry: Dict[str, PipelineBase] = {}
default_config_registry = {}
@@ -298,6 +299,7 @@
class ApplyPipelineFactory:
+ """The factory class for creating executors for inference"""
registry... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/dglgo/dglgo/utils/factory.py |
Write reusable docstrings | from collections.abc import Mapping
from . import backend as F, convert, utils
from .base import ALL, DGLError, EID, is_all, NID
from .heterograph import DGLGraph
from .heterograph_index import disjoint_union, slice_gidx
__all__ = ["batch", "unbatch", "slice_batch"]
def batch(graphs, ndata=ALL, edata=ALL):
if ... | --- +++ @@ -1,3 +1,4 @@+"""Utilities for batching/unbatching graphs."""
from collections.abc import Mapping
from . import backend as F, convert, utils
@@ -10,6 +11,142 @@
def batch(graphs, ndata=ALL, edata=ALL):
+ r"""Batch a collection of :class:`DGLGraph` s into one graph for more efficient
+ graph comp... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/batch.py |
Add docstrings that explain purpose and usage | from __future__ import absolute_import
import os, sys
import pickle as pkl
import networkx as nx
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import graph as dgl_graph
from ..utils import retry_method_with_fix
from .dgl_dataset import DGLBuiltinDataset
from .utils import ... | --- +++ @@ -30,6 +30,31 @@
class KnowledgeGraphDataset(DGLBuiltinDataset):
+ """KnowledgeGraph link prediction dataset
+
+ The dataset contains a graph depicting the connectivity of a knowledge
+ base. Currently, the knowledge bases from the
+ `RGCN paper <https://arxiv.org/pdf/1703.06103.pdf>`_ support... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/knowledge_graph.py |
Write docstrings for utility functions | import hashlib
import os
import pickle
import pandas as pd
from ogb.utils import smiles2graph as smiles2graph_OGB
from tqdm.auto import tqdm
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLDataset
from .utils import (
download,
extract_archive,
load_graphs... | --- +++ @@ -21,6 +21,94 @@
class PeptidesStructuralDataset(DGLDataset):
+ r"""Peptides structure dataset for the graph regression task.
+
+ DGL dataset of Peptides-struct in the LRGB benchmark which contains
+ 15,535 small peptides represented as their molecular graph (SMILES)
+ with 11 regression targe... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/lrgb.py |
Add docstrings including usage examples | import os
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs
class CLUSTERDataset(DGLBuiltinDataset):
def __init__(
self,
mode="train",
raw_dir=None,
force_reload=False,
verbose=False,
transform=None,
):
self._url =... | --- +++ @@ -1,3 +1,4 @@+""" CLUSTERDataset for inductive learning. """
import os
from .dgl_dataset import DGLBuiltinDataset
@@ -5,6 +6,64 @@
class CLUSTERDataset(DGLBuiltinDataset):
+ r"""CLUSTER dataset for semi-supervised clustering task.
+
+ Each graph contains 6 SBM clusters with sizes randomly select... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/cluster.py |
Replace inline comments with docstrings | from __future__ import absolute_import
import builtins
import numbers
import os
import mxnet as mx
import mxnet.ndarray as nd
import numpy as np
from ... import ndarray as dglnd
from ...function.base import TargetCode
from ...utils import version
if version.parse(mx.__version__) < version.parse("1.6.0"):
raise ... | --- +++ @@ -73,6 +73,11 @@
def get_preferred_sparse_format():
+ """Get the preferred sparse matrix format supported by the backend.
+
+ Different backends have their preferred backend. This info is useful when
+ constructing a sparse matrix.
+ """
return "csr"
@@ -524,6 +529,12 @@
def sync(... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/backend/mxnet/tensor.py |
Auto-generate documentation strings for this file | import json
import os
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import from_scipy
from ..transforms import reorder_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, generate_mask_tensor, load_graphs, save_graphs
class FlickrDataset(DGLBui... | --- +++ @@ -1,3 +1,4 @@+"""Flickr Dataset"""
import json
import os
@@ -12,6 +13,59 @@
class FlickrDataset(DGLBuiltinDataset):
+ r"""Flickr dataset for node classification from `GraphSAINT: Graph Sampling Based Inductive
+ Learning Method <https://arxiv.org/abs/1907.04931>`_
+
+ The task of this dataset... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/flickr.py |
Write Python docstrings for this snippet | from __future__ import absolute_import
import builtins
import numbers
import numpy as np
import tensorflow as tf
from ... import ndarray as nd
from ...function.base import TargetCode
from ...utils import version
if version.parse(tf.__version__) < version.parse("2.3.0"):
raise RuntimeError(
"DGL requires... | --- +++ @@ -1,3 +1,4 @@+"""Tensorflow backend implementation"""
from __future__ import absolute_import
import builtins
@@ -68,6 +69,11 @@
def get_preferred_sparse_format():
+ """Get the preferred sparse matrix format supported by the backend.
+
+ Different backends have their preferred backend. This info ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/backend/tensorflow/tensor.py |
Create Google-style docstrings for my code | from __future__ import absolute_import
import warnings
from ._ffi.base import DGLError # pylint: disable=unused-import
from ._ffi.function import _init_internal_api
# A special symbol for selecting all nodes or edges.
ALL = "__ALL__"
# An alias for [:]
SLICE_FULL = slice(None, None, None)
# Reserved column names fo... | --- +++ @@ -1,3 +1,4 @@+"""Module for base types and utilities."""
from __future__ import absolute_import
import warnings
@@ -19,10 +20,12 @@
def is_internal_column(name):
+ """Return true if the column name is reversed by DGL."""
return name in _INTERNAL_COLUMNS
def is_all(arg):
+ """Return tru... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/base.py |
Create Google-style docstrings for my code | import os
import numpy as np
from .. import backend as F
from ..base import DGLError
from .dgl_dataset import DGLDataset
from .utils import load_graphs, save_graphs, Subset
class CSVDataset(DGLDataset):
META_YAML_NAME = "meta.yaml"
def __init__(
self,
data_path,
force_reload=False,... | --- +++ @@ -9,6 +9,64 @@
class CSVDataset(DGLDataset):
+ """Dataset class that loads and parses graph data from CSV files.
+
+ This class requires the following additional packages:
+
+ - pyyaml >= 5.4.1
+ - pandas >= 1.1.5
+ - pydantic >= 1.9.0
+
+ The parsed graph and feature data wi... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/csv_dataset.py |
Fully document this Python code with docstrings | from __future__ import absolute_import
import os
from collections import OrderedDict
import networkx as nx
import numpy as np
from .. import backend as F
from ..convert import from_networkx
from .dgl_dataset import DGLBuiltinDataset
from .utils import (
_get_dgl_url,
deprecate_property,
load_graphs,
... | --- +++ @@ -1,3 +1,7 @@+"""Tree-structured data.
+Including:
+ - Stanford Sentiment Treebank
+"""
from __future__ import absolute_import
import os
@@ -25,6 +29,86 @@
class SSTDataset(DGLBuiltinDataset):
+ r"""Stanford Sentiment Treebank dataset.
+
+ Each sample is the constituency tree of a sentence. T... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/tree.py |
Add docstrings to improve collaboration |
from __future__ import absolute_import
import os, sys
import pickle as pkl
import warnings
import networkx as nx
import numpy as np
import scipy.sparse as sp
from .. import backend as F, convert
from ..batch import batch as batch_graphs
from ..convert import from_networkx, graph as dgl_graph, to_networkx
from ..tr... | --- +++ @@ -1,3 +1,8 @@+"""Cora, citeseer, pubmed dataset.
+
+(lingfan): following dataset loading and preprocessing code from tkipf/gcn
+https://github.com/tkipf/gcn/blob/master/gcn/utils.py
+"""
from __future__ import absolute_import
@@ -41,6 +46,29 @@
class CitationGraphDataset(DGLBuiltinDataset):
+ r"""... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/citation_graph.py |
Write docstrings including parameters and return values | import os
import numpy as np
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_info, loadtxt, save_info
class GDELTDataset(DGLBuiltinDataset):
def __init__(
self,
mode="train",
raw_dir=No... | --- +++ @@ -1,3 +1,4 @@+""" GDELT dataset for temporal graph """
import os
import numpy as np
@@ -9,6 +10,66 @@
class GDELTDataset(DGLBuiltinDataset):
+ r"""GDELT dataset for event-based temporal graph
+
+ The Global Database of Events, Language, and Tone (GDELT) dataset.
+ This contains events happend... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/gdelt.py |
Include argument descriptions in docstrings | import math
import os
import random
import numpy as np
import numpy.random as npr
import scipy as sp
from .. import batch
from ..convert import from_scipy
from .dgl_dataset import DGLDataset
from .utils import load_graphs, load_info, save_graphs, save_info
def sbm(n_blocks, block_size, p, q, rng=None):
n = n_bl... | --- +++ @@ -1,3 +1,4 @@+"""Dataset for stochastic block model."""
import math
import os
import random
@@ -13,6 +14,26 @@
def sbm(n_blocks, block_size, p, q, rng=None):
+ """(Symmetric) Stochastic Block Model
+
+ Parameters
+ ----------
+ n_blocks : int
+ Number of blocks.
+ block_size : int... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/sbm.py |
Create documentation for each function signature | import os
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import graph as dgl_graph
from ..transforms import to_bidirected
from .dgl_dataset import DGLDataset
from .utils import _get_dgl_url, download
class QM9Dataset(DGLDataset):
def __init__(
self,
lab... | --- +++ @@ -1,3 +1,4 @@+"""QM9 dataset for graph property prediction (regression)."""
import os
import numpy as np
@@ -12,6 +13,98 @@
class QM9Dataset(DGLDataset):
+ r"""QM9 dataset for graph property prediction (regression)
+
+ This dataset consists of 130,831 molecules with 12 regression targets.
+ N... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/qm9.py |
Document this code for team use | from __future__ import absolute_import
import errno
import hashlib
import os
import pickle
import sys
import warnings
import networkx.algorithms as A
import numpy as np
import requests
from tqdm.auto import tqdm
from .. import backend as F
from .graph_serialize import load_graphs, load_labels, save_graphs
from .ten... | --- +++ @@ -1,3 +1,4 @@+"""Dataset utilities."""
from __future__ import absolute_import
import errno
@@ -51,6 +52,7 @@
def _get_dgl_url(file_url):
+ """Get DGL online url for download."""
dgl_repo_url = "https://data.dgl.ai/"
repo_url = os.environ.get("DGL_REPO", dgl_repo_url)
if repo_url[-1] ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/utils.py |
Generate docstrings with parameter types | from __future__ import absolute_import
import os
from .. import backend as F
from .._ffi.function import _init_api
from .._ffi.object import ObjectBase, register_object
from ..base import dgl_warning, DGLError
from ..heterograph import DGLGraph
from .heterograph_serialize import save_heterographs
_init_api("dgl.data... | --- +++ @@ -1,3 +1,4 @@+"""For Graph Serialization"""
from __future__ import absolute_import
import os
@@ -16,6 +17,14 @@
@register_object("graph_serialize.StorageMetaData")
class StorageMetaData(ObjectBase):
+ """StorageMetaData Object
+ attributes available:
+ num_graph [int]: return numbers of grap... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/graph_serialize.py |
Generate docstrings for exported functions | import json
import os
import numpy as np
import scipy.sparse as sp
from .. import backend as F
from ..convert import from_scipy
from ..transforms import reorder_graph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, generate_mask_tensor, load_graphs, save_graphs
class YelpDataset(DGLBuilt... | --- +++ @@ -1,3 +1,4 @@+"""Yelp Dataset"""
import json
import os
@@ -12,6 +13,58 @@
class YelpDataset(DGLBuiltinDataset):
+ r"""Yelp dataset for node classification from `GraphSAINT: Graph Sampling Based Inductive
+ Learning Method <https://arxiv.org/abs/1907.04931>`_
+
+ The task of this dataset is ca... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/yelp.py |
Help me document legacy Python code | import os
import numpy as np
from scipy import io
from .. import backend as F
from ..convert import heterograph
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs, save_graphs
class FraudDataset(DGLBuiltinDataset):
file_urls = {
"yelp": "dataset/FraudYelp.zip",
... | --- +++ @@ -1,3 +1,5 @@+"""Fraud Dataset
+"""
import os
import numpy as np
@@ -10,6 +12,71 @@
class FraudDataset(DGLBuiltinDataset):
+ r"""Fraud node prediction dataset.
+
+ The dataset includes two multi-relational graphs extracted from Yelp and Amazon
+ where nodes represent fraudulent reviews or fra... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/fraud.py |
Add docstrings for production code | import ast
import os
from typing import Callable, List, Optional
import numpy as np
import pandas as pd
import pydantic as dt
import yaml
from .. import backend as F
from ..base import dgl_warning, DGLError
from ..convert import heterograph as dgl_heterograph
class MetaNode(dt.BaseModel):
file_name: str
nt... | --- +++ @@ -13,6 +13,7 @@
class MetaNode(dt.BaseModel):
+ """Class of node_data in YAML. Internal use only."""
file_name: str
ntype: Optional[str] = "_V"
@@ -21,6 +22,7 @@
class MetaEdge(dt.BaseModel):
+ """Class of edge_data in YAML. Internal use only."""
file_name: str
etype: Opt... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/csv_dataset_base.py |
Write documentation strings for class attributes | import abc
import itertools
import os
import re
from collections import OrderedDict
import networkx as nx
import numpy as np
import dgl
import dgl.backend as F
from .dgl_dataset import DGLBuiltinDataset
from .utils import (
_get_dgl_url,
generate_mask_tensor,
idx2mask,
load_graphs,
load_info,
... | --- +++ @@ -1,3 +1,8 @@+"""RDF datasets
+Datasets from "A Collection of Benchmark Datasets for
+Systematic Evaluations of Machine Learning on
+the Semantic Web"
+"""
import abc
import itertools
import os
@@ -32,6 +37,14 @@
class Entity:
+ """Class for entities
+ Parameters
+ ----------
+ id : str
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/rdf.py |
Replace inline comments with docstrings | from __future__ import absolute_import
from .. import backend as F
from .._ffi.function import _init_api
from ..ndarray import NDArray
__all__ = ["save_tensors", "load_tensors"]
_init_api("dgl.data.tensor_serialize")
def save_tensors(filename, tensor_dict):
nd_dict = {}
is_empty_dict = len(tensor_dict) == ... | --- +++ @@ -1,3 +1,4 @@+"""For Tensor Serialization"""
from __future__ import absolute_import
from .. import backend as F
@@ -10,6 +11,21 @@
def save_tensors(filename, tensor_dict):
+ """
+ Save dict of tensors to file
+
+ Parameters
+ ----------
+ filename : str
+ File name to store dict ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/tensor_serialize.py |
Document this module using docstrings | import json
import os
import networkx as nx
import numpy as np
from networkx.readwrite import json_graph
from .. import backend as F
from ..convert import from_networkx
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, load_graphs, load_info, save_graphs, save_info
class PPIDataset(DGLBuil... | --- +++ @@ -1,3 +1,4 @@+""" PPIDataset for inductive learning. """
import json
import os
@@ -12,6 +13,59 @@
class PPIDataset(DGLBuiltinDataset):
+ r"""Protein-Protein Interaction dataset for inductive node classification
+
+ A toy Protein-Protein Interaction network dataset. The dataset contains
+ 24 g... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/ppi.py |
Generate helpful docstrings for debugging | import itertools
import json
import os
import numpy as np
from .. import backend as F
from ..convert import graph
from ..transforms import reorder_graph, to_bidirected
from .dgl_dataset import DGLBuiltinDataset
from .utils import _get_dgl_url, generate_mask_tensor, load_graphs, save_graphs
class WikiCSDataset(DGLBu... | --- +++ @@ -1,3 +1,4 @@+"""Wiki-CS Dataset"""
import itertools
import json
import os
@@ -12,6 +13,67 @@
class WikiCSDataset(DGLBuiltinDataset):
+ r"""Wiki-CS is a Wikipedia-based dataset for node classification from `Wiki-CS: A Wikipedia-Based
+ Benchmark for Graph Neural Networks <https://arxiv.org/abs/20... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/wikics.py |
Document all public functions with docstrings |
from __future__ import absolute_import
import abc
import hashlib
import os
import traceback
from ..utils import retry_method_with_fix
from .utils import download, extract_archive, get_download_dir, makedirs
class DGLDataset(object):
def __init__(
self,
name,
url=None,
raw_dir=N... | --- +++ @@ -1,3 +1,5 @@+"""Basic DGL Dataset
+"""
from __future__ import absolute_import
@@ -11,6 +13,71 @@
class DGLDataset(object):
+ r"""The basic DGL dataset for creating graph datasets.
+ This class defines a basic template class for DGL Dataset.
+ The following steps will be executed automatical... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/dgl_dataset.py |
Add docstrings to incomplete code | import os
from scipy import io
from .. import backend as F
from ..convert import graph as dgl_graph
from .dgl_dataset import DGLDataset
from .utils import check_sha1, download, load_graphs, save_graphs
class QM7bDataset(DGLDataset):
_url = (
"http://deepchem.io.s3-website-us-west-1.amazonaws.com/"
... | --- +++ @@ -1,3 +1,4 @@+"""QM7b dataset for graph property prediction (regression)."""
import os
from scipy import io
@@ -10,6 +11,61 @@
class QM7bDataset(DGLDataset):
+ r"""QM7b dataset for graph property prediction (regression)
+
+ This dataset consists of 7,211 molecules with 14 regression targets.
+ ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/qm7b.py |
Add detailed documentation for each class |
import os
import numpy as np
from .. import backend as F
from ..convert import graph as dgl_graph
from ..utils import retry_method_with_fix
from .dgl_dataset import DGLBuiltinDataset
from .utils import (
download,
extract_archive,
load_graphs,
load_info,
loadtxt,
save_graphs,
save_info,
)... | --- +++ @@ -1,3 +1,9 @@+"""Datasets used in How Powerful Are Graph Neural Networks?
+(chen jun)
+Datasets include:
+MUTAG, COLLAB, IMDBBINARY, IMDBMULTI, NCI1, PROTEINS, PTC, REDDITBINARY, REDDITMULTI5K
+https://github.com/weihua916/powerful-gnns/blob/master/dataset.zip
+"""
import os
@@ -19,6 +25,69 @@
class ... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/gindt.py |
Write beginner-friendly docstrings | from __future__ import absolute_import
from .. import backend as F
from .._ffi.function import _init_api
from .._ffi.object import ObjectBase, register_object
from ..container import convert_to_strmap
from ..frame import Frame
from ..heterograph import DGLGraph
_init_api("dgl.data.heterograph_serialize")
def tensor... | --- +++ @@ -1,3 +1,4 @@+"""For HeteroGraph Serialization"""
from __future__ import absolute_import
from .. import backend as F
@@ -11,6 +12,7 @@
def tensor_dict_to_ndarray_dict(tensor_dict):
+ """Convert dict[str, tensor] to StrMap[NDArray]"""
ndarray_dict = {}
for key, value in tensor_dict.items()... | https://raw.githubusercontent.com/dmlc/dgl/HEAD/python/dgl/data/heterograph_serialize.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.