打印深度学习模型结构

要打印 PyTorch 深度学习模型的方法,可以使用多种方式来查看模型的结构、参数和属性。以下是几种常用的方法:

1. 使用 print(model)

直接打印模型对象可以查看模型的结构,包括每一层的类型和参数数量。

import torch
import torch.nn as nn

# 定义一个简单的模型
class SimpleModel(nn.Module):
    def __init__(self):
        super(SimpleModel, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, kernel_size=3, stride=1, padding=1)
        self.conv2 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)
        self.fc1 = nn.Linear(64 * 28 * 28, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = torch.relu(self.conv1(x))
        x = torch.relu(self.conv2(x))
        x = x.view(x.size(0), -1)
        x = torch.relu(self.fc1(x))
        x = self.fc2(x)
        return x

model = SimpleModel()

# 打印模型结构
print(model)
#输出示例
SimpleModel(
  (conv1): Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (conv2): Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (fc1): Linear(in_features=50176, out_features=128, bias=True)
  (fc2): Linear(in_features=128, out_features=10, bias=True)
)

2. 使用 summary 函数

torchsummary 库提供了 summary 函数,可以打印出模型的详细信息,包括每层的输出形状和参数数量。

from torchsummary import summary

model = SimpleModel().cuda()  # 确保模型在 GPU 上

# 打印模型总结信息
summary(model, (1, 28, 28))  # 输入尺寸为 (1, 28, 28)
#输出示例
----------------------------------------------------------------
        Layer (type)               Output Shape         Param #
================================================================
            Conv2d-1           [-1, 32, 28, 28]             320
            Conv2d-2           [-1, 64, 28, 28]          18,496
            Linear-3                  [-1, 128]       6,421,504
            Linear-4                   [-1, 10]           1,290
================================================================
Total params: 6,441,610
Trainable params: 6,441,610
Non-trainable params: 0
----------------------------------------------------------------

3. 使用 state_dict

state_dict 可以查看模型的所有参数(权重和偏置)。

# 打印模型的 state_dict
for param_tensor in model.state_dict():
    print(param_tensor, "\t", model.state_dict()[param_tensor].size())
#输出示例
conv1.weight 	 torch.Size([32, 1, 3, 3])
conv1.bias 	 torch.Size([32])
conv2.weight 	 torch.Size([64, 32, 3, 3])
conv2.bias 	 torch.Size([64])
fc1.weight 	 torch.Size([128, 50176])
fc1.bias 	 torch.Size([128])
fc2.weight 	 torch.Size([10, 128])
fc2.bias 	 torch.Size([10])

5. 查看模型的各层详细信息

通过迭代模型的子模块,可以查看每一层的详细信息。

# 打印每一层的详细信息
for name, layer in model.named_children():
    print(name, ":", layer)
#输出示例
conv1 : Conv2d(1, 32, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
conv2 : Conv2d(32, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
fc1 : Linear(in_features=50176, out_features=128, bias=True)
fc2 : Linear(in_features=128, out_features=10, bias=True)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用PyTorch训练深度学习模型的一般步骤如下: 1. 准备数据集:首先需要准备好训练数据和测试数据,可以使用PyTorch提供的数据加载工具,也可以自己编写代码读取数据。 2. 定义模型结构:使用PyTorch定义深度学习模型结构,可以使用已有的模型结构,也可以自己设计模型。 3. 定义损失函数:选择适合当前模型的损失函数,并定义计算方法。 4. 定义优化算法:选择适合当前模型的优化算法,并定义计算方法。 5. 训练模型:使用准备好的数据集、模型结构、损失函数和优化算法进行模型训练,通过迭代优化模型参数来提高模型性能。 6. 模型评估:使用测试数据对训练好的模型进行评估,可以计算准确率、召回率、F1值等指标。 7. 模型保存:保存训练好的模型,方便后续使用。 下面是一个简单的示例代码: ```python import torch import torch.nn as nn import torch.optim as optim # 准备数据集 train_dataset = ... test_dataset = ... # 定义模型结构 class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc1 = nn.Linear(10, 5) self.fc2 = nn.Linear(5, 2) def forward(self, x): x = self.fc1(x) x = torch.relu(x) x = self.fc2(x) return x net = Net() # 定义损失函数和优化算法 criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) # 训练模型 for epoch in range(10): running_loss = 0.0 for i, data in enumerate(train_dataset, 0): inputs, labels = data optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 1000 == 999: # 每1000个batch打印一次loss print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 1000)) running_loss = 0.0 print('Finished Training') # 模型评估 correct = 0 total = 0 with torch.no_grad(): for data in test_dataset: inputs, labels = data outputs = net(inputs) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() print('Accuracy of the network on the test images: %d %%' % ( 100 * correct / total)) # 模型保存 PATH = './model.pt' torch.save(net.state_dict(), PATH) ``` 以上代码展示了一个简单的分类任务模型的训练过程,具体步骤可以根据需求进行调整和修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值