文章和代码曾经归档至【Github 仓库:https://github.com/timerring/dive-into-AI】或者公众号【AIShareLab】回复 pytorch 教程 也可获取。
autograd 主动求导零碎
torch.autograd
autograd
torch.autograd.backward
torch.autograd.backward (tensors, grad_tensors=None,retain_graph=None,create_graph=False)
性能:主动求取梯度
- tensors : 用于求导的张量,如 loss
- retain\_graph : 保留计算图
- create\_graph:创立导数计算图,用于高阶求导
- grad\_tensors:多梯度权重 (用于设置权重)
留神:张量类中的 backward 办法,实质上是调用的 torch.autogtad.backward。
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() # 能够求两次梯度
应用 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 设置权重
print(w.grad)
tensor([9.])
这个后果是由每一部分的梯度乘它对应局部的权重失去的。
torch.autograd.grad
torch.autograd.grad (outputs, inputs, grad_outputs=None,retain_graph= None, create_graph=False)
性能:求取梯度
- outputs : 用于求导的张量,如 loss
- inputs : 须要梯度的 张量
- create\_graph: 创立导数计算图,用于高阶求导
- retain\_graph : 保留计算图
- grad\_outputs:多梯度权重
x = torch.tensor([3.], requires_grad=True)
y = torch.pow(x, 2) # y = x**2
# grad_1 = dy/dx
grad_1 = torch.autograd.grad(y, x, create_graph=True)
print(grad_1)
# grad_2 = d(dy/dx)/dx
grad_2 = torch.autograd.grad(grad_1[0], x, create_graph=True)
print(grad_2) # 求二阶导
grad_3 = torch.autograd.grad(grad_2[0], x)
print(grad_3)
print(type(grad_3))
(tensor([6.], grad_fn=<MulBackward0>),)
(tensor([2.], grad_fn=<MulBackward0>),)
(tensor([0.]),)
<class 'tuple'>
留神:因为是元组类型,因而再次应用求导的时候须要拜访外面的内容。
1. 梯度不主动清零
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)
# If not zeroed, the errors from each backpropagation add up.
# This underscore indicates in-situ operation
grad.zero_()
tensor([5.])
tensor([5.])
tensor([5.])
tensor([5.])
2. 依赖于叶子结点的结点,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)
# It can be seen that the attributes of the leaf nodes are all set to True
print(a.requires_grad, b.requires_grad, y.requires_grad)
True True True
3. 叶子结点不可执行 in place
什么是 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) # After executing in place, the stored address does not change
2413216666632 tensor([1.]) 2413216668472 tensor([2.]) 2413216668472 tensor([3.])
叶子节点不能执行 in place,因为反向流传时会用到叶子节点张量的值,如 w。而取值是依照 w 的地址获得,因而如果 w 执行 inplace,则更换了 w 的值,导致反向流传谬误。
逻辑回归 Logistic Regression
逻辑回归是线性的二分类模型
模型表达式:
$\begin{array}{c}
y=f(W X+b)\
f(x)=\frac{1}{1+e^{-x}}
\end{array}$
f(x) 称为 Sigmoid 函数,也称为 Logistic 函数
$\text {class}=\left{\begin{array}{ll}
0, & 0.5>y \
1, & 0.5 \leq y
\end{array}\right.$
逻辑回归
$\begin{array}{c}
y=f(W X+b) \
\quad=\frac{1}{1+e^{-(W X+b)}} \
f(x)=\frac{1}{1+e^{-x}}
\end{array}$
线性回归是剖析自变量 x 与 因变量 y(标量) 之间关系的办法
逻辑回归是剖析自变量 x 与 因变量 y(概率) 之间关系的办法
逻辑回归也称为对数几率回归(等价)。
$\frac{y}{1-y}$ 示意对数几率。示意样本 x 为正样本的可能性。
证实等价:
$\begin{array}{l}
\ln \frac{y}{1-y}=W X+b \
\frac{y}{1-y}=e^{W X+b} \
y=e^{W X+b}-y * e^{W X+b} \
y\left(1+e^{W X+b}\right)=e^{W X+b} \
y=\frac{e^{W X+b}}{1+e^{W X+b}}=\frac{1}{1+e^{-(W X+b)}}
\end{array}$
线性回归
自变量:X
因变量:y
关系:y=𝑊𝑋+𝑏
实质就是用 WX+ b 拟合 y。
对数回归
lny=𝑊𝑋+𝑏
就是用𝑊𝑋+𝑏拟合 lny。
同理,对数几率回归就是用 WX+ b 拟合对数几率。
机器学习模型训练步骤
- 数据采集,荡涤,划分和预处理:通过一系列的解决使它能够间接输出到模型。
- 模型:依据工作的难度抉择简略的线性模型或者是简单的神经网络模型。
- 损失函数:依据不同的工作抉择不同的损失函数,例如在线性回归中采纳均方差损失函数,在分类工作中能够抉择穿插熵。有了 Loss 就能够求梯度。
- 失去梯度能够抉择某一种优化形式,即优化器。采纳优化器更新权值。
- 最初再进行迭代训练过程。
逻辑回归的实现
# -*- coding: utf-8 -*-
import torch
import torch.nn as nn
import matplotlib.pyplot as plt
import numpy as np
torch.manual_seed(10)
# ============================ step 1/5 Generate data ============================
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 Select Model ============================
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() # Instantiate a logistic regression model
# ============================ step 3/5 Choose a loss function ============================
# Select the cross-entropy function for binary classification
loss_fn = nn.BCELoss()
# ============================ step 4/5 Choose an optimizer ============================
lr = 0.01 # Learning rate
optimizer = torch.optim.SGD(lr_net.parameters(), lr=lr, momentum=0.9)
# ============================ step 5/5 model training ============================
for iteration in range(1000):
# forward propagation
y_pred = lr_net(train_x)
# calculate loss
loss = loss_fn(y_pred.squeeze(), train_y)
# backpropagation
loss.backward()
# update parameters
optimizer.step()
# clear gradient
optimizer.zero_grad()
# drawing
if iteration % 20 == 0:
mask = y_pred.ge(0.5).float().squeeze() # Classify with a threshold of 0.5
correct = (mask == train_y).sum() # Calculate the number of correctly predicted samples
acc = correct.item() / train_y.size(0) # Calculate classification accuracy
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
实现一个逻辑回归步骤如上。后续会缓缓解释。