当前位置:   article > 正文

李沐深度学习-ch4 多层感知机MLP的从零实现和简介实现 PyTorch_mlp李沐

mlp李沐
#scratch
import torch
from d2l import torch as d2l
from torch import nn
#load data set fashion_mnist
batch_size = 128 # 
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
#set parameters
num_inputs, num_outputs, num_hiddens = 784, 10, 256
W1 = nn.Parameter(torch.randn(
    num_inputs, num_hiddens, requires_grad=True) * 0.01)
b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))
W2 = nn.Parameter(torch.randn(
    num_hiddens, num_outputs, requires_grad=True) * 0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))
parameters = [W1, b1, W2, b2]
#set net one hidden
def net(X):
    X = X.reshape((-1,num_inputs))
    return  torch.relu(X@W1 + b1)@W2 + b2
#set loss func
loss = nn.CrossEntropyLoss(reduction="none")
#train
num_epochs, lr = 20, 0.1
updater = torch.optim.SGD(parameters, lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)

#test
d2l.predict_ch3(net, test_iter)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

训练
在这里插入图片描述

测试
在这里插入图片描述

#concise
import torch
from torch import nn
from d2l import torch as d2l
# use Sequential to define the net: Flatten,Linear,ReLU,Linear
net = nn.Sequential(nn.Flatten(),
                    nn.Linear(784, 256),
                    nn.ReLU(),
                    nn.Linear(256, 10))

# weight tensor to normal weight tensor 
def init_weights(m): 
    # if m is nn.Linear, the tensor m.weight -> a normal tensor which mean=0,std=0.01
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight, std=0.01) # Fills the input Tensor with values drawn from the normal
net.apply(init_weights)
# define parameters batch_size, lr, num_epochs and loss, updater
batch_size, lr, num_epochs = 128, 0.1, 10
loss = nn.CrossEntropyLoss(reduction='none')
updater = torch.optim.SGD(net.parameters(), lr=lr)
# load dataset and train 
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

训练

在这里插入图片描述

教程链接d2l.ai

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/寸_铁/article/detail/939110
推荐阅读
相关标签
  

闽ICP备14008679号