pytorch系列 ---5以 linear_regression为例讲解神经网络实现基本步骤以及解读nn.Linear函数

本文详细解读了PyTorch中nn.Linear的源码,阐述了神经网络实现的基本步骤,并通过线性回归模型的训练过程,展示了损失函数随迭代变化的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文主要讲述最简单的线性回归函数:
y = w x + b y=wx+b y=wx+b在pytorch的实现,主要包括神经网络实现的基本步骤nn.Linear的源码解读

1. nn.Linear 源码解读

先看一下Linear类的实现:
源代码网址:https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html

Linear继承于nn.Module,内部函数主要有__init__reset_parameters, forwardextra_repr函数

在这里插入图片描述

  1. __init__(self, in_features, out_features, bias=True)
  • in_features:前一层网络神经元的个数
  • out_features: 该网络层神经元的个数
    以上两者决定了weight的形状[out_features , in_features]
  • bias: 网络层是否有偏置,默认存在,且维度为[out_features ],若bias=False,则该网络层无偏置。

接下来看一下,输入该网络层的形状(N, *, in_features),其中N为批量处理过成中每批数据的数量,*表示,单个样本数据中间可以包含很多维度,但是单个数据的最后一个维度的形状一定是in_features.

经过该网络输出的形状为(N, *, out_features),其中计算过程为:

[ N , ∗ , i n _ f e a t u r e s ] ∗ [ o u t _ f e a t u r e s , i n _ f e a t u r e s ] T = [ N , ∗ , o u t _ f e a t u r e s ] [N, *, in\_{features}] * {[out\_{features }, in\_{features}]}^T = [N, *, out\_{features}] [N,,in_features][out_features,

### 如何在 PyTorch实现 CNN-LSTM 架构 为了实现PyTorch 中构建 CNN-LSTM 的架构,可以遵循一种分步编码的方式。这种组合利用了卷积神经网络 (CNN) 提取局部特征的能力以及长短时记忆网络 (LSTM) 对时间序列数据处理的优势。 #### 定义模型类 定义一个继承自 `torch.nn.Module` 的 Python 类来创建 CNN-LSTM 结合的模型: ```python import torch from torch import nn, optim class CNNLSTM(nn.Module): def __init__(self, input_size, hidden_size, num_layers, output_size): super(CNNLSTM, self).__init__() # Define a convolutional layer with kernel size of 3 and stride of 1. self.conv = nn.Conv2d(in_channels=1, out_channels=input_size, kernel_size=(3, 3), padding='same') # LSTM Layer setup self.lstm = nn.LSTM(input_size=input_size, hidden_size=hidden_size, num_layers=num_layers, batch_first=True) # Fully connected layer to map from hidden state space to the number of classes or regression targets. self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): # Apply Convolution operation over time-series data reshaped appropriately for convolutions. c_out = self.conv(x.unsqueeze(1)) # Reshape tensor so that it can be fed into LSTM expecting dimensions [batch, sequence_length, features]. lstm_input = c_out.squeeze().permute(0, 2, 1) # Pass through LSTM layers getting outputs at each step as well as final states h_n,c_n which are not used here directly. lstm_output, _ = self.lstm(lstm_input) # Use only last time-step's output from LSTM for classification/regression task via fully-connected layer. fc_output = self.fc(lstm_output[:, -1, :]) return fc_output ``` 此代码片段展示了如何初始化 CNN 和 LSTM 层,并设置前向传播函数以完成从输入到输出的过程[^2]。 #### 准备训练过程 除了上述模型外,在实际操作中还需要准备好损失函数、优化器以及其他辅助工具以便于后续训练阶段的工作开展。如: ```python model = CNNLSTM(input_size=64, hidden_size=100, num_layers=2, output_size=10).to(device) loss_function = nn.CrossEntropyLoss() optimizer = optim.Adam(model.parameters(), lr=learning_rate) ``` 这里假设设备变量 (`device`) 已经被设定好指向 GPU 或 CPU;学习率 (`learning_rate`) 是预先指定好的超参数之一[^3]。 #### 训练循环 最后一步是编写训练循环逻辑,这通常涉及遍历整个数据集多次(即多个 epoch),对于每一批次的数据执行如下操作——传递给模型得到预测结果、计算误差、反向传播更新权重等。 以上就是在 PyTorch实现 CNN-LSTM 架构的方法概述[^4]。
评论 15
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值