打赏

多层感知机——pytorch版

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)

num_inputs,num_outputs,num_hiddens = 784, 10,256
w1 = nn.Parameter(
    torch.randn(num_inputs,num_hiddens,requires_grad=True)
)
b1 = nn.Parameter(torch.zeros(num_hiddens,requires_grad=True))
w2 = nn.Parameter(torch.randn(num_hiddens,num_outputs,requires_grad=True))

b2 = nn.Parameter(torch.zeros(num_outputs,requires_grad=True))
# w1 b1是第一层,w2 b2是第二层
params = [w1,b1,w2,b2]
# 实现relu激活函数
def relu(x):
    a = torch.zeros_like(x)
    return torch.max(x,a)
# 实现模型
def net(x):
    # 把图片拉成矩阵
    x = x.reshape((-1,num_inputs))
    # @表示矩阵乘法
    h = relu(x@w1+b1)
    return (h@w2+b2)

loss = nn.CrossEntropyLoss()
# 训练
num_epochs,lr=10,0.1
updater = torch.optim.SGD(params,lr=lr)
print(updater)
# d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,updater)

简洁版

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

# 隐藏层包含256个隐藏单元,并使用ReLU激活函数
net = nn.Sequential(
    # Flatten把三维变成二维
    nn.Flatten(),nn.Linear(784,256),nn.ReLU(),nn.Linear(256,10)
)
def init_weight(m):
    if type(m) == nn.Linear:
        nn.init.normal_(m.weight,std=0.01)

net.apply(init_weight)

batch_size, lr, num_epochs = 256, 0.1, 10
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(), lr=lr)

train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, trainer)

 

posted @ 2023-07-29 09:22  不像话  阅读(7)  评论(0编辑  收藏  举报