
🍊本文详细介绍了线性回归和逻辑回归是什么,并对二者进行了对比,此外详细介绍了sigmoid函数,最后使用Pytorch来实战模拟二者
🍊实验一使用Pytorch实现线性回归
🍊实验二使用Pytorch实现逻辑回归
在初学机器学习的时候,我们总会听到线性回归模型和逻辑回归模型,那么它们究竟是什么?有什么联系与区别呢?
首先他们都是一条线,目的是让我们预测的对象尽可能多的穿过这条线
线性回归模型是真的回归模型,但是逻辑回归模型虽然名字上带着回归,实际上是个分类模型,看看看下图就知道了。因为是完全属于不同类型的模型,因此他们的损失函数也是不一样的


损失函数

这里的σ是sigmoid函数, 分类模型是需要将最后的预测结果仿射到0-1区间中,且所有的类的预测值之和为1,因此sigmoid函数最主要的作用就是将结果尽可能的仿射到0-1区间中

损失函数
![]()
sigmoid型函数是指一类S型曲线函数,两端饱和。其中最出名的是logistic函数,因此很多地方直接将sigmoid函数默认为logistic函数。
Logistic函数公式
Logistic函数的特点是区间范围在0~1之间,而且当x等于0时,其函数值为0.5,主要用作二分类。

Tanh函数公式
Tanh函数的特点是区间范围在-1~1之间,而且当x等于0时,其函数值为0


Hard-Logistic函数和Hard-Tanh函数

伪代码
1 Prepare dataset
2 Design model using Class
3 Construct loss and optimizer(Using Pytorch API)
4 Training cycle(forward,backward,update)
- import torch
-
- # 1 Prepare for the dataset
- x_data = torch.tensor([[1.0], [2.0], [3.0]])
- y_data = torch.tensor([[2.0], [4.0], [6.0]])
-
-
- # Define the Model
- class LinearModel(torch.nn.Module):
- def __init__(self):
- super(LinearModel, self).__init__() # 默认写法,一定要有
- self.linear = torch.nn.Linear(1, 1, bias=True)
- # 两个参数为输入和输出的维度,N*输入维度和N*输出维度,其模型为y=Ax+b线性模型,因此其输入输出的维度一定是一样的
- # bias为模型是否需要偏置b
-
- def forward(self, x):
- y_pred = self.linear(x) #
- return y_pred
- # 这里发现没有BP,这是因为使用Model构造出来的模型会根据你的计算图来自动进行BP
-
-
- model = LinearModel()
-
- # Define the criterion and optimizer
- criterion = torch.nn.MSELoss(size_average=False) # MSELoss是将所有的平方误差相加
- 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)
-
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
-
- # Output weight and bias
- print('w=', model.linear.weight.item())
- print('b=', model.linear.bias.item())
-
- # Test model
- x_test = torch.Tensor([[4.0]])
- y_test = model(x_test)
- print('y_pred=', y_test.data)
Result

最后预测的结果w接近2,而b接近0,这是与我们的数据集的情况相匹配的
- import torch
- import torchvision
- import torch.nn.functional as F
- import numpy as np
- import matplotlib.pyplot as plt
-
- # Prepare dataset
- x_data = torch.Tensor([[1.0], [2.0], [3.0]])
- y_data = torch.Tensor([[0], [0], [1]])
-
-
- # Define the 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()
-
- # Define the criterion 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:{:.6f}'.format(epoch, 1000, loss.item()))
- optimizer.zero_grad()
- loss.backward()
- optimizer.step()
-
- # Drawing
- 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.show()
Result

可以看到当x等于2.5的时候,预测值刚好为0.5。这是与我们的数据集是相匹配的
参考资料
《机器学习》周志华
《深度学习与机器学习》吴恩达
《神经网络与与深度学习》邱锡鹏
《Pytorch深度学习实战》刘二大人