逻辑斯蒂回归和线性模型的明显区别是在线性模型的后面,添加了激活函数(非线性变换)
分布的差异:KL散度,cross-entropy交叉熵。
BCELoss(Binary CrossEntropyLoss ) 是CrossEntropyLoss的一个特例,只用于二分类问题,而CrossEntropyLoss可以用于二分类,也可以用于多分类。如果是二分类问题,建议BCELoss。
如果预测与标签越接近,BCE损失越小。
###代码实现
import torch
# prepare dataset
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[0.0], [0.0], [1.0]])
#design model using class
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 = torch.sigmoid(self.linear(x)) # 在线性的外面套sigmoid函数
return y_pred
model = LogisticRegressionModel()
# construct loss and optimizer
criterion = torch.nn.BCELoss(reduction = 'sum')
optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)
# training cycle forward, backward, update
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
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)
参考博客:https://blog.csdn.net/bit452/article/details/109680909