PyTorch深度学习实践 Lecture06 逻辑斯蒂回归


🤵 AuthorHorizon John

编程技巧篇各种操作小结

🎇 机器视觉篇会变魔术 OpenCV

💥 深度学习篇简单入门 PyTorch

🏆 神经网络篇经典网络模型

💻 算法篇再忙也别忘了 LeetCode


视频链接:Lecture 06 Logistic_Regression
文档资料:

//Here is the link:
课件链接:https://pan.baidu.com/s/1vZ27gKp8Pl-qICn_p2PaSw
提取码:cxe4

Logistic_Regression(逻辑斯蒂回归)

概述

逻辑斯蒂回归线性回归 之间的区别在于 激活函数 σ()

作用:

我们所使用的数据绝大多数是 非线性 的,而我们之前构造的神经网络都是 线性模型

这样会使得我们无论怎么增加网络深度,它最终得到的模型仍是一个线性模型,

引入激活函数就能在 神经网络中引入非线性,从而构造出 非线性模型强化网络的学习能力

所以激活函数的最大特点就是非线性。


在这里插入图片描述


注:

Logistic Regression: 可以将之前的线性模型 " Linear_Model :y = wx+b " 通过 Sigmoid函数 映射到(0,1)区间内,

并通过划定的一个 阈值 ,实现大于阈值的分为一类,小于阈值的分为另一类,可以用来处理二分类问题。


常见激活函数


在这里插入图片描述

Code

# Here is the code :

import torch
import matplotlib.pyplot as plt

# 1 prepare dataset

x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])


# 2 design model using class
class LogisticRegressionModel(torch.nn.Module):
    def __init__(self):
        super(LogisticRegressionModel, self).__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        y_pred = torch.sigmoid(self.linear(x))   # 使用激活函数F.sigmoid()
        return y_pred

model = LogisticRegressionModel()


# 3 construct loss and optimizer

criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)


# 4 training cycle (forward, backward, update)

epoch_list = []  # 构建数组存放迭代过程中的 epoch 和 cost 值
cost_list = []

for epoch in range(1000):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)

    epoch_list.append(epoch)
    cost_list.append(loss.item()/len(x_data))

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())

x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)

plt.plot(epoch_list, cost_list)  # 绘图
plt.title('Epoch - cost')
plt.xlabel('Epoch')
plt.ylabel('cost')
plt.show()

运行结果

w =  1.111702561378479
b =  -2.6895899772644043
y_pred =  tensor([[0.8529]])

附录:相关文档资料

PyTorch 官方文档: PyTorch Documentation
PyTorch 中文手册: PyTorch Handbook


《PyTorch深度学习实践》系列链接:

  Lecture01 Overview
  Lecture02 Linear_Model
  Lecture03 Gradient_Descent
  Lecture04 Back_Propagation
  Lecture05 Linear_Regression_with_PyTorch
  Lecture06 Logistic_Regression
  Lecture07 Multiple_Dimension_Input
  Lecture08 Dataset_and_Dataloader
  Lecture09 Softmax_Classifier
  Lecture10 Basic_CNN
  Lecture11 Advanced_CNN
  Lecture12 Basic_RNN
  Lecture13 RNN_Classifier

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Horizon John

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值