Pytorch:LogisticRegression

该博客通过PyTorch构建了一个简单的逻辑回归模型,用于预测学生是否通过考试。数据集包含三个小时的学习时间,模型训练了1000个周期,并在0到10小时的时间范围内进行了预测。训练过程中使用了二元交叉熵损失函数和随机梯度下降优化器。最终,模型的预测概率被绘制出来,与及格概率线进行对比。

loss Funct

在这里插入图片描述
在这里插入图片描述

代码

import numpy as np
import torch
import torch.nn.functional as F
import matplotlib.pyplot as plt
#1.Prepare dataset
x_data=torch.Tensor([[1.0],[2.0],[3.0]])
y_data=torch.Tensor([[0],[0],[1]])
#----------------------------------------------------#
#2.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_predict=torch.sigmoid(self.Linear(x))
        return y_predict

model=LogisticRegressionModel()
#----------------------------------------------------#
#3.Construct loss and optimizer
creterion=torch.nn.BCELoss(size_average=False)
optimizer=torch.optim.SGD(model.parameters(),lr=0.01)
#----------------------------------------------------#
#4.Training cycle:forward, backward, update
for epoch in range(1000):
    y_predict=model(x_data)
    loss=creterion(y_predict,y_data)
    print(epoch,loss.item())

    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
#----------------------------------------------------#
#test
x=np.linspace(0,10,200)
x_t=torch.Tensor(x).view(200,1)#相当于reshape
y_t=model(x_t)
y=y_t.data.numpy()
plt.plot(x,y)
plt.plot([0,10],[0.5,0.5],c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()

在这里插入图片描述

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值