Logistic回归这样写Loss函数为什么不收敛?

476 次浏览0个评论2021年07月19日
import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random
num_inputs = 2
num_examples = 100
n_data = torch.ones(50, 2)
x1 = torch.normal(2 * n_data, 1) 
y1 = torch.zeros(50) 
x2 = torch.normal(-2 * n_data, 1) 
y2 = torch.ones(50) 
features = torch.cat((x1, x2), 0).type(torch.FloatTensor)
labels = torch.cat((y1, y2), 0).type(torch.FloatTensor)
num_inputs = 2
def data_iter(batch_size, features, labels):
    num_examples = len(features)
    indices = list(range(num_examples))
    random.shuffle(indices) # 样本的读取顺序是随机的
    for i in range(0, num_examples, batch_size):
        j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) 
        yield features.index_select(0, j), labels.index_select(0, j)
w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)
w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
def logreg(X, w, b):
    return 1/(1+torch.exp(-(torch.mm(X, w) + b)))
def ce_loss(y_hat, y): 
    return -(y*torch.log(y_hat)+(1-y)*torch.log(1-y_hat))
def sgd(params, lr, batch_size):
    for param in params:
        param.data -= lr * param.grad / batch_size
lr = 0.01
num_epochs = 200
batch_size=10
net = logreg
loss = ce_loss
CELoss = []
for epoch in range(num_epochs): # 训练模型一共需要num_epochs个迭代周期
# 在每一个迭代周期中,会使用训练数据集中所有样本一次
    for X, y in data_iter(batch_size, features, labels): # x和y分别是小批量样本的特征和标签
        l = loss(net(X, w, b), y).sum() # l是有关小批量X和y的损失
        l.backward() # 小批量的损失对模型参数求梯度
        sgd([w, b], lr, batch_size) # 使用小批量随机梯度下降迭代模型参数
        w.grad.data.zero_() # 梯度清零
        b.grad.data.zero_()
    train_l = loss(net(features, w, b), labels)
    CELoss.append(train_l.mean().item())
    print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))
plt.plot(CELoss)
plt.ylabel("CELoss")
plt.xlabel("epoch")
plt.show()

编译运行得到Loss-epoch图像,是发散的。

提交评论

请登录后评论

用户评论

    当前暂无评价,快来发表您的观点吧...

更多相关好文

    当前暂无更多相关好文推荐...

    公告提示

    Pytorch是Facebook的AI研究团队发布了一个Python工具包,是Python优先的深度学习框架。作为numpy的替代品;使用强大的GPU能力,提供最大的灵活性和速度,实现了机器学习框架Torch在Python语言环境的执行,基于python且具备强大GPU加速的张量和动态神经网络。