反向传播的一个手算例子:https://blog.csdn.net/weixin_38347387/article/details/82936585
这里主要是靠这个文章学的pytorch:https://www.jianshu.com/p/52684285e335
我们首先使用 numpy 来实现这个神经网络。
import numpy as np
# N is batch size; D_in is input dimension;
# H is hidden dimension; D_out is output dimension.
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random input and output data
x = np.random.randn(N, D_in)
y = np.random.randn(N, D_out)
# Randomly initialize weights
w1 = np.random.randn(D_in, H)
w2 = np.random.randn(H, D_out)
learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y
h = x.dot(w1)
h_relu = np.maximum(h, 0)
y_pred = h_relu.dot(w2)
# Compute and print loss
loss = np.square(y_pred - y).sum()
print(t, loss)
# Backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 2.0 * (y_pred - y)
grad_w2 = h_relu.T.dot(grad_y_pred)
grad_h_relu = grad_y_pred.dot(w2.T)
grad_h = grad_h_relu.copy()
grad_h_relu[h<0] = 0
grad_w1 = x.T.dot(grad_h)
# update weights
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
Numpy 是一个伟大的框架,但是他不能利用 GPUs 来加快数值计算。对于现代深度神经网络, GPU 通常提供50倍或更高的加速,所以不幸的是 numpy 不足以用于现代深度学习.
我们使用 PyTorch 来训练一个两层的网络让它拟合随机数据
import torch
dtype = torch.FloatTensor
# dtype = torch.cuda.FloatTensor # Uncomment this to run GPU
# N is batch size; D_in is input dimenssion
# H is hidden demenssion; D_out is output dimension
N, D_in, H, D_out = 64, 1000, 100, 10
# create random input and output data
x = torch.randn(N, D_in).type(dtype)
y = torch.randn(N, D_out).type(dtype)
# Randomly initialize weights
w1 = torch.randn(D_in, H).type(dtype)
w2 = torch.randn(H, D_out).type(dtype)
learning_rate = 1e-6
for t in range(500):
# Forward pss: compute predicted y
h = x.mm(w1)
h_relu = h.clamp(min=0)
y_pred = h_relu.mm(w2)
# compute and print loss
loss = (y_pred - y).pow(2).sum()
print(t, loss)
# backprop to compute gradients of w1 and w2 with respect to loss
grad_y_pred = 3.0 * (y_pred - y)
grad_w2 = h_relu.t().mm(grad_y_pred)
grad_h_relu = grad_y_pred.mm(w2.t())
grad_h = grad_h_relu.clone()
grad_h[h<0] = 0
grad_w1 = x.t().mm(grad_h)
# update weights using gradient descent
w1 -= learning_rate * grad_w1
w2 -= learning_rate * grad_w2
手动实现反向传播对于一个小型的两层网络来说并不是什么难题,但是对于大型复杂啊网络,很快就会变得棘手。
值得庆幸的是,我们可以使用自动微分来自动计算神经网络的反向传播。PyTorch 中的 autograd 包提供了这一功能。当我们使用自动求导时,你的神经网络的前向传播讲定义一个计算图;图中的节点将是 Tensors,边表示从输入张量产生输出张量的函数。通过图反向传播可以让你轻松的计算梯度。
用 Variable 对象来包装 Tensors。 一个 Variable 表示计算图中的一个节点。
如果 x 是一个 Variable,那么 x.data 则是一个 Tensor,x.grad 是另一个用来保存 x 关于某个标量值的梯度。
使用 Variables 定义了一个计算图, 允许你自动的计算梯度。
这里我们使用 Variable 和自动求导来实现我们的两层网络;现在我们不再需要手动地实现反向传播。
torch.Tensor 是这个包的核心类。如果设置它的属性 .requires_grad 为 True,那么它将会追踪对于该张量的所有操作。当完成计算后可以通过调用 .backward(),来自动计算所有的梯度。这个张量的所有梯度将会自动累加到.grad属性.
import torch
from torch.autograd import Variable
dtype = torch.FloatTensor
# dtype = torch.cuda.FloatTensor # Uncomment this to run on GPU
N, D_in, H, D_out = 64, 1000, 100, 10
# Create random Tensors to hold input and outpus, and wrap them in Variables.
# Setting requires_grad=False indicates that we do not need to compute gradients
# with respect to these Variables during the backward pass
x = Variable(torch.randn(N, D_in).type(dtype), requires_grad=False)
y = Variable(torch.randn(N, D_out).type(dtype), requires_grad=False)
# Create random Tensors for weights, and wrap them in Variables.
# Setting requires_grad=True indicates that we want to compute gradients with
# respect to these Variables during the backward pass.
w1 = Variable(torch.randn(D_in, H).type(dtype), requires_grad=True)
w2 = Variable(torch.randn(H, D_out).type(dtype), requires_grad=True)
learning_rate = 1e-6
for t in range(500):
# Forward pass: compute predicted y using operations on Variables; these
# are exactly the same operations we used to compute the forward pass using
# Tensors, but we do not need to keep references to intermediate values since
# we are not implementing the backward pass by hand.
y_pred = x.mm(w1).clamp(min=0).mm(w2)
# Compute and print loss using operations on Variables.
# Now loss is a Variable of shape (1,) and loss.data is a Tensor of shape
# (1,); loss.data[0] is a scalar value holding the loss.
loss = (y_pred - y).pow(2).sum()
print(t, loss.data[0])
# Use autograd to compute the backward pass. This call will compute the
# gradient of loss with respect to all Variables with requires_grad=True.
# After this call w1.grad and w2.grad will be Variables holding the gradient
# of the loss with respect to w1 and w2 respectively.
loss.backward()
# Update weights using gradient descent; w1.data and w2.data are Tensors,
# w1.grad and w2.grad are Variables and w1.grad.data and w2.grad.data are
# Tensors.
w1.data -= learning_rate * w1.grad.data
w2.data-= learning_rate * w2.grad.data
# Manually zero the gradients after updating weights
w1.grad.data.zero_()
w2.grad.data.zero_()
最大的区别是: Tensorflow 中的计算图是静态的,而 PyTorch 使用的是动态计算图。在 Tensorflow 中,我们只定义一次计算图,然后重复执行同一个图,可能将不同的输入数据提供给图。在 PyTorch 中,每次前向传播都会定义一个新的计算图。
计算图和 autograd 是定义复杂运算符和自动求导的的一个非常强大的范例。然而对于大规模的神经网络, 原始的 autograd 可能有点太低级了。
在 PyTorch 中, nn 包提供了同样的功能。 nn 包提供了一组模块,他们大致相当于神经网络层。一个模块接收一个输入变量并计算输出向量,也可能保存内部状态,如包含可学习的参数。 nn 包还定义了一组训练神经网络时有用的损失函数。
在这个例子中我们使用 nn 包来实现我们的两层网络:
原文:https://www.cnblogs.com/pocahontas/p/11636765.html