python
复制代码
import torch
import torch.nn as nn
import torch.nn.functional as F
class SimpleCNN(nn.Module):
def __init__(self):
super(SimpleCNN, self).__init__()
# 1. 卷积层 (Convolutional Layer)
# 输入: 1个通道(灰度图), 输出: 32个特征图, 卷积核: 3x3
self.conv1 = nn.Conv2d(in_channels=1, out_channels=32, kernel_size=3, padding=1)
# 2. 池化层 (Pooling Layer)
# 2x2 最大池化,将图片尺寸减半
self.pool = nn.MaxPool2d(kernel_size=2, stride=2)
# 3. 全连接层 (Fully Connected Layer)
# 假设输入图片是 28x28:
# 经过 conv1 (padding=1) -> 28x28
# 经过 pool -> 14x14
# 所以展平后的维度是: 32(通道) * 14 * 14
self.fc1 = nn.Linear(32 * 14 * 14, 10) # 输出 10 个类别 (例如数字 0-9)
def forward(self, x):
# 前向传播逻辑
x = self.conv1(x)
x = F.relu(x) # 激活函数
x = self.pool(x) # 下采样
x = x.view(-1, 32 * 14 * 14) # 展平 (Flatten)
x = self.fc1(x)
return x
# --- 测试代码 ---
# 创建模型实例
model = SimpleCNN()
print(model)
# 模拟一张随机生成的图片 (Batch_size=1, Channel=1, Height=28, Width=28)
dummy_input = torch.randn(1, 1, 28, 28)
output = model(dummy_input)
print(f"\n输出形状: {output.shape}") # 应该是 [1, 10]
import tensorflow as tf
from tensorflow.keras import layers, models
def create_simple_cnn():
model = models.Sequential()
# 1. 卷积层 + 激活函数
# input_shape=(28, 28, 1) 对应 高, 宽, 通道数
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
# 2. 池化层
model.add(layers.MaxPooling2D((2, 2)))
# 3. 展平层 (把多维特征图变成一维向量)
model.add(layers.Flatten())
# 4. 全连接层 (输出层)
model.add(layers.Dense(10, activation='softmax')) # 10个类别
return model
# --- 测试代码 ---
model = create_simple_cnn()
# 打印模型结构概览
model.summary()