### 手动构建 ResNet18 神经网络模型
以下是基于 PyTorch 和 TensorFlow 的两种实现方式。
#### 使用 PyTorch 构建 ResNet18 模型
PyTorch 提供了一种灵活的方式来定义神经网络架构。ResNet18 是一种经典的卷积神经网络,其核心在于残差模块的设计。以下是一个完整的 ResNet18 实现:
```python
import torch.nn as nn
import torch
class BasicBlock(nn.Module):
expansion = 1
def __init__(self, in_channels, out_channels, stride=1, downsample=None):
super(BasicBlock, self).__init__()
self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1, bias=False)
self.bn1 = nn.BatchNorm2d(out_channels)
self.relu = nn.ReLU(inplace=True)
self.conv2 = nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1, bias=False)
self.bn2 = nn.BatchNorm2d(out_channels)
self.downsample = downsample
def forward(self, x):
identity = x
out = self.conv1(x)
out = self.bn1(out)
out = self.relu(out)
out = self.conv2(out)
out = self.bn2(out)
if self.downsample is not None:
identity = self.downsample(x)
out += identity
out = self.relu(out)
return out
class ResNet18(nn.Module):
def __init__(self, block, layers, num_classes=10): # CIFAR-10 has 10 classes
super(ResNet18, self).__init__()
self.in_channels = 64
self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False) # Adjusted for CIFAR-10 input size
self.bn1 = nn.BatchNorm2d(64)
self.relu = nn.ReLU(inplace=True)
self.layer1 = self._make_layer(block, 64, layers[0], stride=1)
self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
self.fc = nn.Linear(512 * block.expansion, num_classes)
def _make_layer(self, block, out_channels, blocks, stride=1):
downsample = None
if stride != 1 or self.in_channels != out_channels * block.expansion:
downsample = nn.Sequential(
nn.Conv2d(self.in_channels, out_channels * block.expansion, kernel_size=1, stride=stride, bias=False),
nn.BatchNorm2d(out_channels * block.expansion),
)
layers = []
layers.append(block(self.in_channels, out_channels, stride, downsample))
self.in_channels = out_channels * block.expansion
for _ in range(1, blocks):
layers.append(block(self.in_channels, out_channels))
return nn.Sequential(*layers)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.fc(x)
return x
def resnet18(num_classes=10):
return ResNet18(BasicBlock, [2, 2, 2, 2], num_classes=num_classes)
```
上述代码实现了 ResNet18 模型的核心部分[^2]。通过 `resnet18` 函数可以实例化该模型并用于训练或推理。
---
#### 使用 TensorFlow/Keras 构建 ResNet18 模型
TensorFlow 中可以通过 Keras API 来快速搭建复杂的神经网络结构。下面展示了如何使用函数式 API 定义 ResNet18:
```python
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, ReLU, Add, GlobalAveragePooling2D, Dense
from tensorflow.keras.models import Model
def basic_block(inputs, filters, stride=1, downsample=None):
shortcut = inputs
x = Conv2D(filters=filters, kernel_size=(3, 3), strides=stride, padding='same', use_bias=False)(inputs)
x = BatchNormalization()(x)
x = ReLU()(x)
x = Conv2D(filters=filters, kernel_size=(3, 3), strides=1, padding='same', use_bias=False)(x)
x = BatchNormalization()(x)
if downsample is not None:
shortcut = downsample(shortcut)
x = Add()([x, shortcut])
x = ReLU()(x)
return x
def make_layer(inputs, filters, blocks, stride=1):
downsample = None
if stride != 1 or inputs.shape[-1] != filters:
downsample = lambda x: Conv2D(filters=filters, kernel_size=(1, 1), strides=stride, use_bias=False)(x)
x = basic_block(inputs, filters, stride, downsample)
for _ in range(1, blocks):
x = basic_block(x, filters)
return x
def resnet18(input_shape=(32, 32, 3), num_classes=10):
inputs = Input(shape=input_shape)
x = Conv2D(filters=64, kernel_size=(3, 3), strides=1, padding='same', use_bias=False)(inputs)
x = BatchNormalization()(x)
x = ReLU()(x)
x = make_layer(x, 64, 2, stride=1)
x = make_layer(x, 128, 2, stride=2)
x = make_layer(x, 256, 2, stride=2)
x = make_layer(x, 512, 2, stride=2)
x = GlobalAveragePooling2D()(x)
outputs = Dense(units=num_classes, activation='softmax')(x)
model = Model(inputs=inputs, outputs=outputs)
return model
model = resnet18()
model.summary()
```
此代码片段提供了 ResNet18 的完整实现,并支持自定义输入形状和类别数[^1]。
---
#### 加载预训练权重(可选)
如果希望加载已有的预训练权重,则可以在完成模型定义后调用相应接口。对于 PyTorch,可以直接利用官方提供的预训练模型;而对于 TensorFlow,则需下载对应的权重文件并应用到模型上。
---