pytorch(十七):多层感知机全连接曾

Posted zhangxianrong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了pytorch(十七):多层感知机全连接曾相关的知识,希望对你有一定的参考价值。

一、全连接层用pytorch定义

技术图片

 

 二、MLP举例

技术图片

 

 技术图片

 

 三、具体代码

class MLP(nn.Module):
    def __init__(self):
        super(MLP,self).__init__()
        
        self.model = nn.Sequential(
            nn.Linear(784,200),
            nn.ReLU(inplace = True),
            nn.Linear(200,200),
            nn.ReLU(inplace = True),
            nn.Linear(200,10),
            nn.ReLU(inplace = True)
        )
        
    def forward(self,x):
        x = self.model(x)
        
        return x

epochs = 3
learning_rate = 1e-2
batch_size = 64


train_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST(datasets/mnist_data,
                train=True,
                download=True,
                transform=torchvision.transforms.Compose([
                torchvision.transforms.ToTensor(),                       # 数据类型转化
                torchvision.transforms.Normalize((0.1307, ), (0.3081, )) # 数据归一化处理
    ])), batch_size=batch_size,shuffle=True)

test_loader = torch.utils.data.DataLoader(torchvision.datasets.MNIST(datasets/mnist_data/,
                train=False,
                download=True,
                transform=torchvision.transforms.Compose([
                torchvision.transforms.ToTensor(),
                torchvision.transforms.Normalize((0.1307, ), (0.3081, ))
    ])),batch_size=batch_size,shuffle=False)


net = MLP()
optimizer = optim.SGD(net.parameters(),lr = learning_rate)
criteon = nn.CrossEntropyLoss()

for epoch in range(epochs):
    for batch_idx,(data,target) in enumerate(train_loader):
        data = data.view(-1,28*28)
        logits = net(data)
        loss= criteon(logits,target)
        
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch_idx % 100 == 0:
            print(Train Epoch: {} [{}/{} ({:.0f}%)]	Loss: {:.6f}.format(
                epoch, batch_idx * len(data), len(train_loader.dataset),
                       100. * batch_idx / len(train_loader), loss.item()))


    test_loss = 0
    correct = 0
    for data, target in test_loader:
        data = data.view(-1, 28 * 28)
        logits = net(data)
        test_loss += criteon(logits, target).item()

        pred = logits.data.max(1)[1]
        correct += pred.eq(target.data).sum()

    test_loss /= len(test_loader.dataset)
    print(
Test set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)
.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

 

以上是关于pytorch(十七):多层感知机全连接曾的主要内容,如果未能解决你的问题,请参考以下文章

PyTorch如何实现多层全连接神经网络

动手学习pytorch——多层感知机

用pytorch实现多层感知机(MLP)(全连接神经网络FC)分类MNIST手写数字体的识别

Pytorch深度学习学习总结-3月1日(3.8-多层感知机

从头学pytorch 多层感知机及其实现

深度学习6. 多层感知机及PyTorch实现