pytorch实现逻辑回归

pytorch实现逻辑回归

  1. 数据准备,参数初始化
  2. 前向计算
  3. 计算损失
  4. 计算梯度
  5. 更新参数

在官网上找到线性函数的公式表达式

python 复制代码
import torch
from sklearn.datasets import load_iris
# from sklearn.model_selection import train_test_split #train_test_split是sklearn中的一个函数,作用是将数据集划分为训练集和测试集
python 复制代码
#数据准备
X, y = load_iris(return_X_y=True) #加载数据,X,y分别为特征和标签
X = X[:100] #取前100个样本
y = y[:100] #取前100个样本

#创建张量数据集
tensor_x = torch.tensor(X, dtype=torch.float32)
tensor_y = torch.tensor(y, dtype=torch.float32)

#超参数设置
learning_rate = 0.001
epochs = 500

#模型参数
w = torch.randn(1, 4, requires_grad=True) #requires_grad=True表示w需要求导,1表示输出维度,4表示输入维度
b = torch.randn(1, requires_grad=True) #1表示输出维度

【注】

  1. 张量是一种容器
  2. 张量也是一种计算的方法,或说操作
  3. grad属性,梯度属性,保存参数梯度值
python 复制代码
for i in range(epochs):  
    #前向计算
    z = torch.nn.functional.linear(tensor_x, w, b) #线性函数计算
    #z = torch.matmul(tensor_x, w.t()) + b #线性函数计算
    z = torch.sigmoid(z) #线性函数转为概率函数0-1之间
    #损失函数
    loss = torch.nn.functional.binary_cross_entropy(z.reshape(-1), tensor_y,reduction='mean') #二分类交叉熵损失函数
    #reduction='mean'表示对每个样本的损失求均值
    
    #计算梯度
    loss.backward() #计算梯度、梯度保存在w.grad和b.grad中

    #参数更新
    #with torch.no_grad()表示不需要梯度跟踪,不需要计算梯度,不需要梯度更新
    #with关键字是上下文管理器,用于简化资源管理,确保资源被及时释放(可以理解为作用域)
    with torch.no_grad(): #梯度清零,关闭梯度计算跟踪,防止梯度累加
        w -= learning_rate * w.grad
        b -= learning_rate * b.grad
        #梯度清零                
        w.grad.zero_()
        b.grad.zero_()

    #训练动态损失
    print('train loss:' ,loss.item())
复制代码
train loss: 0.9154033064842224
train loss: 0.9093276262283325
train loss: 0.9033000469207764
train loss: 0.8973206877708435
train loss: 0.891389787197113
train loss: 0.8855075240135193
train loss: 0.8796738982200623
train loss: 0.873889148235321
train loss: 0.8681536912918091

             ......
train loss: 0.37976446747779846
train loss: 0.37959033250808716
train loss: 0.3794163167476654
train loss: 0.379242479801178
train loss: 0.3790687322616577
train loss: 0.37889519333839417
train loss: 0.378721684217453
train loss: 0.37854844331741333
train loss: 0.3783752918243408
train loss: 0.37820228934288025
python 复制代码
w.grad #查看w的梯度
复制代码
tensor([[0., 0., 0., 0.]])

二元交叉熵计算损失维度要相同,不然报错,去掉维度

z.reshape(-1).shape #将z展平

z.squeeze().shape #将z压缩(去掉维度为1的维度)


torch.Size([100])

完整代码

python 复制代码
import torch
from sklearn.datasets import load_iris
#数据准备
X, y = load_iris(return_X_y=True) 
X = X[:100] 
y = y[:100] 

#创建张量数据集
tensor_x = torch.tensor(X, dtype=torch.float32)
tensor_y = torch.tensor(y, dtype=torch.float32)

#超参数设置
learning_rate = 0.001
epochs = 500

#模型参数
w = torch.randn(1, 4, requires_grad=True) 
b = torch.randn(1, requires_grad=True) 

for i in range(epochs):  
    #前向计算
    z = torch.nn.functional.linear(tensor_x, w, b) 
    z = torch.sigmoid(z) 
    #损失函数
    loss = torch.nn.functional.binary_cross_entropy(z.reshape(-1), tensor_y,reduction='mean')
    
    #计算梯度
    loss.backward() 

    #参数更新
    with torch.no_grad(): 
        w -= learning_rate * w.grad
        b -= learning_rate * b.grad
        #梯度清零                
        w.grad.zero_()
        b.grad.zero_()

    #训练动态损失
    print('train loss:' ,loss.item())
相关推荐
亦复何言??1 分钟前
BeyondMimic 论文解析
人工智能·算法·机器人
深蓝海拓3 分钟前
使用@property将类方法包装为属性
开发语言·python
Lee川4 分钟前
🛠️ LangChain Tools 实战指南:让 AI 拥有“动手能力”
人工智能
gorgeous(๑>؂<๑)5 分钟前
【CVPR26-索尼】EW-DETR:通过增量低秩检测Transformer实现动态世界目标检测
人工智能·深度学习·目标检测·计算机视觉·transformer
xianluohuanxiang9 分钟前
新能源功率预测的“生死局”:从“能报曲线”到“能做收益”,中间差的不是一点算法
人工智能
码农垦荒笔记26 分钟前
Claude Code 2026 年 3 月全面进化:Auto 模式、Computer Use 与云端持续执行重塑 AI 编程工作流
人工智能·ai 编程·claude code·agentic coding·computer use
threerocks32 分钟前
【Claude Code 系列课程】01 | Claude Code 架构全览
人工智能·ai编程·claude
熊猫代跑得快34 分钟前
Agent 通用架构入门学习
人工智能·agent·智能体
格林威34 分钟前
Baumer相机锂电池极片裁切毛刺检测:防止内部短路的 5 个核心方法,附 OpenCV+Halcon 实战代码!
开发语言·人工智能·数码相机·opencv·计算机视觉·c#·视觉检测
codeの诱惑37 分钟前
推荐算法(一):数学基础回顾——勾股定理与欧氏距离
算法·机器学习·推荐算法