花卉分类resnet
时间: 2024-12-25 18:20:01 浏览: 4
### 使用ResNet实现花卉图像分类
#### 准备工作
为了使用ResNet进行花卉分类,需先准备环境并加载必要的库。确保安装了PyTorch和其他依赖项。
```bash
pip install torch torchvision matplotlib numpy pandas scikit-learn
```
#### 数据预处理
数据集通常需要经过标准化和增强来提高模型泛化能力。对于224×224大小的图片,在训练过程中应用随机裁剪、水平翻转等操作可以增加样本多样性[^1]。
```python
from torchvision import transforms
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])
]),
'val': transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
```
#### 加载数据集
假设已下载好Flowers17或类似的花卉数据集,并将其分为训练集和验证集两个部分。
```python
import os
from torchvision.datasets.folder import ImageFolder
from torch.utils.data import DataLoader
image_datasets = {x: ImageFolder(os.path.join(data_dir, x), data_transforms[x]) for x in ['train', 'val']}
dataloaders = {x: DataLoader(image_datasets[x], batch_size=4, shuffle=True, num_workers=4) for x in ['train', 'val']}
dataset_sizes = {x: len(image_datasets[x]) for x in ['train', 'val']}
class_names = image_datasets['train'].classes
```
#### 定义模型
采用预训练过的ResNet作为基础网络,冻结其参数以利用迁移学习的优势,仅微调最后几层适应新的类别数量。
```python
import torch.nn as nn
from torchvision.models.resnet import resnet50
model_conv = resnet50(pretrained=True)
for param in model_conv.parameters():
param.requires_grad = False
num_ftrs = model_conv.fc.in_features
model_conv.fc = nn.Linear(num_ftrs, len(class_names))
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model_conv = model_conv.to(device)
```
#### 设置优化器与损失函数
选择合适的优化算法(如SGD),设置初始学习率为0.001,并定义交叉熵损失用于多类别的预测任务。
```python
criterion = nn.CrossEntropyLoss()
optimizer_ft = optim.SGD(model_conv.fc.parameters(), lr=0.001, momentum=0.9)
exp_lr_scheduler = lr_scheduler.StepLR(optimizer_ft, step_size=7, gamma=0.1)
```
#### 开始训练过程
通过循环迭代整个数据集多次来进行训练,期间记录下每次epoch的最佳性能指标以便后续评估。
```python
def train_model(model, criterion, optimizer, scheduler, num_epochs=25):
best_acc = 0.0
for epoch in range(num_epochs):
print(f'Epoch {epoch}/{num_epochs - 1}')
print('-' * 10)
# Each epoch has a training and validation phase
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
running_corrects = 0
# Iterate over data.
for inputs, labels in dataloaders[phase]:
inputs = inputs.to(device)
labels = labels.to(device)
# zero the parameter gradients
optimizer.zero_grad()
# forward
with torch.set_grad_enabled(phase == 'train'):
outputs = model(inputs)
_, preds = torch.max(outputs, 1)
loss = criterion(outputs, labels)
# backward + optimize only if in training phase
if phase == 'train':
loss.backward()
optimizer.step()
# statistics
running_loss += loss.item() * inputs.size(0)
running_corrects += torch.sum(preds == labels.data)
if phase == 'train':
scheduler.step()
epoch_loss = running_loss / dataset_sizes[phase]
epoch_acc = running_corrects.double() / dataset_sizes[phase]
print('{} Loss: {:.4f} Acc: {:.4f}'.format(
phase, epoch_loss, epoch_acc))
# deep copy the model
if phase == 'val' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(model.state_dict())
print()
print('Best val Acc: {:4f}'.format(best_acc))
# load best model weights
model.load_state_dict(best_model_wts)
return model
```
执行上述代码片段即可启动训练流程,最终获得针对特定花卉种类定制化的ResNet模型实例[^3]。
阅读全文