resnet-50项目实例
时间: 2024-12-30 08:29:37 浏览: 15
### ResNet-50 实现概述
ResNet-50 是一种深度残差网络,在图像分类任务上表现出色。该模型通过引入跳跃连接解决了深层网络中的梯度消失问题[^3]。
#### 使用 PyTorch 的 ResNet-50 示例代码
以下是基于 PyTorch 构建并训练 ResNet-50 模型的一个简单例子:
```python
import torch
from torchvision import models, transforms
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
import torch.nn as nn
import torch.optim as optim
def train_model(model, criterion, optimizer, dataloaders, device='cuda', num_epochs=25):
model.to(device)
for epoch in range(num_epochs):
print(f'Epoch {epoch}/{num_epochs - 1}')
print('-' * 10)
for phase in ['train']:
if phase == 'train':
model.train()
running_loss = 0.0
running_corrects = 0
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
if phase == 'train':
optimizer.zero_grad()
loss.backward()
optimizer.step()
_, preds = torch.max(outputs, 1)
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
epoch_loss = running_loss / len(dataloaders[phase].dataset)
epoch_acc = running_corrects.double() / len(dataloaders[phase].dataset)
print(f'{phase} Loss: {epoch_loss:.4f} Acc: {epoch_acc:.4f}')
data_transforms = {
'train': transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
image_datasets = {'train': CIFAR10(root='./data', train=True,
download=True, transform=data_transforms['train'])}
dataloaders_dict = {'train': DataLoader(image_datasets[x], batch_size=4,
shuffle=True, num_workers=4)}
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
model_ft = models.resnet50(pretrained=True)
num_ftrs = model_ft.fc.in_features
model_ft.fc = nn.Linear(num_ftrs, 10) # 修改最后一层全连接层适应CIFAR-10数据集类别数量
criterion = nn.CrossEntropyLoss()
optimizer_ft = optim.SGD(model_ft.parameters(), lr=0.001, momentum=0.9)
model_ft = train_model(model_ft, criterion, optimizer_ft, dataloaders=dataloaders_dict)
```
此段代码展示了如何加载预训练的 ResNet-50 并针对特定的数据集调整最后几层以适配新的分类任务,同时设置了简单的训练循环来进行微调[^2]。
#### 使用 TensorFlow/Keras 的 ResNet-50 示例代码
对于那些更倾向于使用 TensorFlow 或 Keras API 来构建和训练模型的人来说,下面是一个类似的实现方式:
```python
import tensorflow as tf
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.layers import Dense, GlobalAveragePooling2D
from tensorflow.keras.models import Model
from tensorflow.keras.preprocessing.image import ImageDataGenerator
base_model = ResNet50(weights='imagenet', include_top=False)
x = base_model.output
x = GlobalAveragePooling2D()(x)
predictions = Dense(10, activation='softmax')(x)
model = Model(inputs=base_model.input, outputs=predictions)
for layer in base_model.layers:
layer.trainable = False
datagen = ImageDataGenerator(
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True)
train_generator = datagen.flow_from_directory(
'./data/train',
target_size=(224, 224),
batch_size=32,
class_mode='categorical')
model.compile(optimizer='adam', loss='categorical_crossentropy')
model.fit(train_generator, epochs=10)
```
这段代码同样实现了迁移学习的过程,其中冻结了原始 ResNet 层,并只对新添加的部分进行了训练[^1]。
阅读全文