pytorch从零开始学习3
1.logistics regression
分类问题的理解:假设分类个数是10,类别分别是0-9.分类的结果是0-9各自的概率值,即输出值为0、1、2…9的概率分别为XXX,XXX…XXX。这里概率值相加为1.因此,从这里可以知道,不管分成多少个类别,总的概率值为1.因此,在最后输出的结果前一步中的激活函数将输出值映射到[-1,1]或是[0,1]
a
f
f
i
n
e
:
y
^
=
x
×
w
+
b
l
o
g
i
s
t
i
c
r
e
g
r
e
s
s
i
o
n
m
o
d
e
l
:
y
^
=
σ
(
x
×
w
+
b
)
affine :\hat{y}= x\times w+b\\ logistic\ regression\ model :\hat{y}=\sigma(x\times w +b)
affine:y^=x×w+blogistic regression model:y^=σ(x×w+b)
loss function for binary classification
l
o
s
s
f
u
n
c
t
i
o
n
f
o
r
l
i
n
e
a
r
r
e
g
r
e
s
s
i
o
n
l
o
s
s
=
(
y
^
−
y
)
2
=
(
x
×
w
−
y
)
2
l
o
s
s
f
u
n
c
t
i
o
n
f
o
r
b
i
n
a
r
y
c
l
a
s
s
i
f
i
c
a
t
i
o
n
l
o
s
s
=
−
(
y
l
o
g
y
^
+
(
1
−
y
)
l
o
g
(
1
−
y
^
)
)
loss\ function\ for\ linear\ regression\\ loss = (\hat{y}-y)^2=(x\times w -y)^2\\ loss\ function\ for\ binary\ classification\\loss=-(ylog\hat{y}+(1-y)log(1-\hat{y}))
loss function for linear regressionloss=(y^−y)2=(x×w−y)2loss function for binary classificationloss=−(ylogy^+(1−y)log(1−y^))
一些注意事项:
概率分布相似性–>交叉熵损失函数
比较的是概率分布。预测的分布与真实的分布比较,训练使得这两个分布尽可能接近。
σ \sigma σ是没有参数的,意味着没有参数可供训练,因此不用写在__init__中,直接在forward中调用即可。因此,从这里可以知道,__init__中定义的参数是需要更新的。
神经网络学习能力过强会将噪声信息学习到,所以不是学习能力越强越好
2. 批梯度下降(BGD)
一个epoch使用所有的数据进行训练。
优点:
- 由全数据集确定的参数更新方向可以更好的代表总体,从而当数据表现为凸函数时,能够得到全局最优解
缺点:
- 当数据量很大时,训练很慢
3. 随机梯度下降(SDG)
一次使用一个样本进行更新
优点:
- 由于不是在全部的数据集上进行更新,可以加快训练速度
缺点:
准确度下降。即使在目标函数为凸函数时,也不能得到全局最优解,得到的是局部最优解
不易于并行运算
4. 小批量随机梯度下降(MBGD)
一次使用batch size个样本进行更新
通过在随机梯度下降与批梯度下降折中,可以有效的实现以下:
- 并行化
- 提高一定的训练速度
init:初始化时,根据数据量的多少,来选择是否将所有数据或标签读取进来。如果数据过大,此时读取进来会导致内存不够,因此,不在这里初始化,在__getitem__中进行初始化
注意:输入的数据要转为tensor
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
# ------------------------------------------------------------prepare data---------------------------------------------------
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])
# ------------------------------------------------------------define model---------------------------------------------------
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 = F.sigmoid(self.linear(x))
return y_pred
# -----------------------------------------------------------------模型实例化--------------------------------------------------
model = LogisticRegressionModel()
# ----------------------------------------------construct loss and optimizer-------------------------------------------------
criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# ----------------------------------------------------training---------------------------------------------------------------
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
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)
# --------------------------------------------------可视化------------------------------------------------------------------
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()