import torch import torch.nn.functional as F from torch_geometric.nn import GCNConv class GCN(torch.nn.Module): def __init__(self, in_channels, hidden_channels, out_channels): super(GCN, self).__init__() self.conv1 = GCNConv(in_channels, hidden_channels) self.conv2 = GCNConv(hidden_channels, out_channels) def forward(self, x, edge_index): # 第一层卷积 + ReLU x = F.relu(self.conv1(x, edge_index)) # 第二层卷积 + LogSoftmax x = self.conv2(x, edge_index) return F.log_softmax(x, dim=1) # 初始化模型 model = GCN(dataset.num_node_features, 16, dataset.num_classes) optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4)
时间: 2025-03-24 22:13:20 浏览: 40
### 定义和初始化基于 PyTorch Geometric 的 GCN 模型
在 PyTorch Geometric 中,定义和初始化一个图卷积网络(Graph Convolutional Network, GCN)模型可以通过继承 `torch.nn.Module` 并利用内置的 `GCNConv` 层来完成。以下是详细的说明以及代码示例。
#### 1. 图卷积网络的核心参数
当构建 GCN 模型时,通常需要指定以下几个核心参数:
- **num_nodes**: 图中节点的数量[^3]。
- **in_channels**: 输入特征的维度。
- **out_channels**: 输出特征的维度。
- **hidden_channels**: 隐藏层的特征维度。
- **num_layers**: 卷积层数量。
这些参数决定了模型的结构及其复杂度。
#### 2. 初始化策略
对于 GCN 模型的权重矩阵,可以采用多种初始化方式,例如 Xavier 初始化、正态分布初始化等[^2]。PyTorch 提供了便捷的方法来进行这种初始化。
#### 3. 归一化计算
为了提高收敛速度并防止梯度爆炸或消失,在 GCN 的前向传播过程中会涉及边索引 (`edge_index`) 和节点特征 (`x`) 的归一化处理[^4]。这一步骤通过调整邻接矩阵的幂次实现。
下面是完整的代码实现:
```python
import torch
from torch.nn import Linear
from torch_geometric.nn import GCNConv
from torch_geometric.utils import degree
class GCN(torch.nn.Module):
def __init__(self, num_features, hidden_channels, out_channels, num_layers=2, dropout=0.5):
super(GCN, self).__init__()
# 构建多层GCN架构
self.convs = torch.nn.ModuleList()
self.convs.append(GCNConv(num_features, hidden_channels)) # 第一层输入到隐藏层
for _ in range(num_layers - 2):
self.convs.append(GCNConv(hidden_channels, hidden_channels))
self.convs.append(GCNConv(hidden_channels, out_channels)) # 最后一层从隐藏层到输出
self.dropout = dropout
def forward(self, data):
x, edge_index = data.x, data.edge_index
# 前向传播过程
for i, conv in enumerate(self.convs[:-1]):
x = conv(x, edge_index)
x = torch.relu(x) # 使用ReLU激活函数
x = torch.dropout(x, p=self.dropout, training=self.training)
# 最后的卷积层不需要激活函数
x = self.convs[-1](x, edge_index)
return x
# 示例:创建一个具有两层的GCN模型
model = GCN(
num_features=16,
hidden_channels=32,
out_channels=7,
num_layers=2,
dropout=0.5
)
print(model)
```
上述代码展示了如何定义一个多层 GCN 模型,并设置了默认的超参数值。每一层都应用了 ReLU 激活函数以引入非线性特性[^5]。
#### 关于归一化的进一步解释
如果需要手动执行归一化,则可以在 `forward()` 方法之前加入以下逻辑:
```python
row, col = edge_index
deg = degree(col, x.size(0), dtype=x.dtype)
deg_inv_sqrt = deg.pow(-0.5)
deg_inv_sqrt[deg_inv_sqrt == float('inf')] = 0
norm = deg_inv_sqrt[row] * deg_inv_sqrt[col]
data.edge_weight = norm # 将归一化系数存储为属性
```
此部分代码实现了对邻接矩阵的对称归一化操作。
---
###
阅读全文
相关推荐


















