Pytorch Logistic Regresstion模型实现(分类)——up主:刘二大人《PyTorch深度学习实践》

b站up主:刘二大人《PyTorch深度学习实践》
教程: https://www.bilibili.com/video/BV1Y7411d7Ys?p=6&vd_source=715b347a0d6cb8aa3822e5a102f366fe
线性回归模型 : t o r c h . n n . L i n e a r 激活函数: t o r c h . s i g m o i d 交叉熵损失函数: n n . B C E L o s s 优化器: o p t i m . A d a m 数据集: x d a t a = t o r c h . T e n s o r ( [ [ 1.0 ] , [ 2.0 ] , [ 3.0 ] ] ) y d a t a = t o r c h . T e n s o r ( [ [ 0 ] , [ 0 ] , [ 1 ] ] ) 线性回归模型:torch.nn.Linear \\激活函数:torch.sigmoid \\交叉熵损失函数:nn.BCELoss \\优化器:optim.Adam \\数据集:x_{data} = torch.Tensor([[1.0],[2.0],[3.0]]) \\y_{data} = torch.Tensor([[0],[0],[1]]) 线性回归模型:torch.nn.Linear激活函数:torch.sigmoid交叉熵损失函数:nn.BCELoss优化器:optim.Adam数据集:xdata=torch.Tensor([[1.0],[2.0],[3.0]])ydata=torch.Tensor([[0],[0],[1]])

import torch
import matplotlib.pyplot as plt

#数据集
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[0],[0],[1]])

epoch_p = []
loss_p = []

#设计模型
class Model(torch.nn.Module):
  def __init__(self):
    super(Model, self).__init__()
    self.linear = torch.nn.Linear(1, 1)

  def forward(self, x):
    #加入sigmoid函数
    y_pred = torch.sigmoid(self.linear(x))
    return y_pred

model = Model()

#构造损失函数和优化器
criterion = torch.nn.BCELoss() #交叉熵损失函数,计算概率损失
optimizer = torch.optim.Adam(model.parameters(), lr = 0.01)

#train
for epoch in range(5000):
  y_pred = model(x_data)
  loss = criterion(y_pred, y_data)
  loss_p.append(loss.item())
  epoch_p.append(epoch)
  print("第{}个Epoch,loss = {:.6f}".format(epoch, loss))

  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

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.item())

plt.figure()
plt.plot(epoch_p, loss_p, c = 'b')
plt.xlabel('Epoch')
plt.ylabel('loss')
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值