用来分类的模型
说明:1、 逻辑斯蒂回归和线性模型的明显区别是在线性模型的后面,添加了激活函数(非线性变换)
2、分布的差异:KL散度,cross-entropy交叉熵
现在损失函数衡量不是距离而是分布,所以要改为交叉熵
sigmod的函数是一个在生物学中常见的S型函数,也称为S型生长曲线。在信息科学中,由于其单增以及反函数单增等性质,常被用作神经网络的激活函数,将变量映射到0,1之间。-------------摘自《百度百科》
sigmod函数也叫作Logistic函数,用于隐层神经单元输出,取值范围为(0,1),它可以将一个实数映射到(0,1)的区间,可以用来做二分类。在特征相差比较复杂或者相差不是特别大的时候效果比较好。
类实现:
python
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))
y_pred = torch.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
总python实现
python
import torch
# prepare dataset
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])
# design model using class
class LogisticModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = torch.sigmoid(self.linear(x))#线性层后面加一层非线性SIGMOD激活函数
return y_pred
logistic = LogisticModel()
# construct loss and optimizer
# reduction='mean'取平均 reduction='sum'求和 loss被累加
criterion = torch.nn.BCELoss(reduction='sum')
optimizer = torch.optim.SGD(logistic.parameters(), lr=0.01)
# training cycle forward, backward, update
for epoch in range(1000):
y_pred = logistic(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print("w= ", logistic.linear.weight.item())
print("b= ", logistic.linear.bias.item())
x_test = torch.Tensor([4.0])
y_pred = logistic(x_test)
print("y_pred= ", y_pred)