dgl.DGLGraph.formats
- DGLGraph.formats(formats=None)[source]
获取具有指定允许的稀疏格式的克隆图,或查询稀疏格式的使用状态。
此 API 复制图结构和特征。
如果输入图有多个边类型,它们将具有相同的稀疏格式。
当
formats
不为 None 时,如果 formats 与当前图已创建的稀疏格式之间存在非空交集,则返回的克隆图只保留交集中的所有稀疏格式。如果交集为空,则将按照'coo' -> 'csr' -> 'csc'
的顺序选择一种稀疏格式进行创建。- 参数:
formats (str 或 str 列表 或 None) –
如果 formats 为 None,则返回稀疏格式的使用状态
否则,它可以是
'coo'
/'csr'
/'csc'
或它们的子列表,指定要使用的稀疏格式。
- 返回值:
如果 formats 为 None,结果将是一个记录稀疏格式使用状态的字典。
否则,将返回一个 DGLGraph,它是原始图的克隆,具有指定的允许稀疏格式
formats
。
- 返回类型:
示例
以下示例使用 PyTorch 后端。
>>> import dgl >>> import torch
同构图或具有单一边类型的异构图
>>> g = dgl.graph(([0, 0, 1], [2, 3, 2])) >>> g.ndata['h'] = torch.ones(4, 1) >>> # Check status of format usage. >>> g.formats() {'created': ['coo'], 'not created': ['csr', 'csc']} >>> # Get a clone of the graph with 'csr' format. >>> csr_g = g.formats('csr') >>> # Only allowed formats will be displayed in the status query. >>> csr_g.formats() {'created': ['csr'], 'not created': []} >>> # Features are copied as well. >>> csr_g.ndata['h'] tensor([[1.], [1.], [1.], [1.]])
具有多种边类型的异构图
>>> g = dgl.heterograph({ ... ('user', 'plays', 'game'): (torch.tensor([0, 1, 1, 2]), ... torch.tensor([0, 0, 1, 1])), ... ('developer', 'develops', 'game'): (torch.tensor([0, 1]), ... torch.tensor([0, 1])) ... }) >>> g.formats() {'created': ['coo'], 'not created': ['csr', 'csc']} >>> # Get a clone of the graph with 'csr' format. >>> csr_g = g.formats('csr') >>> # Only allowed formats will be displayed in the status query. >>> csr_g.formats() {'created': ['csr'], 'not created': []}
当 formats 与已创建的格式有交集时
>>> g = dgl.graph(([0, 0, 1], [2, 3, 2])) >>> g = g.formats(['coo', 'csr']) >>> g.create_formats_() >>> g.formats() {'created': ['coo', 'csr'], 'not created': []} >>> # Get a clone of the graph allowed formats 'csr' and 'csc'. >>> csr_csc_g = g.formats(['csr', 'csc']) >>> # Only the intersection 'csr' will be retained. >>> csr_csc_g.formats() {'created': ['csr'], 'not created': ['csc']}
当 formats 与已创建的格式没有交集时
>>> g = dgl.graph(([0, 0, 1], [2, 3, 2])) >>> g = g.formats('coo') >>> g.formats() {'created': ['coo'], 'not created': []} >>> # Get a clone of the graph allowed formats 'csr' and 'csc'. >>> csr_csc_g = g.formats(['csr', 'csc']) >>> # Since the intersection is empty, 'csr' will be created as it is >>> # first in the order of 'coo' -> 'csr' -> 'csc'. >>> csr_csc_g.formats() {'created': ['csr'], 'not created': ['csc']}