学习笔记|Pytorch使用教程04
本学习笔记主要摘自“深度之眼”,做一个总结,方便查阅。
使用Pytorch版本为1.2。
- torch.autograd
- 逻辑回归
一.autograd——自动求导系统
torch.autograd.backward()
功能:自动求取梯度
- tensors:用于求导的张量,如loss
- grad_tensors:多梯度权重
- retain_graph:保存计算图
- create_graph:创建导数计算图,用于高阶求导
计算图与梯度求导
y
=
(
x
+
w
)
∗
(
w
+
1
)
y=(x+w) *(w+1)
y=(x+w)∗(w+1)
a
=
x
+
w
b
=
w
+
1
a=x+w \quad b=w+1
a=x+wb=w+1
y
=
a
∗
b
y=a * b
y=a∗b
y对w求导可得:
∂
y
∂
w
=
∂
y
∂
a
∂
a
∂
w
+
∂
y
∂
b
∂
b
∂
w
=
b
+
1
+
a
∗
1
=
b
+
a
=
(
w
+
1
)
+
(
x
+
w
)
=
2
∗
w
+
x
+
1
=
2
∗
1
+
2
+
1
=
5
\begin{aligned} \frac{\partial y}{\partial w} &=\frac{\partial y}{\partial a} \frac{\partial a}{\partial w}+\frac{\partial y}{\partial b} \frac{\partial b}{\partial w} \\ &=b+1+a * 1 \\ &=b+a \\ &=(w+1)+(x+w) \\ &=2 * w+x+1 \\ &=2 * 1+2+1=5 \end{aligned}
∂w∂y=∂a∂y∂w∂a+∂b∂y∂w∂b=b+1+a∗1=b+a=(w+1)+(x+w)=2∗w+x+1=2∗1+2+1=5
retain_graph:
retain_graph = true ,能把计算图保存下来,才能进行第二次反向传播(梯度会累加)。
测试代码:
# ====================================== retain_graph ==============================================
flag = True
#flag = False
if flag:
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(retain_graph=True)
print(w.grad)
y.backward()
print(w.grad)
输出:
tensor([5.])
tensor([10.])
grad_tensors:
grad_tensors是可以设置多个梯度的权重。
测试代码:
# ====================================== grad_tensors ==============================================
flag = True
# flag = False
if flag:
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.]) #5*1 + 2*2
torch.autograd.grad()
功能:求取梯度
- outputs:用于求导的张量,如loss
- inputs:需要梯度的张量
- create_graph:创建导数的计算图,用于高阶求导
- retain_graph:保存计算图
- grad_outputs:多梯度权重
测试代码:
只有创建了导数的计算图,才能用于高阶求导
# ====================================== autograd.gard ==============================================
flag = True
# flag = False
if flag:
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.]),)
autograd小贴士:
- 梯度不自动清零
- 依赖于叶子结点的结点,requires_grad默认位True
- 叶子结点不可执行in-place
对于“梯度不自动清零”,测试代码:
如果梯度不清零,梯度会进行累加。要清零就加上:w.grad.zero_()。
# ====================================== tips: 1 ==============================================
flag = True
# flag = False
if flag:
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.])
对于“依赖于叶子结点的结点,requires_grad默认位True”,关于这个的理解参考上述的“计算图”,测试代码:
比如:x的梯度是依赖与a的梯度,a的梯度又依赖与y的梯度。
# ====================================== tips: 2 ==============================================
flag = True
# flag = False
if flag:
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)
输出:
True True True
对于“叶子结点不可执行in-place(原地操作)”,测试代码:
flag = True
# flag = False
if flag:
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()
执行上述代码会报错: a leaf Variable that requires grad has been used in an in-place operation.
下面理解in-place操作。
# ====================================== tips: 3 ==============================================
flag = True
# flag = False
if flag:
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)
输出:
2175013002280 tensor([1.])
2175013003080 tensor([2.])
发现,a的内存地址发生了变化。这是因为运算:a = a + torch.ones((1, ))开辟了新的内存地址,也就是这个不是in-place操作。如果使用a += torch.ones((1, )),则输出:
2175012960120 tensor([1.])
2175012960120 tensor([2.])
内存地址没有发生变化,这个就是in-place操作。
为什么叶子结点不能不能使用in-place操作:
参考上述计算图,以变量w为例。前向传播的时候,会记录w的地址,地址中会保存w的数据。反向传播的时候,会根据w的地址,读取w的数据,进行计算梯度。如果在反向传播之前,进行in-place操作,那么原来w的地址没有变,但是新的数据会覆盖原来的数据,那么会造成计算梯度错误。
二.逻辑回归
逻辑回归是线性的二分类模型。
模型表达式:
y
=
f
(
W
X
+
b
)
y=f(W X+b)
y=f(WX+b)
f
(
x
)
=
1
1
+
e
−
x
f(x)=\frac{1}{1+e^{-x}}
f(x)=1+e−x1
f
(
x
)
f(x)
f(x)被称为Sigmoid函数,也称为Logistic函数
分类标准:
class
=
{
0
,
0.5
>
y
1
,
0.5
≤
y
=\left\{\begin{array}{ll}{0,} & {0.5>y} \\ {1,} & {0.5 \leq y}\end{array}\right.
={0,1,0.5>y0.5≤y
逻辑回归又称之为对数几率回归(
ln
y
1
−
y
\ln \frac{y}{1-y}
ln1−yy)。
ln
y
1
−
y
=
W
X
+
b
\ln \frac{y}{1-y}=W X+b
ln1−yy=WX+b
y
1
−
y
=
e
W
X
+
b
\frac{y}{1-y}=e^{W X+b}
1−yy=eWX+b
y
=
e
W
X
+
b
−
y
∗
e
W
X
+
b
y=e^{W X+b}-y * e^{W X+b}
y=eWX+b−y∗eWX+b
y
(
1
+
e
W
X
+
b
)
=
e
W
X
+
b
y\left(1+e^{W X+b}\right)=e^{W X+b}
y(1+eWX+b)=eWX+b
y
=
e
W
X
+
b
1
+
e
W
X
+
b
=
1
1
+
e
−
(
W
X
+
b
)
y=\frac{e^{W X+b}}{1+e^{W X+b}}=\frac{1}{1+e^{-(W X+b)}}
y=1+eWX+beWX+b=1+e−(WX+b)1
- 机器学习模型训练步骤
测试代码:
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
torch.manual_seed(10)
# ============================ step 1/5 生成数据 ============================
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/5 选择模型 ============================
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/5 选择损失函数 ============================
loss_fn = nn.BCELoss()
# ============================ step 4/5 选择优化器 ============================
lr = 0.01 # 学习率
optimizer = torch.optim.SGD(lr_net.parameters(), lr=lr, momentum=0.9)
# ============================ step 5/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()
# 绘图
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
输出: