阅读以下代码
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import models, transforms
from torchvision.models import resnet50, ResNet50_Weights
from PIL import Image
import json
from torch.cuda.amp import autocast, GradScaler # 引入AMP模块
自定义数据集类
class GameDataset(Dataset):
def init(self, images, actions, transform=None):
self.images = images
self.actions = actions
self.transform = transform
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
image = self.images[idx]
action = self.actions[idx]
if self.transform:
image = self.transform(image)
return image, action
图像预处理的变换
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
准备数据
images_folder = 'c:\dnf\dd' # 替换为你的图像文件夹路径
actions_folder = 'c:\map' # 替换为你的动作txt文件夹路径
获取目录中的所有图像文件和动作文件
images_files = sorted(os.listdir(images_folder))
actions_files = sorted(os.listdir(actions_folder))
images = []
actions = []
遍历图像文件并加载图片和对应的动作
for img_file, action_file in zip(images_files, actions_files):
# 加载图像
img_path = os.path.join(images_folder, img_file)
image = Image.open(img_path).convert('RGB') # 确保图像是RGB格式
images.append(image)
# 加载动作
action_path = os.path.join(actions_folder, action_file)
with open(action_path, 'r') as f:
action = int(f.readline().strip())
actions.append(action)
检查是否加载了相同数量的图像和动作
assert len(images) == len(actions), "图像文件和动作文件的数量不匹配"
创建标签映射字典
unique_actions = sorted(set(actions))
label_map = {label: idx for idx, label in enumerate(unique_actions)}
inverse_label_map = {idx: label for label, idx in label_map.items()}
将标签值转换为连续整数
actions = [label_map[action] for action in actions]
保存映射关系到文件
with open('label_mapping.json', 'w') as f:
json.dump(label_map, f)
with open('inverse_label_mapping.json', 'w') as f:
json.dump(inverse_label_map, f)
创建数据集和数据加载器
dataset = GameDataset(images, actions, transform=transform)
dataloader = DataLoader(dataset, batch_size=32, shuffle=True,num_workers=6)
使用GPU
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
加载ResNet模型(例如ResNet-50)
resnet_model = resnet50(weights=ResNet50_Weights.DEFAULT)
resnet_model.fc = nn.Linear(resnet_model.fc.in_features, len(unique_actions)) # 为特定任务调整分类头
resnet_model.to(device) # 将模型移动到GPU
使用交叉熵损失和 AdamW 优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.AdamW(resnet_model.parameters(), lr=0.0001, weight_decay=0.01)
将所有数据加载到显存中
all_images = []
all_actions = []
for images, actions in dataloader:
images = images.to(device)
actions = actions.to(device)
all_images.append(images)
all_actions.append(actions)
将所有数据拼接成一个大的张量
all_images = torch.cat(all_images, dim=0)
all_actions = torch.cat(all_actions, dim=0)
释放内存中的图像数据
del images, actions
torch.cuda.empty_cache() # 清理显存缓存
AMP梯度缩放器
scaler = GradScaler()
训练模型
num_epochs = 150
save_interval = 10 # 每10个epoch保存一次模型
for epoch in range(num_epochs):
resnet_model.train()
running_loss = 0.0
for i in range(0, len(all_images), 32): # 手动分批
batch_images = all_images[i:i+32]
batch_actions = all_actions[i:i+32]
optimizer.zero_grad()
# 前向传播 (开启AMP的autocast上下文)
with autocast():
outputs = resnet_model(batch_images)
loss = criterion(outputs, batch_actions)
# 反向传播及优化(使用AMP动态梯度缩放器)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update() # 更新梯度缩放倍率
running_loss += loss.item()
# 输出每个批次的损失
if (i // 32) % 10 == 0: # 每10个批次输出一次
print(f"Epoch [{epoch + 1}/{num_epochs}], Batch [{i // 32}/{len(all_images) // 32}], Loss: {loss.item()}")
# 输出每个epoch的平均损失
average_loss = running_loss / (len(all_images) // 32) # 计算平均 Loss
print(f"Epoch [{epoch + 1}/{num_epochs}], Average Loss: {average_loss}")
# 每10个epoch保存一次模型
if (epoch + 1) % save_interval == 0:
model_path = f'resnet_bc_model_epoch_{epoch + 1}_loss_{average_loss:.4f}.pth' # 动态文件名包含Loss
torch.save(resnet_model.state_dict(), model_path)
print(f"Model saved at epoch {epoch + 1} to {model_path}")
保存最终模型
final_model_path = f'resnet_bc_model_final_loss_{average_loss:.4f}.pth' # 最终模型文件名也包含 Loss
torch.save(resnet_model.state_dict(), final_model_path)
print(f"Final model saved to {final_model_path}")
这段代码将内存数据转移至显存非常缓慢,我的要求是 数据要全部一次性加载进显存,在这个前提下提速