PyTorch 深度学习实践-06-[Logistic Regression]

Date: 2021-12-27

Repositity: Gitee

本节引出分类问题,使用模型为Logistic regression。使用数据集为:MNIST手写数字数据集。

0. MNIST Dataset

关于MNIST数据集有:

  • 训练集大小:60000张手写样本;
  • 测试集大小:10000张手些样本;
  • 共计10个类别:{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}

因此我们需要区分出来 y ∈ { 0 ,   1 ,   2 ,   3 ,   4 ,   5 , 6 ,   7 ,   8 ,   9 } y \in \{0,\ 1, \ 2, \ 3, \ 4, \ 5, 6, \ 7, \ 8, \ 9 \} y{0, 1, 2, 3, 4, 5,6, 7, 8, 9} 为哪一个数字,分出具体的类别。

Q:按照之前线性回归的思路来,即是:如果y 是第一个类别,则有y == 1…,这个思路是不好的,为什么?

A:因为我们构造类别的编号时,存在以下情况:类别标签上01是挨着的,789也是挨着的,但是其在笔画上并不相似(79明显更相似),并且在输入空间上79也更接近(09很像,但在结果上差的很远)。因为这些类别并没有一维实数空间数值大小的含义,不是单纯的数值比较,类别不存在大小关系。我们需要输出的是对应类别的概率,找到最大概率对应的类别。

如何使用MNIST数据集,PyTorch中导入torchvision

import torchvision

train_set = torchvision.datasets.MNIST(root='../dataset/mnist',
                                       train=True , download=True)
test_set = torchvision.datasets.MNIST(root='../dataset/mnist',
                                      train=False , download=True)

对应的还有CIFAR-10数据集(彩色小图像)

  • 训练集大小:50000张手写样本;
  • 测试集大小:10000张手些样本;
  • 共计10个类别:{airplane, automobile, bird, cat, deer, dog, frog, horse, ship, truck}

如何使用:

import torchvision

train_set = torchvision.datasets.CIFAR10(root='../dataset/cifar10',
                                         train=True , download=True)
test_set = torchvision.datasets.CIFAR10(root='../dataset/cifar10',
                                        train=False , download=True)

2. Regression vs Classification

这里将训练数据做一个调整,右侧的橙色为考试不通过,绿色为考试通过。

对于分类而言,要么考试通过要么不通过,典型的2分类问题。所以,我们只需要计算通过的概率即可。

3. Logistsic Function

第二节我们知道最终我们得到实际是 y ^ = 1 \hat{y}=1 y^=1 的概率,那么如何实现 y ^ = x ∗ ω + b \hat{y} = x *\omega + b y^=xω+b 结果有映射关系 R → [ 0 ,   1 ] \mathbb{R} \rightarrow \left[0, \ 1 \right] R[0, 1]Logistic function
σ ( x ) = 1 1 + e − x (1) \sigma(x) = \frac{1}{1+e^{-x}} \tag{1} σ(x)=1+ex1(1)
画出其函数图,可以发现其结果刚好满足值域在[0, 1]单调增函数。其导数即饱和函数。除了logistic还有其他激活函数,其都满足值域有限,单调增,导数为饱和函数。

4. Logistic Regression Model

回到逻辑回归,结合前面的logistic函数,其模型变为下图所示。

反向传播注意其导数: σ ( x ) ′ = e − x ( 1 + e − x ) 2 = σ ( x ) ( 1 − σ ( x ) ) \sigma(x)'=\frac{e^{-x}}{\left(1+e^{-x}\right)^2}=\sigma(x)(1-\sigma(x)) σ(x)=(1+ex)2ex=σ(x)(1σ(x))

5. Loss function for Binary Classification

先回忆一下线性回归的损失函数MSE
l o s s = ( y ^ − y ) 2 = ( x ⋅ ω + b − y ) 2 (2) loss = \left( \hat{y} - y \right)^2=(x\cdot{\omega} + b - y)^2 \tag{2} loss=(y^y)2=(xω+by)2(2)
计算两个实数值之间的差值,计算的实数轴上的一个距离。而logostic回归,计算的是一个概率分布的差异,不是几何空间的距离。那么如何衡量?K-L散度,交叉熵?

实际使用的交叉熵,这里叫BCE,前面的-号则表示差异越小越好。
l o s s = − ( y log ⁡ y ^ + ( 1 − y ) log ⁡ ( 1 − y ^ ) ) (3) loss = -(y\log{\hat{y}} + (1 - y)\log{(1- \hat{y})}) \tag{3} loss=(ylogy^+(1y)log(1y^))(3)
对应的Mini-Batch损失函数则变为:
l o s s = − 1 N ∑ n = 1 N ( y n log ⁡ y ^ n + ( 1 − y n ) log ⁡ ( 1 − y ^ n ) ) (4) loss = -\frac{1}{N}\sum_{n=1}^{N}\left(y_n\log{\hat{y}_n} + (1 - y_n)\log{(1 - \hat{y}_n)}\right) \tag{4} loss=N1n=1N(ynlogy^n+(1yn)log(1y^n))(4)

6. code

import torch
""" pyplot model """
import numpy as np
import matplotlib.pyplot as plt

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


class LogisticRegressionModel(torch.nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = torch.nn.Linear(1, 1)

    def forward(self, x):
        # use sigmoid func
        y_pred = torch.sigmoid(self.linear(x))
        return y_pred


model = LogisticRegressionModel()

# use BCE, 少量数据直接`sum`即可,不用均值
criterion = torch.nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)

num = 1000
for epoch in range(num):
    y_pred = model(x_data)
    loss = criterion(y_pred, y_data)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
    print('\r Epoch: {:>3.0f}%[{}->{}], loss: {}'.format(epoch * 100 / (num - 1), int(epoch / 10) * '*',
                                                         (int(num / 10) - 1 - int(epoch / 10)) * '.', loss.item()),
          end='')

print('\n>> check parameter: w = {}, b = {}'.format(model.linear.weight.item(),
                                                    model.linear.bias.item()))

""" test """
x = torch.Tensor([[10.]])
y_gt = 1
y = model(x)
print('>> Test x = {}, prediction: y = {}, diff: {}'.format(x.numpy(), y.data.numpy(), (y_gt - y.data.numpy()) / y_gt))

x = np.linspace(0, 10, 200)
x_t = torch.Tensor(x).view((200, 1))
y_t = model(x_t)
y = y_t.data.numpy()
plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值