上一篇文章中,介绍了Pytorch的自动求导机制,可以帮我们通过反向传播,求解参数的导数。但模型中的神经层结构,还是需要自己构建,会很麻烦,本文介绍Pytorch中通过Sequential模型容器,快速搭建神经网络的方法。
代码示例
import torch
import torch.nn as nn
N, D_in, H, D_out = 64, 1000, 100, 10
x = torch.randn(N, D_in)
y = torch.randn(N, D_out)
# 定义模型容器,快速搭建神经网络
model = nn.Sequential(
nn.Linear(D_in, H),
nn.ReLU(H),
nn.Linear(H, D_out)
)
# 返回误差平方和
loss_fn = torch.nn.MSELoss(reduction='sum')
lr = 1e-4
for i in range(500):
y_hat = model(x)
loss = loss_fn(y_hat, y)
print(i, loss)
loss.backward()
# 更新权重参数
with torch.no_grad():
for param in model.parameters():
param -= param.grad * lr
param.grad.zero_()
本文为 陈华 原创,欢迎转载,但请注明出处:http://www.chenhuax.com/read/309