Logistic回归这样写Loss函数为什么不收敛?
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图像,是发散的。
用户评论
当前暂无评价,快来发表您的观点吧...
更多相关好文
当前暂无更多相关好文推荐...
-
微信公众号文章/菜单添加小程序时路径如何获取? 2021-12-22
-
如何轻松获取微信小程序路径path? 2021-12-22
-
cannot import name 'CUDA_HOME' from 'mmcv.utils' 2021-12-05
-
vgg的loss一轮达到ln(1/n)阈值,如何解决 2021-11-21
-
如何下载使用utils库 2021-10-27
热门文章
-
cannot import name 'CUDA_HOME' from 'mmcv.utils' 2021-12-05
-
vgg的loss一轮达到ln(1/n)阈值,如何解决 2021-11-21
-
如何下载使用utils库 2021-10-27
-
pytorch调用geforce rtx 3060 2021-10-24
-
pytorch中如何实现多模型的并联 2021-09-15
栏目最新文章
公告提示
- pytorch中文文档
- pytorch官方文档
提交评论