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())
相关推荐
却道天凉_好个秋26 分钟前
深度学习(二):神经元与神经网络
人工智能·神经网络·计算机视觉·神经元
UQI-LIUWJ27 分钟前
unsloth笔记:运行&微调 gemma
人工智能·笔记·深度学习
XiaoMu_00127 分钟前
基于Python+Streamlit的旅游数据分析与预测系统:从数据可视化到机器学习预测的完整实现
python·信息可视化·旅游
THMAIL30 分钟前
深度学习从入门到精通 - 生成对抗网络(GAN)实战:创造逼真图像的魔法艺术
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·cnn
却道天凉_好个秋32 分钟前
计算机视觉(八):开运算和闭运算
人工智能·计算机视觉·开运算与闭运算
无风听海33 分钟前
神经网络之深入理解偏置
人工智能·神经网络·机器学习·偏置
JoinApper34 分钟前
目标检测系列-Yolov5下载及运行
人工智能·yolo·目标检测
北京地铁1号线1 小时前
GPT(Generative Pre-trained Transformer)模型架构与损失函数介绍
gpt·深度学习·transformer
飞哥数智坊1 小时前
即梦4.0实测:我真想对PS说“拜拜”了!
人工智能
fantasy_arch1 小时前
9.3深度循环神经网络
人工智能·rnn·深度学习