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:因为我们构造类别的编号时,存在以下情况:类别标签上0
、1
是挨着的,7
、8
、9
也是挨着的,但是其在笔画上并不相似(7
和9
明显更相似),并且在输入空间上7
和9
也更接近(0
和9
很像,但在结果上差的很远)。因为这些类别并没有一维实数空间数值大小的含义,不是单纯的数值比较,类别不存在大小关系。我们需要输出的是对应类别的概率,找到最大概率对应的类别。
如何使用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
这里将训练数据做一个调整,右侧的橙色为考试不通过,绿色为考试通过。
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+e−x1(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+e−x)2e−x=σ(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⋅ω+b−y)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^+(1−y)log(1−y^))(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=1∑N(ynlogy^n+(1−yn)log(1−y^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()