pytorch 打印模型结构
时间: 2023-07-19 19:28:44 浏览: 72
在 PyTorch 中,可以通过打印模型对象,来显示模型的结构。具体代码如下所示:
```python
import torch
import torch.nn as nn
# 定义一个简单的模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 创建一个模型对象
net = Net()
# 打印模型结构
print(net)
```
运行上述代码,就可以打印出模型的结构。输出结果如下所示:
```
Net(
(conv1): Conv2d(3, 6, kernel_size=(5, 5), stride=(1, 1))
(pool): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
(conv2): Conv2d(6, 16, kernel_size=(5, 5), stride=(1, 1))
(fc1): Linear(in_features=400, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
```
从输出结果可以看出,模型由 Conv2d、MaxPool2d、Linear 等模块组成,每个模块的输入和输出特征维度也都有相应的描述。
阅读全文