一键导入
dgl
DGL (Deep Graph Library) — graph construction, message passing, GNN layers, heterogeneous graphs, and batching for fraud detection on blockchain graphs
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
DGL (Deep Graph Library) — graph construction, message passing, GNN layers, heterogeneous graphs, and batching for fraud detection on blockchain graphs
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
HuggingFace ecosystem — transformers, datasets, huggingface_hub. Model loading, tokenization, training, and dataset handling.
Optuna hyperparameter optimization — study creation, samplers, pruners, storage, and best practices for ML tuning
Pydantic v2 and pydantic-settings — BaseModel, field validation, config structs, and BaseSettings for CLI/config management (replaces argparse.Namespace)
PyTorch Lightning — LightningModule, Trainer, callbacks, logging, and checkpointing patterns for deep learning training loops
基于 SOC 职业分类
| name | dgl |
| description | DGL (Deep Graph Library) — graph construction, message passing, GNN layers, heterogeneous graphs, and batching for fraud detection on blockchain graphs |
import dgl
import torch
# Homogeneous graph from edge lists
src = torch.tensor([0, 1, 2, 3])
dst = torch.tensor([1, 2, 3, 0])
g = dgl.graph((src, dst))
# Add node/edge features
g.ndata["feat"] = torch.randn(g.num_nodes(), 64)
g.edata["weight"] = torch.ones(g.num_edges())
# From networkx
import networkx as nx
nx_g = nx.DiGraph()
nx_g.add_edges_from([(0, 1), (1, 2)])
g = dgl.from_networkx(nx_g)
# Add self-loops (often needed for GCN)
g = dgl.add_self_loop(g)
# Ethereum: account -[sends]-> account, account -[creates]-> contract
g = dgl.heterograph({
("account", "sends", "account"): (src_acct, dst_acct),
("account", "creates", "contract"): (src_acct, dst_contract),
})
g.nodes["account"].data["feat"] = account_feats
g.edges["sends"].data["amount"] = tx_amounts
import dgl.function as fn
# Built-in aggregation (fast, fused CUDA kernels — prefer over UDF)
g.update_all(
fn.copy_u("h", "m"), # message: copy src node feat
fn.mean("m", "h_agg"), # reduce: mean over neighbors
)
h_new = g.ndata["h_agg"]
# Edge-weighted aggregation
g.edata["e"] = edge_weights
g.update_all(
fn.u_mul_e("h", "e", "m"), # message: h * edge_weight
fn.sum("m", "h_agg"),
)
# Custom UDF (slower, use only when built-ins don't cover it)
def message_fn(edges):
return {"m": edges.src["h"] * edges.data["w"]}
def reduce_fn(nodes):
return {"h": nodes.mailbox["m"].sum(dim=1)}
g.update_all(message_fn, reduce_fn)
from dgl.nn import GraphConv, GATConv, SAGEConv
# GCN
conv = GraphConv(in_feats=64, out_feats=128, norm="both", allow_zero_in_degree=True)
h = conv(g, g.ndata["feat"])
# GAT (multi-head attention)
gat = GATConv(64, 32, num_heads=4, feat_drop=0.1, attn_drop=0.1)
h = gat(g, g.ndata["feat"]) # shape: [N, num_heads, out_feats]
h = h.flatten(1) # shape: [N, num_heads * out_feats]
# GraphSAGE
sage = SAGEConv(64, 128, aggregator_type="mean")
h = sage(g, g.ndata["feat"])
from dgl.dataloading import NodeDataLoader, MultiLayerNeighborSampler
# 2-layer GNN: sample 15 neighbors at layer 2, 10 at layer 1
sampler = MultiLayerNeighborSampler([15, 10])
train_ids = torch.where(g.ndata["train_mask"])[0]
loader = NodeDataLoader(
g, train_ids, sampler,
batch_size=1024,
shuffle=True,
drop_last=False,
num_workers=4,
)
for input_nodes, output_nodes, blocks in loader:
# blocks: list of bipartite graphs, one per GNN layer
h = blocks[0].srcdata["feat"]
for i, (block, layer) in enumerate(zip(blocks, gnn_layers)):
h = layer(block, h)
loss = loss_fn(h, blocks[-1].dstdata["label"])
# Batch multiple graphs for training (e.g., transaction subgraphs)
graphs = [dgl.graph(...) for _ in range(batch_size)]
batched = dgl.batch(graphs)
# Unbatch
graphs_list = dgl.unbatch(batched)
# Readout (graph-level prediction)
import dgl
h_graph = dgl.mean_nodes(batched, "h") # [batch_size, feat_dim]
g = g.to("cuda") # move graph + all ndata/edata to GPU
g = g.to(torch.device("cuda:0"))
# In DataLoader: use device parameter (DGL >= 1.1)
loader = NodeDataLoader(..., device="cuda")
allow_zero_in_degree=True must be set for GCN/GAT when isolated nodes exist — otherwise raises an error silently giving wrong results in older versions.dgl.function message/reduce ops over UDFs — they use fused CUDA kernels and are 2–5× faster.MultiLayerNeighborSampler samples in reverse layer order; blocks[0] is the input layer, blocks[-1] contains output nodes..to("cuda") also moves all ndata/edata tensors — don't move them separately.dgl.nn.HeteroGraphConv to apply different convolutions per relation type.