多层感知机——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)
作者:Jace Jin
github地址:https://github.com/buxianghua
原创文章版权归作者所有.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.
欢迎转载,转载时请在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.