一、多层感知机手动实现
# 多层感知机的手动实现
%matplotlib inline
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_first_hiddens = 784, 10, 256
W1 = nn.Parameter(
torch.randn(num_inputs, num_first_hiddens, requires_grad=True)*0.01)
b1 = nn.Parameter(torch.zeros(num_first_hiddens, requires_grad=True))
W2 = nn.Parameter(
torch.randn(num_first_hiddens, num_outputs, requires_grad=True)*0.01)
b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))
params = [W1, b1, W2, b2]
# relu函数,输入是隐藏层W1*X + b1
def relu(X):
zero_x = torch.zeros(X.shape)
return torch.max(X, zero_x)
# 模型函数,输入是数据X
def net(X):
X = X.reshape((-1, num_inputs))
H = relu(X@W1 + b1)
return (H@W2 + b2)
loss = nn.CrossEntropyLoss(reduction='none')
num_epochs = 10
lr = 0.1
updater = torch.optim.SGD(params, lr=lr)
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
二、利用torch框架实现多层感知机
# 多层感知机的简洁实现
%matplotlib inline
import torch
from d2l import torch as d2l
from torch import nn
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net = nn.Sequential(nn.Flatten(), # 先把输入数据(1,28,28)展开为(1,784)
nn.Linear(784, 256), # 784输入->256输出的隐藏层
nn.ReLU(), # 对隐藏层的输出再做一个ReLu函数
nn.Linear(256, 10)) # 输出层
net.apply(init_weights)
lr = 0.1
batch_size = 256
num_epochs = 10
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
updater = torch.optim.SGD(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss(reduction='none')
d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)
标签:nn,python,torch,iter,感知机,num,lr,d2l,李沐
From: https://blog.csdn.net/yuzixuan233/article/details/143575182