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)
)
"""
相关推荐
weixin_468466852 小时前
PyTorch导出ONNX格式分割模型及在C#中调用预测
人工智能·pytorch·深度学习·c#·跨平台·onnx·语义分割
软件算法开发2 小时前
基于火烈鸟搜索算法的LSTM网络模型(FSA-LSTM)的一维时间序列预测matlab仿真
人工智能·rnn·matlab·lstm·一维时间序列预测·火烈鸟搜索算法·fsa-lstm
七夜zippoe1 天前
PyTorch深度革命:从自动微分到企业级应用
人工智能·pytorch·python
好的收到1111 天前
PyTorch深度学习(小土堆)笔记3:小土堆 Dataset 类实战笔记,99% 的新手都踩坑!看完秒懂数据加载底层逻辑!
pytorch·笔记·深度学习
小lo想吃棒棒糖1 天前
思路启发:超越Transformer的无限上下文:SSM-Attention混合架构的理论分析
人工智能·pytorch·python
Lun3866buzha1 天前
内窥镜设备部件检测与识别——基于Mask R-CNN的改进模型训练与实现
开发语言·r语言·cnn
2401_828890641 天前
实现变分自编码器 VAE- MNIST 数据集
人工智能·python·深度学习·cnn·transformer
民乐团扒谱机1 天前
【读论文】深度学习中的卷积算术指南 A guide to convolution arithmetic for deep learning
人工智能·深度学习·神经网络·机器学习·cnn·卷积神经网络·图像识别
励ℳ2 天前
【CNN网络入门】基于PyTorch的MNIST手写数字识别:从数据准备到模型部署全流程详解
人工智能·pytorch·深度学习
eqXUIrcRQM2 天前
汇川H3U实用程序框架:工程实战与跨品牌借鉴
cnn