<jupyter_start><jupyter_text>3.10 多层感知机的简洁实现<jupyter_code>import torch
from torch import nn
from torch.nn import init
import numpy as np
import sys
sys.path.append("..") 
import d2lzh_pytorch as d2l

print(torch.__version__)<jupyter_output>0.4.1<jupyter_text>3.10.1 定义模型<jupyter_code>num_inputs, num_outputs, num_hiddens = 784, 10, 256
    
net = nn.Sequential(
        d2l.FlattenLayer(),
        nn.Linear(num_inputs, num_hiddens),
        nn.ReLU(),
        nn.Linear(num_hiddens, num_outputs), 
        )
    
for params in net.parameters():
    init.normal_(params, mean=0, std=0.01)<jupyter_output><empty_output><jupyter_text>3.10.2 读取数据并训练模型<jupyter_code>batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
loss = torch.nn.CrossEntropyLoss()

optimizer = torch.optim.SGD(net.parameters(), lr=0.5)

num_epochs = 5
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, batch_size, None, None, optimizer)<jupyter_output>epoch 1, loss 0.0031, train acc 0.703, test acc 0.757
epoch 2, loss 0.0019, train acc 0.824, test acc 0.822
epoch 3, loss 0.0016, train acc 0.845, test acc 0.825
epoch 4, loss 0.0015, train acc 0.855, test acc 0.811
epoch 5, loss 0.0014, train acc 0.865, test acc 0.846
{'fraction_non_alphanumeric': 0.11726384364820847, 'fraction_numerical': 0.08794788273615635, 'mean_word_length': 4.4622222222222225, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '3', 'dir': 'jupyter-structured-clean-dedup', 'id': '206', 'license': 'Apache-2.0', 'n_tokens_mistral': 576, 'n_tokens_neox': 519, 'n_words': 114, 'path': 'code/chapter03_DL-basics/3.10_mlp-pytorch.ipynb', 'repo_name': 'fizzyelf-es/Dive-into-DL-PyTorch', 'size': '1228'}