Task06 基于图神经网络的图表征学习方法
1.1 基于图同构网络(GIN)的图表征网络的实现
基本思路:计算节点表征,对图上各个节点的表征做图池化,得到图的表征
图表征模块(GINGraphReprModule):
对图上每一个节点进行节点嵌入,得到节点表征
对节点表征做图池化,得到图表征
用一层线性变换对图表征转换为对图的预测
节点嵌入模块(GINNodeEmbeddingModule):
用AtomEcoder进行嵌入,得到第0层节点表征
逐层计算节点表征
感受野越大,节点i的表征最后能捕获到节点i的距离为num_layers的邻接节点的信息
图同构卷积层(GINConv):
将类别型边属性转换为边表征
消息传递、消息聚合、消息更新
AtomEncoder和BondEncoder:将节点属性和边属性分布映射到一个新空间,再对节点和边进行信息融合。
importtorchfromtorchimportnnfromtorch_geometric.nnimportglobal_add_pool,global_mean_pool,global_max_pool,GlobalAttention,Set2Setimporttorch.nn.functionalasFfromtorch_geometric.nnimportMessagePassingfromogb.graphproppred.mol_encoderimportBondEncoderfromogb.utils.featuresimportget_atom_feature_dims,get_bond_feature_dimsCopy to clipboardErrorCopied
classGINGraphPooling(nn.Module):def__init__(self,num_tasks=1,num_layers=5,emb_dim=300,residual=False,drop_ratio=0,JK="last",graph_pooling="sum"):"""GIN Graph Pooling Module
此模块首先采用GINNodeEmbedding模块对图上每一个节点做嵌入,然后对节点嵌入做池化得到图的嵌入,最后用一层线性变换得到图的最终的表示(graph representation)。
Args:
num_tasks (int, optional): number of labels to be predicted. Defaults to 1 (控制了图表示的维度,dimension of graph representation).
num_layers (int, optional): number of GINConv layers. Defaults to 5.
emb_dim (int, optional): dimension of node embedding. Defaults to 300.
residual (bool, optional): adding residual connection or not. Defaults to False.
drop_ratio (float, optional): dropout rate. Defaults to 0.
JK (str, optional): 可选的值为"last"和"sum"。选"last",只取最后一层的结点的嵌入,选"sum"对各层的结点的嵌入求和。Defaults to "last".
graph_pooling (str, optional): pooling method of node embedding. 可选的值为"sum","mean","max","attention"和"set2set"。 Defaults to "sum".
Out:
graph representation
"""super(GINGraphPooling,self).__init__()self.num_layers=num_layers self.drop_ratio=drop_ratio self.JK=JK self.emb_dim=emb_dim self.num_tasks=num_tasksifself.num_layers<2:raiseValueError("Number of GNN layers must be greater than 1.")# 对图上的每个节点进行节点嵌入self.gnn_node=GINNodeEmbedding(num_layers,emb_dim,JK=JK,drop_ratio=drop_ratio,residual=residual)# Pooling function to generate whole-graph embeddingsifgraph_pooling=="sum":self.pool=global_add_poolelifgraph_pooling=="mean":self.pool=global_mean_poolelifgraph_pooling=="max":self.pool=global_max_poolelifgraph_pooling=="attention":self.pool=GlobalAttention(gate_nn=nn.Sequential(nn.Linear(emb_dim,emb_dim),nn.BatchNorm1d(emb_dim),nn.ReLU(),nn.Linear(emb_dim,1)))elifgraph_pooling=="set2set":self.pool=Set2Set(emb_dim,processing_steps=2)else:raiseValueError("Invalid graph pooling type.")ifgraph_pooling=="set2set":self.graph_pred_linear=nn.Linear(2*self.emb_dim,self.num_tasks)else:self.graph_pred_linear=nn.Linear(self.emb_dim,self.num_tasks)defforward(self,batched_data):h_node=self.gnn_node(batched_data)h_graph=self.pool(h_node,batched_data.batch)# 一层线性变换,对图表征转换为对图的预测output=self.graph_pred_linear(h_graph)ifself.training:returnoutputelse:# At inference time, relu is applied to output to ensure positivityreturntorch.clamp(output,min=0,max=50)Copy to clipboardErrorCopied
classGINNodeEmbedding(torch.nn.Module):"""
Output:
node representations
"""def__init__(self,num_layers,emb_dim,drop_ratio=0.5,JK="last",residual=False):"""GIN Node Embedding Module
采用多层GINConv实现图上结点的嵌入。
"""super(GINNodeEmbedding,self).__init__()self.num_layers=num_layers self.drop_ratio=drop_ratio self.JK=JK# add residual connection or notself.residual=residualifself.num_layers<2:raiseValueError("Number of GNN layers must be greater than 1.")self.atom_encoder=AtomEncoder(emb_dim)# List of GNNsself.convs=torch.nn.ModuleList()self.batch_norms=torch.nn.ModuleList()forlayerinrange(num_layers):self.convs.append(GINConv(emb_dim))self.batch_norms.append(torch.nn.BatchNorm1d(emb_dim))defforward(self,batched_data):x,edge_index,edge_attr=batched_data.x,batched_data.edge_index,batched_data.edge_attr# computing input node embedding# 先将类别型原子属性转化为原子嵌入,得到第0层节点表征h_list=[self.atom_encoder(x)]# 逐层计算节点表征forlayerinrange(self.num_layers):h=self.convs[layer](h_list[layer],edge_index,edge_attr)h=self.batch_norms[layer](h)iflayer==self.num_layers-1:# remove relu for the last layerh=F.dropout(h,self.drop_ratio,training=self.training)else:h=F.dropout(F.relu(h),self.drop_ratio,training=self.training)ifself.residual:h+=h_list[layer]# 得到全部节点表征h_list.append(h)# Different implementations of Jk-concatifself.JK=="last":node_representation=h_list[-1]elifself.JK=="sum":node_representation=0forlayerinrange(self.num_layers+1):node_representation+=h_list[layer]returnnode_representationCopy to clipboardErrorCopied
classGINConv(MessagePassing):def__init__(self,emb_dim):'''
emb_dim (int): node embedding dimensionality
'''super(GINConv,self).__init__(aggr="add")self.mlp=nn.Sequential(nn.Linear(emb_dim,emb_dim),nn.BatchNorm1d(emb_dim),nn.ReLU(),nn.Linear(emb_dim,emb_dim))self.eps=nn.Parameter(torch.Tensor([0]))self.bond_encoder=BondEncoder(emb_dim=emb_dim)defforward(self,x,edge_index,edge_attr):edge_embedding=self.bond_encoder(edge_attr)# 先将类别型边属性转换为边嵌入out=self.mlp((1+self.eps)*x+self.propagate(edge_index,x=x,edge_attr=edge_embedding))returnoutdefmessage(self,x_j,edge_attr):returnF.relu(x_j+edge_attr)defupdate(self,aggr_out):returnaggr_outCopy to clipboardErrorCopied
full_atom_feature_dims=get_atom_feature_dims()full_bond_feature_dims=get_bond_feature_dims()classAtomEncoder(torch.nn.Module):"""该类用于对原子属性做嵌入。
记`N`为原子属性的维度,则原子属性表示为`[x1, x2, ..., xi, xN]`,其中任意的一维度`xi`都是类别型数据。full_atom_feature_dims[i]存储了原子属性`xi`的类别数量。
该类将任意的原子属性`[x1, x2, ..., xi, xN]`转换为原子的嵌入`x_embedding`(维度为emb_dim)。
"""def__init__(self,emb_dim):super(AtomEncoder,self).__init__()self.atom_embedding_list=torch.nn.ModuleList()fori,diminenumerate(full_atom_feature_dims):emb=torch.nn.Embedding(dim,emb_dim)# 不同维度的属性用不同的Embedding方法torch.nn.init.xavier_uniform_(emb.weight.data)self.atom_embedding_list.append(emb)defforward(self,x):x_embedding=0# 节点的不同属性融合foriinrange(x.shape[1]):x_embedding+=self.atom_embedding_list[i](x[:,i])returnx_embeddingclassBondEncoder(torch.nn.Module):def__init__(self,emb_dim):super(BondEncoder,self).__init__()self.bond_embedding_list=torch.nn.ModuleList()fori,diminenumerate(full_bond_feature_dims):emb=torch.nn.Embedding(dim,emb_dim)torch.nn.init.xavier_uniform_(emb.weight.data)self.bond_embedding_list.append(emb)defforward(self,edge_attr):bond_embedding=0# 边的不同属性融合foriinrange(edge_attr.shape[1]):bond_embedding+=self.bond_embedding_list[i](edge_attr[:,i])returnbond_embedding