You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

t_model.rst 9.6 kB

4 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. .. _model_cn:
  2. AutoGL 模型
  3. ============
  4. 在AutoGL中,我们使用 ``model`` 和 ``automodel`` 类定义图神经网络模型,并让它们和超参数优化(hyper parameter optimization, HPO)模块兼容。
  5. 当前版本下,我们支持节点分类、图分类和链接预测三种任务任务,支持的具体模型如下:
  6. +----------------------+----------------------------+
  7. |任务 | 模型 |
  8. +======================+============================+
  9. |节点分类 | ``gcn``, ``gat``, ``sage`` |
  10. +----------------------+----------------------------+
  11. |图分类 | ``gin``, ``topk`` |
  12. +----------------------+----------------------------+
  13. |链接预测 | ``gcn``, ``gat``, ``sage`` |
  14. +----------------------+----------------------------+
  15. 自定义模型和自动模型
  16. ------------------
  17. 我们强烈建议您同时定义 ``model`` 类和 ``automodel`` 类。
  18. 其中, ``model`` 类来管理参数的初始化与模型前向传播逻辑, ``automodel`` 类组织超参数相关的搜索。
  19. ``automodel`` 在 ``solver`` 和 ``trainer`` 模块会被调用。
  20. 示例
  21. ^^^^
  22. 以一个用于节点分类任务的多层感知机(MLP)为例。您可以使用AutoGL来帮您找到最合适的超参数。
  23. 首先,您可以定义一个MLP模型,并假设所有超参数已经给定。
  24. .. code-block:: python
  25. import torch
  26. class MyMLP(torch.nn.Module):
  27. # 假定所有超参数可获得
  28. def __init__(self, args):
  29. super().__init__()
  30. in_channels, num_classes = args['in_channels'], args['num_classes']
  31. layer_num, dim = args['layer_num'], int(args['dim'])
  32. if layer_num == 1:
  33. ops = [torch.nn.Linear(in_channels, num_classes)]
  34. else:
  35. ops = [torch.nn.Linear(in_channels, dim)]
  36. for i in range(layer_num - 2):
  37. ops.append(torch.nn.Linear(dim, dim))
  38. ops.append(torch.nn.Linear(dim, num_classes))
  39. self.core = torch.nn.Sequential(*ops)
  40. # 必须利用forward函数定义模型的前向传播逻辑
  41. def forward(self, data):
  42. assert hasattr(data, 'x'), 'MLP only support graph data with features'
  43. x = data.x
  44. return torch.nn.functional.log_softmax(self.core(x))
  45. 接下来,您可以定义自动模型 ``automodel`` 类以更好管理您的超参数。
  46. 对于来自于数据集的参数如输入维度与输出维度,可以直接传入 ``automodel`` 类中的初始化函数中 ``__init__()`` 。
  47. 而对于需要搜索的其他超参数,需要自定义搜索空间。
  48. .. code-block:: python
  49. from autogl.module.model import BaseAutoModel
  50. # 定义自动模型类,需要从BaseAutoModel类继承
  51. class MyAutoMLP(BaseAutoModel):
  52. def __init__(self, num_features=None, num_classes=None, device=None, **args
  53. ):
  54. super().__init__(num_features, num_classes, device, **args)
  55. # (required) 需要定义搜索空间(包含超参数、超参数的类型以及搜索范围)
  56. self.space = [
  57. {'parameterName': 'layer_num', 'type': 'INTEGER', 'minValue': 1, 'maxValue': 5, 'scalingType': 'LINEAR'},
  58. {'parameterName': 'dim', 'type': 'INTEGER', 'minValue': 64, 'maxValue': 128, 'scalingType': 'LINEAR'}
  59. ]
  60. # 设置默认超参数
  61. self.hyper_parameters = {
  62. "layer_num": 2,
  63. "dim": 72,
  64. }
  65. # # (required) since we don't know the num_classes and num_features until we see the dataset,
  66. # # we cannot initialize the models when instantiated. the initialized will be set to False.
  67. # self.initialized = False
  68. # (required) instantiate the core MLP model using corresponding hyper-parameters
  69. def _initialize(self):
  70. # (required) you need to make sure the core model is named as `self.model`
  71. self.model = MyMLP({
  72. "in_channels": self.input_dimension,
  73. "num_classes": self.output_dimension,
  74. **self.hyper_parameters
  75. }
  76. ).to(self.device)
  77. 接着,只需要将定义好的自动图模型输入自动图分类任务的 ``solver`` 中,就可以利用它完成节点分类任务。
  78. 具体代码示例如下:
  79. .. code-block :: python
  80. from autogl.solver import AutoNodeClassifier
  81. solver = AutoNodeClassifier(graph_models=(MyAutoMLP(num_features, num_classes,device=torch.device('cuda')),))
  82. 图分类任务的模型定义和整个流程和节点分类任务相似。详情参考图分类模型的tutorial。
  83. 用于链接预测任务的模型
  84. ^^^^^^^^^^^^^^^^^^^^
  85. 对于链接预测任务,模型的定义在 ``forward()`` 函数中略有不同。
  86. 为了更好地和链接预测训练器 ``LinkPredictionTrainer`` 与自动链接预测器 ``AutoLinkPredictor`` 交互,您需要定义编码函数 ``lp_encode(self, data)`` 与解码函数 ``lp_decode(self, x, pos_edge_index, neg_edge_index)`` 。
  87. 用同样的多层感知机作为示例,如果您想要将其用于链接预测任务,那么您不必再定义 ``forward()`` 函数,而是定义 ``lp_encode(self, data)`` 与 ``lp_decode(self, x, pos_edge_index, neg_edge_index)`` 两个函数。具体代码示例如下:
  88. .. code-block:: python
  89. class MyMLPForLP(torch.nn.Module):
  90. def __init__(self, in_channels, layer_num, dim):
  91. super().__init__()
  92. ops = [torch.nn.Linear(in_channels, dim)]
  93. for i in range(layer_num - 1):
  94. ops.append(torch.nn.Linear(dim, dim))
  95. self.core = torch.nn.Sequential(*ops)
  96. # (required) 和trainer与solver模块交互
  97. def lp_encode(self, data):
  98. return self.core(data.x)
  99. # (required) 和trainer与solver模块交互
  100. def lp_decode(self, x, pos_edge_index, neg_edge_index):
  101. # 首先得到所有需要的正样本边与负样本边集合
  102. edge_index = torch.cat([pos_edge_index, neg_edge_index], dim=-1)
  103. # 利用点积计算logits,或者使用其他decode方法
  104. logits = (x[edge_index[0]] * x[edge_index[1]]).sum(dim=-1)
  105. return logits
  106. class MyAutoMLPForLP(MyAutoMLP):
  107. def initialize(self):
  108. self.model = MyMLPForLP(
  109. in_channels = self.num_features,
  110. layer_num = self.layer_num,
  111. dim = self.dim
  112. ).to(self.device)
  113. 支持采样的模型
  114. ^^^^^^^^^^^^^
  115. 为了高效地实现大规模图上表示学习,AutoGL目前支持使用节点级别(node-wise)的采样、层级别(layer-wise)的采样和子图级别(subgraph-wise)的采样等采样技术进行节点分类。
  116. 有关采样的更多信息,请参阅::ref:`trainer_cn`。
  117. 根据图神经网络中的消息传递机制,一个节点的表达由它多跳邻居构成的子图决定。
  118. 但是,节点的邻居数量随着神经网络层数的增加呈现指数级增长,计算并储存所有节点的表达会占用许多的计算资源。
  119. 因此,在得到节点表达时,我们可以在每层神经网络输入不同的采样后的子图以达到高效计算的目的。
  120. 以torch_geometric的data为例,一个图包含节点特征x和边集合edge_index,在AutoGL的采样技巧中,我们会为data提供edge_indexes属性以表示不同的图卷积层采样出来的不同子图。
  121. .. code-block:: python
  122. import autogl
  123. from autogl.module.model import ClassificationSupportedSequentialModel
  124. # 重新定义接收图作为输入的Linear类
  125. class Linear(torch.nn.Linear):
  126. def forward(self, data):
  127. return super().forward(data.x)
  128. class MyMLPSampling(ClassificationSupportedSequentialModel):
  129. def __init__(self, in_channels, num_classes, layer_num, dim):
  130. super().__init__()
  131. if layer_num == 1:
  132. ops = [Linear(in_channels, num_classes)]
  133. else:
  134. ops = [Linear(in_channels, dim)]
  135. for i in range(layer_num - 2):
  136. ops.append(Linear(dim, dim))
  137. ops.append(Linear(dim, num_classes))
  138. self.core = torch.nn.ModuleList(ops)
  139. # (required) 覆盖序列编码层sequential_encoding_layers(),和sampling交互
  140. @property
  141. def sequential_encoding_layers(self) -> torch.nn.ModuleList:
  142. return self.core
  143. # (required) define the encode logic of classification for sampling
  144. def cls_encode(self, data):
  145. if hasattr(data, 'edge_indexes'):
  146. # edge_indexes是由edge_index组成的列表,每个edge_index代表每层图卷积所使用的边
  147. edge_indexes = data.edge_indexes
  148. edge_weights = [None] * len(self.core) if getattr(data, 'edge_weights', None) is None else data.edge_weights
  149. else:
  150. # 默认edge_index和edge_weight是相同的
  151. edge_indexes = [data.edge_index] * len(self.core)
  152. edge_weights = [getattr(data, 'edge_weight', None)] * len(self.core)
  153. x = data.x
  154. for i in range(len(self.core)):
  155. data = autogl.data.Data(x=x, edge_index=edge_indexes[i])
  156. data.edge_weight = edge_weights[i]
  157. x = self.sequential_encoding_layers[i](data)
  158. return x
  159. def cls_decode(self, x):
  160. return torch.nn.functional.log_softmax(x)