栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pytorch autograd_pytorch实现逻辑回归?

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pytorch autograd_pytorch实现逻辑回归?

0. 往期内容

[一]深度学习Pytorch-张量定义与张量创建

[二]深度学习Pytorch-张量的操作:拼接、切分、索引和变换

[三]深度学习Pytorch-张量数学运算

[四]深度学习Pytorch-线性回归

[五]深度学习Pytorch-计算图与动态图机制

[六]深度学习Pytorch-autograd与逻辑回归

深度学习Pytorch-autograd与逻辑回归

0. 往期内容1. 自动求导函数

1.1 torch.autograd.backward(tensors)1.2 torch.autograd.grad(outputs, inputs)1.3 autograd需要注意的tips 2. 逻辑回归

2.1 逻辑回归定义2.2 逻辑回归与线性回归2.3 机器学习模型训练步骤2.4 代码实战

1. 自动求导函数 1.1 torch.autograd.backward(tensors)
torch.autograd.backward(tensors, grad_tensors=None, retain_graph=None, create_graph=False)

(1)功能:自动求取梯度;
(2)参数:
tensors: 用于求导的张量,如loss;
retain_graph: 是否保存计算图,如果想要保存计算图,需要设置retain_graph为True;
create_graph: 是否创建导数计算图,一般用于高阶求导;
grad_tensors: 多梯度权重;
(3)代码示例:

# ====================================== 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)
    #想要进行第二次反向传播需要将第一次反向传播设置为retain_graph=True
    y.backward()

# ====================================== 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)    dy0/dw= 5
    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., 1.])

    loss.backward(gradient=grad_tensors)    # gradient 传入 torch.autograd.backward()中的grad_tensors

    print(w.grad)
    #输出为7,5*1+2*1=7
1.2 torch.autograd.grad(outputs, inputs)
torch.autograd.grad(outputs, inputs, grad_outputs=None, retain_graph=None, create_graph=False)

(1)功能:求取梯度;
(2)参数:
outputs: 用于求导的张量,如loss;
inputs: 需要梯度的张量;
(3)代码示例:

# ====================================== autograd.gard ==============================================
# flag = True
flag = False
if flag:

    x = torch.tensor([3.], requires_grad=True)
    y = torch.pow(x, 2)     # y = x**2

    #create_graph一定要设置为True,它是用来创建导数的计算图
    grad_1 = torch.autograd.grad(y, x, create_graph=True)   # grad_1 = dy/dx = 2x = 2 * 3 = 6
    print(grad_1)
    #输出为6,2*3=6

    #grad_1是元组,所以需要用grad_1[0]来吧梯度取出来
    grad_2 = torch.autograd.grad(grad_1[0], x)              # grad_2 = d(dy/dx)/dx = d(2x)/dx = 2
    print(grad_2)
    #输出2
1.3 autograd需要注意的tips


(1)梯度不自动清零:梯度在每一次反向传播时会自动叠加,不会清零,需要使用grad.zero_()手动清零。_下划线表示in place原地操作。
(2)代码示例:

# ====================================== 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)

        #梯度不会自动清零,每一次反向传播会自动叠加
        #需要使用grad.zero_()手动清零。
        w.grad.zero_() 


# ====================================== 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,因为a、b依赖于叶子节点w、x,y依赖于a、b也就是依赖于叶子节点w、x


# ====================================== 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)

    #两者的内存地址一样,+=操作是in-place操作
    a += torch.ones((1, ))
    print(id(a), a)


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)

    #加了这一行代码会报错,in-place操作是在原始内存中改变其数据
    w.add_(1)

    y.backward()
2. 逻辑回归 2.1 逻辑回归定义

2.2 逻辑回归与线性回归

对数几率回归=逻辑回归

2.3 机器学习模型训练步骤

2.4 代码实战
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 选择模型 ============================
#g构建逻辑回归类
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)
#momentum是引入的动量,一般设置为0.9。
# 当momentum越大时,转换为势能的能量就越大,就越有可能摆脱局部凹区域,从而进入全局凹区域。momentum主要是用于权值优化。
# 可以理解为,如果上一次的 momentum(v) 与当前的momentum负梯度方向是相同的,那这次下降的幅度就会加大,从而可以加快模型收敛。

# ============================ 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()

    # 清空梯度
    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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/783515.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号