8-多层感知机

import torch
from torch import nn
from d2l import torch as d2l

batch_size = 256

# 准备数据
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)

# 构造模型
net = nn.Sequential(nn.Flatten(),
                    nn.Linear(784, 256),
                    nn.ReLU(),
                    nn.Linear(256, 10))

def init_weights(m):
    if isinstance(m, nn.Linear):
        nn.init.normal_(m.weight, 0, 0.01)
        nn.init.zeros_(m.bias)

net.apply(init_weights)

# 构造损失函数和优化器
loss = nn.CrossEntropyLoss(reduction='none')
optimizer = torch.optim.SGD(net.parameters(), lr=0.01)

d2l.train_ch3(net, train_iter, test_iter, loss, 10, optimizer)


posted @ 2024-08-24 10:14  不是孩子了  阅读(3)  评论(0编辑  收藏  举报