请利用pytorch框架写一个最基础的图神经网络模型的代码
时间: 2023-09-04 10:04:01 浏览: 112
### 回答1:
示例代码:import torch
import torch.nn as nn# 定义输入与输出维度
input_dim = 784
output_dim = 10# 定义模型
model = nn.Sequential(
nn.Linear(input_dim, 32),
nn.ReLU(),
nn.Linear(32, output_dim),
nn.Softmax(dim=1)
)# 定义损失函数
criterion = nn.CrossEntropyLoss()# 定义优化器
optimizer = torch.optim.Adam(model.parameters())
### 回答2:
以下是使用PyTorch框架编写的一个基本的图神经网络(Graph Convolutional Network, GCN)模型的代码示例:
```python
import torch
import torch.nn as nn
import torch.nn.functional as F
class GCN(nn.Module):
def __init__(self, input_dim, hidden_dim, output_dim):
super(GCN, self).__init__()
self.linear1 = nn.Linear(input_dim, hidden_dim)
self.linear2 = nn.Linear(hidden_dim, output_dim)
self.activation = nn.ReLU()
def forward(self, adjacency_matrix, features):
# 第一层图卷积
hidden = self.linear1(torch.matmul(adjacency_matrix, features))
hidden = self.activation(hidden)
# 第二层图卷积
output = self.linear2(torch.matmul(adjacency_matrix, hidden))
output = self.activation(output)
return output
# 定义输入数据
adjacency_matrix = torch.tensor([[0, 1, 1], [1, 0, 1], [1, 1, 0]]) # 图的邻接矩阵
features = torch.tensor([[1, 0], [0, 1], [1, 1]]) # 图中每个节点的特征
# 定义模型,并进行前向传播
input_dim = features.shape[1]
hidden_dim = 16
output_dim = 8
model = GCN(input_dim, hidden_dim, output_dim)
predictions = model(adjacency_matrix, features)
print(predictions)
```
此代码示例实现了一个简单的GCN模型,包含两层图卷积层和ReLU激活函数。输入数据由邻接矩阵和节点特征组成,并通过模型的前向传播函数得到预测输出。请根据需要适当修改参数和模型结构。
### 回答3:
import torch
from torch import nn
from torch.nn import functional as F
from torch_geometric.nn import GCNConv
class GraphConvNet(nn.Module):
def __init__(self, num_features, num_classes):
super(GraphConvNet, self).__init__()
self.conv1 = GCNConv(num_features, 16)
self.conv2 = GCNConv(16, num_classes)
def forward(self, x, edge_index):
x = self.conv1(x, edge_index)
x = F.relu(x)
x = self.conv2(x, edge_index)
return torch.log_softmax(x, dim=1)
# 定义输入特征维度和目标类别数量(仅作示例)
num_features = 64
num_classes = 10
# 创建模型实例
model = GraphConvNet(num_features, num_classes)
# 定义输入数据(仅作示例)
x = torch.randn((100, num_features))
edge_index = torch.rand((2, 200)).long()
# 运行模型推理
logits = model(x, edge_index)
# 打印输出
print(logits)
阅读全文