PyTorch-卷积神经网络

时间:2024-03-07 14:38:29

# 定义 Convolution Network 模型

class Cnn(nn.Module):

    def __init__(self, in_dim, n_class):

        super(Cnn, self).__init__()

        self.conv = nn.Sequential(

            nn.Conv2d(in_dim, 6, 3, stride=1, padding=1),

            nn.ReLU(True),

            nn.MaxPool2d(2, 2),

            nn.Conv2d(6, 16, 5, stride=1, padding=0),

            nn.ReLU(True),

            nn.MaxPool2d(2, 2),

        )

        self.fc = nn.Sequential(

            nn.Linear(400, 120),

            nn.Linear(120, 84),

            nn.Linear(84, n_class)

        )

    def forward(self, x):

        out = self.conv(x)

        out = out.view(out.size(0), -1)

        out = self.fc(out)

        return out

model = Cnn(1, 10)  # 图片大小是28x28

use_gpu = torch.cuda.is_available()  # 判断是否有GPU加速

if use_gpu:

    model = model.cuda()

# 定义loss和optimizer

criterion = nn.CrossEntropyLoss()

optimizer = optim.SGD(model.parameters(), lr=learning_rate)