感知机
从零开始实现
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)
#实现一个具有单隐藏层的多层感知机,包含256个隐藏单元
num_inputs,num_outputs,num_hiddens = 784,10,256
# 784*256
W1= nn.Parameter(torch.randn(num_inputs,num_hiddens,requires_grad=True))
# 256
b1 = nn.Parameter(torch.zeros(num_hiddens,requires_grad=True))
# 256*10
W2 = nn.Parameter(torch.randn(num_hiddens,num_outputs,requires_grad=True))
# 10
b2= nn.Parameter(torch.zeros(num_outputs,requires_grad=True))
params =[W1,b1,W2,b2]
# 实现激活函数
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(reduction='none')
# 训练
num_epochs,lr = 30,0.1
updater = torch.optim.SGD(params,lr=lr)
d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,updater)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/539e8db502d9e768bc24ec5573376635.png)
简洁实现
# 简洁实现
import torch
from torch import nn
from d2l import torch as d2l
# 3D转2D 线性层 激活函数 线形层
net = nn.Sequential(nn.Flatten(),nn.Linear(784,256),nn.ReLU(),nn.Linear(256,10))
def init_weights(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight,std=0.5)
net.apply(init_weights);
# 训练过程
batch_size,lr,num_epochs =256,0.1,10
loss = nn.CrossEntropyLoss(reduction='none')
trainer = torch.optim.SGD(net.parameters(),lr=lr)
trian_iter,test_iter=d2l.load_data_fashion_mnist(batch_size)
d2l.train_ch3(net,train_iter,test_iter,loss,num_epochs,trainer)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cf6caff7e079f9513e8120b956832725.png)