自动求导
深度学习本质就是不断地去更新权值,而权值的更新去求取梯度,因此梯度的求取是至关重要的。然而求取梯度十分的繁琐。因为pytorch
提供了自动求导系统,只需要搭建好前向传播,pytorch
会自动求解梯度
自动求导系统
torch.autograd.backward
功能:自动求取梯度
torch.autograd.backward(tensors, # 用于求解梯度的张量,比如:loss
grad_tensors=None, # 多梯度权重
retain_graph=None, # 保存计算图
create_graph=False #创建导数计算图,用于高阶求导)
例如:
w = torch.tensor([1.], requires_grad=True)
x = torch.tensor([2.], requires_grad=True)
a = torch.add(w, x)
b = torch.add(w, 1)
y = torch.mul(a, b)
y.backward()
print(w.grad)
输出的结果为:
tensor([5.])
其中调用backward
函数本身就是pytorch
的自动求导系统,进入这个函数发现其实就是:
torch.autograd.backward(self, gradient, retain_graph, create_graph, inputs=inputs)
1. retain_graph
但是当想要继续进一步求梯度,此时会发生错误。因为pytorch已经将计算图已经释放了。想要继续进一步求解梯度,只要在这里进行更改即可
y.backward(retain_graph=True)
y.backward()
2. grad_tensors
功能:分配多个梯度权重
例如:
w = torch.tensor([1.], requires_grad=True)
x = torch.tensor([2.], requires_grad=True)
a = torch.add(w, x) # retain_grad()
b = torch.add(w, 1)
y0 = torch.mul(a, b) # y0 = (x+w) * (w+1)
y1 = torch.add(a, b) # y1 = (x+w) + (w+1) dy1/dw = 2
loss = torch.cat([y0, y1], dim=0) # [y0, y1]
grad_tensors = torch.tensor([1., 2.])
loss.backward(gradient=grad_tensors) # gradient 传入 torch.autograd.backward()中的grad_tensors
print(w.grad)
输出的结果为:
tensor([9.])
dy0/dw
的导数是5
,dy1/dw
的导数2
,然后分配的梯度为(1, 2)
,所以最后的输出结果:5 + 2 * 2 = 9
3.autograd.gard
x = torch.tensor([3.], requires_grad=True)
y = torch.pow(x, 2) # y = x**2
# 一阶导数
grad_1 = torch.autograd.grad(y, x, create_graph=True) # grad_1 = dy/dx = 2x = 2 * 3 = 6
print(grad_1)
# 二阶导数
grad_2 = torch.autograd.grad(grad_1[0], x) # grad_2 = d(dy/dx)/dx = d(2x)/dx = 2
print(grad_2)
输出的结果为:
(tensor([6.], grad_fn=<MulBackward0>),)
(tensor([2.]),)
需要注意的是:create_graph=True
,这时才会创建导数计算图,才能计算二阶导数。grad_1[0]
这里是因为输出的grad_1
是元组,因此需要取出梯度
pytorch进行自动求导的时候有三个地方需要注意:
- 梯度不自动清零
w = torch.tensor([1.], requires_grad=True)
x = torch.tensor([2.], requires_grad=True)
for i in range(4):
a = torch.add(w, x)
b = torch.add(w, 1)
y = torch.mul(a, b)
y.backward()
print(w.grad)
# w.grad.zero_()
输出的结果为:
tensor([5.])
tensor([10.])
tensor([15.])
tensor([20.])
此时梯度并没清零,而是在不断累加。因为若想要清除梯度,需要手动添加w.grad.zero_()
此时输出的结果:
tensor([5.])
tensor([5.])
tensor([5.])
tensor([5.])
- 依赖于叶子结点的结点,
requires_grad
默认为True
w = torch.tensor([1.], requires_grad=True)
x = torch.tensor([2.], requires_grad=True)
a = torch.add(w, x)
b = torch.add(w, 1)
y = torch.mul(a, b)
print(a.requires_grad, b.requires_grad, y.requires_grad)
此计算图中,叶子结点只有w
和x
,而a
和b
都依赖这两个叶子结点,因此输出这两个输出都应该为True
。同理y的输出也应该是True
输出结果为:
True True True
- 叶子结点不可执行
in_place
(原地操作)
原地操作就是在相同的地址中进行操作运算
例如:
a = torch.ones((1, ))
print(id(a), a)
a = a + torch.ones((1, ))
print(id(a), a)
a += torch.ones((1, ))
print(id(a), a)
输出1:
2696554173128 tensor([1.])
2696610773096 tensor([2.])
输出2:
2519500804808 tensor([1.])
2519500804808 tensor([2.])
其中第二个就是原地操作(in_place
)
例如:
w = torch.tensor([1.], requires_grad=True)
x = torch.tensor([2.], requires_grad=True)
a = torch.add(w, x)
b = torch.add(w, 1)
y = torch.mul(a, b)
w.add_(1)
y.backward()
输出的结果为:
RuntimeError: a leaf Variable that requires grad is being used in an in-place operation.
原因是:在反向传播的过程中,梯度的计算是根据叶子结点的地址进行计算的,保存的是叶子结点的地址,根据地址来寻找数据
逻辑回归
逻辑回归是线性的二分类模型,逻辑回归也叫对数几率回归
- 线性回归是分析自变量
x
与因变量y
(标量)之间关系的方法 - 逻辑回归是分析自变量
x
与因变量y
(概率)之间关系的方法
深度学习中模型的构建一般包含:数据、模型、损失函数、优化器以及迭代训练
step 1
生成数据
sample_nums = 100
mean_value = 1.7
bias = 1
n_data = torch.ones(sample_nums, 2)
x0 = torch.normal(mean_value * n_data, 1) + bias # 类别0 数据 shape=(100, 2)
y0 = torch.zeros(sample_nums) # 类别0 标签 shape=(100, 1)
x1 = torch.normal(-mean_value * n_data, 1) + bias # 类别1 数据 shape=(100, 2)
y1 = torch.ones(sample_nums) # 类别1 标签 shape=(100, 1)
train_x = torch.cat((x0, x1), 0)
train_y = torch.cat((y0, y1), 0)
step 2
选择模型
class LR(nn.Module):
def __init__(self):
super(LR, self).__init__()
self.features = nn.Linear(2, 1)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = self.features(x)
x = self.sigmoid(x)
return x
lr_net = LR() # 实例化逻辑回归模型
step 3
选择损失函数
loss_fn = nn.BCELoss()
step 4
选择优化器
lr = 0.01 # 学习率
optimizer = torch.optim.SGD(lr_net.parameters(), lr=lr, momentum=0.9)
step 5
模型训练
for iteration in range(1000):
# 前向传播
y_pred = lr_net(train_x)
# 计算 loss
loss = loss_fn(y_pred.squeeze(), train_y)
# 反向传播
loss.backward()
# 更新参数
optimizer.step()
# 清空梯度
optimizer.zero_grad()
# 绘图
if iteration % 20 == 0:
mask = y_pred.ge(0.5).float().squeeze() # 以0.5为阈值进行分类
correct = (mask == train_y).sum() # 计算正确预测的样本个数
acc = correct.item() / train_y.size(0) # 计算分类准确率
plt.scatter(x0.data.numpy()[:, 0], x0.data.numpy()[:, 1], c='r', label='class 0')
plt.scatter(x1.data.numpy()[:, 0], x1.data.numpy()[:, 1], c='b', label='class 1')
w0, w1 = lr_net.features.weight[0]
w0, w1 = float(w0.item()), float(w1.item())
plot_b = float(lr_net.features.bias[0].item())
plot_x = np.arange(-6, 6, 0.1)
plot_y = (-w0 * plot_x - plot_b) / w1
plt.xlim(-5, 7)
plt.ylim(-7, 7)
plt.plot(plot_x, plot_y)
plt.text(-5, 5, 'Loss=%.4f' % loss.data.numpy(), fontdict={'size': 20, 'color': 'red'})
plt.title("Iteration: {}\nw0:{:.2f} w1:{:.2f} b: {:.2f} accuracy:{:.2%}".format(iteration, w0, w1, plot_b, acc))
plt.legend()
plt.show()
plt.pause(0.5)
if acc > 0.99:
break