Pytorch框架下的CNN和RNN

1.CNN

建立了3层(3层=2层+1层全连接层)。分别是conv1、conv2和分类问题中的全连接层线性层out

c 复制代码
class CNN(nn.Module):
    def __init__(self):
        super(CNN, self).__init__()
        self.conv1 = nn.Sequential(         # input shape (1, 28, 28)
            nn.Conv2d(
                in_channels=1,              # input height
                out_channels=16,            # n_filters
                kernel_size=5,              # filter size
                stride=1,                   # filter movement/step
                padding=2,                  # if want same width and length of this image after Conv2d, padding=(kernel_size-1)/2 if stride=1
            ),                              # output shape (16, 28, 28)
            nn.ReLU(),                      # activation
            nn.MaxPool2d(kernel_size=2),    # choose max value in 2x2 area, output shape (16, 14, 14)
        )
        self.conv2 = nn.Sequential(         # input shape (16, 14, 14)
            nn.Conv2d(16, 32, 5, 1, 2),     # output shape (32, 14, 14)
            nn.ReLU(),                      # activation
            nn.MaxPool2d(2),                # output shape (32, 7, 7)
        )
        self.out = nn.Linear(32 * 7 * 7, 10)   # fully connected layer, output 10 classes

    def forward(self, x):
        x = self.conv1(x)
        x = self.conv2(x)
        x = x.view(x.size(0), -1)           # flatten the output of conv2 to (batch_size, 32 * 7 * 7)
        output = self.out(x)
        return output, x    # return x for visualization

2.RNN

2.1RNN分类问题代码

设计了rnn层【输入(INPUT_SIZE),隐藏层1层(hidden_size)】和分类问题的全连接线性层out

c 复制代码
class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.LSTM(     # LSTM 效果要比 nn.RNN() 好多了
            input_size=28,      # 图片每行的数据像素点
            hidden_size=64,     # rnn hidden unit
            num_layers=1,       # 有几层 RNN layers
            batch_first=True,   # input & output 会是以 batch size 为第一维度的特征集 e.g. (batch, time_step, input_size)
        )

        self.out = nn.Linear(64, 10)    # 输出层

    def forward(self, x):
        # x shape (batch, time_step, input_size)
        # r_out shape (batch, time_step, output_size)
        # h_n shape (n_layers, batch, hidden_size)   LSTM 有两个 hidden states, h_n 是分线, h_c 是主线
        # h_c shape (n_layers, batch, hidden_size)
        r_out, (h_n, h_c) = self.rnn(x, None)   # None 表示 hidden state 会用全0的 state

        # 选取最后一个时间点的 r_out 输出
        # 这里 r_out[:, -1, :] 的值也是 h_n 的值
        out = self.out(r_out[:, -1, :])
        return out

rnn = RNN()
print(rnn)
"""
RNN (
  (rnn): LSTM(28, 64, batch_first=True)
  (out): Linear (64 -> 10)
)
"""

2.2RNN回归问题代码

具体参考:https://mofanpy.com/tutorials/machine-learning/torch/RNN-regression

c 复制代码
class RNN(nn.Module):
    def __init__(self):
        super(RNN, self).__init__()

        self.rnn = nn.RNN(  # 这回一个普通的 RNN 就能胜任
            input_size=1,
            hidden_size=32,     # rnn hidden unit
            num_layers=1,       # 有几层 RNN layers
            batch_first=True,   # input & output 会是以 batch size 为第一维度的特征集 e.g. (batch, time_step, input_size)
        )
        self.out = nn.Linear(32, 1)

    def forward(self, x, h_state):  # 因为 hidden state 是连续的, 所以我们要一直传递这一个 state
        # x (batch, time_step, input_size)
        # h_state (n_layers, batch, hidden_size)
        # r_out (batch, time_step, output_size)
        r_out, h_state = self.rnn(x, h_state)   # h_state 也要作为 RNN 的一个输入

        outs = []    # 保存所有时间点的预测值
        for time_step in range(r_out.size(1)):    # 对每一个时间点计算 output
            outs.append(self.out(r_out[:, time_step, :]))
        return torch.stack(outs, dim=1), h_state


rnn = RNN()
print(rnn)
"""
RNN (
  (rnn): RNN(1, 32, batch_first=True)
  (out): Linear (32 -> 1)
)
"""
相关推荐
yzx9910137 小时前
[特殊字符] AI画廊:基于CNN的实时艺术风格迁移系统
人工智能·神经网络·cnn
Buxxxxxx9 小时前
DAY 44 简单CNN
人工智能·神经网络·cnn
机器学习之心10 小时前
BO-CNN-BiLSTM贝叶斯优化卷积双向长短期记忆神经网络多输入多输出预测,MATLAB代码
神经网络·matlab·cnn·bo-cnn-bilstm
AI即插即用11 小时前
即插即用系列 | CVPR 2025 FDConv:频域动态卷积,打破密集预测任务的参数效率瓶颈
图像处理·人工智能·深度学习·神经网络·计算机视觉·cnn·视觉检测
natide12 小时前
表示/嵌入差异-1-欧几里得距离(Euclidean Distance)-L2 距离(L2 distance)-欧式距离的标准化
人工智能·pytorch·python·深度学习·算法·自然语言处理
Pyeako13 小时前
深度学习--CUDA安装配置、pytorch库、torchvision库、torchaudio库安装
人工智能·pytorch·python·深度学习·gpu·cuda
小杨互联网13 小时前
PyTorch分布式训练实战:从零构建Llama模型多GPU训练系统
人工智能·pytorch·llama
一只大侠的侠13 小时前
融合Transformer与CNN的多模态时间序列预测模型
深度学习·cnn·transformer
小龙13 小时前
【学习笔记】PyTorch 中.pth文件格式解析与可视化
人工智能·pytorch·笔记·学习
悟道心13 小时前
3.自然语言处理NLP - RNN及其变体
人工智能·rnn·自然语言处理