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

#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)

训练
在这里插入图片描述

测试
在这里插入图片描述

#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)

训练

在这里插入图片描述

教程链接d2l.ai

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值