• 3-2 中阶API示范


    下面的范例使用Pytorch的中阶API实现线性回归模型和和DNN二分类模型。
    Pytorch的中阶API主要包括各种模型层,损失函数,优化器,数据管道等等。
    在低阶API示范中,是采用原生方式模拟DataLoader:

    # 构建数据管道迭代器 模拟DataLoader
    def data_iter(features, labels, batch_size=8):
        num_examples = len(features)
        indices = list(range(num_examples)) # 构建一个列表
        np.random.shuffle(indices)  #样本的读取顺序是随机的
        for i in range(0, num_examples, batch_size): 
            indexs = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # 构建索引切片
            yield  features.index_select(0, indexs), labels.index_select(0, indexs) # yield用于生成
            
    # 测试数据管道效果   输出一个batch数据
    batch_size = 8
    (features,labels) = next(data_iter(X, Y, batch_size))  # 刚刚用了 yield 所以现在用 next 就可以输出每个batch的数据(下面循环)
    print(features)
    print(labels)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    而在中阶API中,会介绍 DataLoader 如何使用:

    #构建输入数据管道
    ds = TensorDataset(X,Y)
    dl = DataLoader(ds,batch_size = 10,shuffle=True,
                    num_workers=2)
    
    • 1
    • 2
    • 3
    • 4

    线性模型:
    在低阶API示范中,是采用原生方式模拟损失函数:

    # 定义模型
    class LinearRegression: 
        
        def __init__(self):
            # 初始化 形状一致
            self.w = torch.randn_like(w0,requires_grad=True)
            self.b = torch.zeros_like(b0,requires_grad=True) # 偏置初始化为0
            
        #正向传播
        def forward(self,x): 
            return x@self.w + self.b
    
        # 损失函数
        def loss_fn(self,y_pred,y_true):  
            return torch.mean((y_pred - y_true)**2/2)
    
    model = LinearRegression()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    中阶中,可以直接调用 损失函数:

    model = nn.Linear(2,1) #线性层
    
    model.loss_fn = nn.MSELoss()
    model.optimizer = torch.optim.SGD(model.parameters(),lr = 0.01) # 优化器
    
    • 1
    • 2
    • 3
    • 4

    DNN二分类模型:
    低阶:

    class DNNModel(nn.Module): # 深度神经网络 继承自 nn.Module
        def __init__(self):
            super(DNNModel, self).__init__()
            self.w1 = nn.Parameter(torch.randn(2,4))
            self.b1 = nn.Parameter(torch.zeros(1,4))
            self.w2 = nn.Parameter(torch.randn(4,8))
            self.b2 = nn.Parameter(torch.zeros(1,8))
            self.w3 = nn.Parameter(torch.randn(8,1))
            self.b3 = nn.Parameter(torch.zeros(1,1))
    
        # 正向传播
        def forward(self,x):
            x = torch.relu(x@self.w1 + self.b1)
            x = torch.relu(x@self.w2 + self.b2)
            y = torch.sigmoid(x@self.w3 + self.b3)
            return y
        
        # 损失函数(二元交叉熵)
        def loss_fn(self,y_pred,y_true):  
            #将预测值限制在1e-7以上, 1- (1e-7)以下,避免log(0)错误
            eps = 1e-7
            y_pred = torch.clamp(y_pred,eps,1.0-eps) # 将输入input张量每个元素的值压缩到区间 [min,max],并返回结果到一个新张量
            bce = - y_true*torch.log(y_pred) - (1-y_true)*torch.log(1-y_pred) # bce loss 公式
            return torch.mean(bce)
        
        # 评估指标(准确率)
        def metric_fn(self,y_pred,y_true):
            y_pred = torch.where(y_pred>0.5,torch.ones_like(y_pred,dtype = torch.float32), # 条件是 >0.5 那么就是返回1 否则返回0
                              torch.zeros_like(y_pred,dtype = torch.float32))
            acc = torch.mean(1-torch.abs(y_true-y_pred))
            return acc
        
    model = DNNModel()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    高阶:

    class DNNModel(nn.Module):
        def __init__(self):
            super(DNNModel, self).__init__()
            self.fc1 = nn.Linear(2,4) # 全连接层1
            self.fc2 = nn.Linear(4,8) # 全连接层2
            self.fc3 = nn.Linear(8,1) # 全连接层3
    
        # 正向传播
        def forward(self,x):
            x = F.relu(self.fc1(x))
            x = F.relu(self.fc2(x))
            y = nn.Sigmoid()(self.fc3(x))
            return y
        
        # 损失函数
        def loss_fn(self,y_pred,y_true):
            return nn.BCELoss()(y_pred,y_true)
        
        # 评估函数(准确率)
        def metric_fn(self,y_pred,y_true):
            y_pred = torch.where(y_pred>0.5,torch.ones_like(y_pred,dtype = torch.float32),
                              torch.zeros_like(y_pred,dtype = torch.float32))
            acc = torch.mean(1-torch.abs(y_true-y_pred))
            return acc
        
        # 优化器
        @property
        def optimizer(self):
            return torch.optim.Adam(self.parameters(),lr = 0.001)
        
    model = DNNModel()
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    参考:https://github.com/lyhue1991/eat_pytorch_in_20_days

  • 相关阅读:
    基于JavaWeb+SpringBoot+Vue医疗器械商城微信小程序系统的设计和实现
    后台开发核心技术与应用实践看书笔记(二):面向对象的C++
    CVE-2023-28303(截图修复)
    JAVA基础(JAVA SE)学习笔记(二)变量与运算符
    【SpringCloud微服务实战09】Elasticsearch 搜索引擎
    c++ 学习之类型,常量以及变量的重点知识
    20.1CubeMx配置FMC控制SDRAM【W9825G6KH-6】
    音视频会议需要哪些设备配置
    CAD图清晰打印设置
    TCP流量控制与拥塞控制(重要)
  • 原文地址:https://blog.csdn.net/hxhabcd123/article/details/132864672