Pytorch常用代码

import time
import torch
from torch import nn, optim
from torch.autograd import Variable
import sys
sys.path.append("..") 
import d2lzh_pytorch as d2l
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 本函数已保存在d2lzh_pytorch包中方便以后使用
class FlattenLayer(nn.Module):
    def __init__(self):
        super(FlattenLayer, self).__init__()
    def forward(self, x): # x shape: (batch, *, *, ...)
        return x.view(x.shape[0], -1)
    
class LeNet(nn.Module):
    def __init__(self):
        super(LeNet, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(1, 6, 5), # in_channels, out_channels, kernel_size
            nn.Sigmoid(),
            nn.MaxPool2d(2, 2), # kernel_size, stride
            nn.Conv2d(6, 16, 5),
            nn.Sigmoid(),
            nn.MaxPool2d(2, 2),
#             FlattenLayer()
        )
        self.fc = nn.Sequential(
            nn.Linear(16*4*4, 120),
            nn.Sigmoid(),
            nn.Linear(120, 84),
            nn.Sigmoid(),
            nn.Linear(84, 10)
        )
        
    def forward(self, img):
        feature = self.conv(img)
        output = self.fc(feature.view(img.shape[0], -1))
        return feature.size()

#     def forward(self, img):
#         feature = self.conv(img)
#         output = self.fc(feature.view(img.shape[0], -1))
#         return output.size()
net = LeNet()
data_input = Variable(torch.randn([256, 1, 28, 28])) # 这里假设输入图片是96x96
print(data_input.size())
net(data_input)

在这里插入图片描述
可解决卷积层后nn.Linear输入参数无法确定的问题

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
PyTorch中,有一些常用代码片段可以帮助我们进行深度学习任务。以下是一些常见的代码片段: 1. 定义网络模型: ```python import torch import torch.nn as nn class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.fc = nn.Linear(10, 5) def forward(self, x): x = self.fc(x) return x net = Net() ``` 在这个示例中,我们定义了一个简单的神经网络模型Net,它包含一个全连接层nn.Linear。我们可以使用这个模型来进行前向传播。 2. 数据加载: ```python import torch from torch.utils.data import DataLoader, Dataset class CustomDataset(Dataset): def __init__(self, data): self.data = data def __getitem__(self, index): x, y = self.data[index] return torch.tensor(x), torch.tensor(y) def __len__(self): return len(self.data) dataset = CustomDataset(data) dataloader = DataLoader(dataset, batch_size=32, shuffle=True) ``` 在这个示例中,我们定义了一个自定义的数据集CustomDataset,并使用DataLoader将数据集加载为批量大小为32的数据加载器。 3. 模型训练: ```python import torch import torch.optim as optim import torch.nn as nn criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9) for epoch in range(num_epochs): running_loss = 0.0 for inputs, labels in dataloader: optimizer.zero_grad() outputs = net(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() print(f"Epoch {epoch+1}: Loss = {running_loss/len(dataloader)}") ``` 在这个示例中,我们使用交叉熵损失函数nn.CrossEntropyLoss和随机梯度下降优化器optim.SGD来训练我们的模型。我们使用for循环迭代数据加载器中的批次,并在每个批次上进行前向传播、计算损失、反向传播和优化模型参数。 4. 模型保存和加载: ```python torch.save(net.state_dict(), 'model.pth') # 加载模型 model = Net() model.load_state_dict(torch.load('model.pth')) ``` 在这个示例中,我们使用torch.save将模型的状态字典保存到文件'model.pth'中,并使用model.load_state_dict加载模型的参数。 这些是PyTorch中一些常见的代码片段,可以帮助我们进行深度学习任务。需要根据具体任务的需求进行适当的修改和调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值