代码拉取完成,页面将自动刷新
import os
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import datasets, transforms, models
from sklearn.metrics import accuracy_score
# 数据预处理
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]),
])
# 自定义数据集类
class CustomDataset(torch.utils.data.Dataset):
def __init__(self, root, transform=None):
self.root = root
self.transform = transform
self.image_paths = []
self.labels = []
for label in ['0', '1']:
label_path = os.path.join(root, label)
for filename in os.listdir(label_path):
self.image_paths.append(os.path.join(label_path, filename))
self.labels.append(int(label))
def __len__(self):
return len(self.image_paths)
def __getitem__(self, index):
image_path = self.image_paths[index]
label = self.labels[index]
image = Image.open(image_path).convert('RGB')
if self.transform is not None:
image = self.transform(image)
return image, label
# 加载训练数据集
train_dataset = CustomDataset(root='path/to/train', transform=transform)
train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True, num_workers=4)
# 加载测试数据集
test_dataset = CustomDataset(root='path/to/test', transform=transform)
test_loader = DataLoader(test_dataset, batch_size=32, shuffle=False, num_workers=4)
# 加载预训练的AlexNet模型
model = models.alexnet(pretrained=True)
# 修改最后一层,适应二分类任务
num_classes = 2
model.classifier[6] = nn.Linear(model.classifier[6].in_features, num_classes)
# 将模型移动到GPU上(如果可用)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
num_epochs = 10
for epoch in range(num_epochs):
model.train()
for inputs, labels in train_loader:
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
# 在测试集上评估模型
model.eval()
all_preds = []
all_labels = []
with torch.no_grad():
for inputs, labels in test_loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
all_preds.extend(predicted.cpu().numpy())
all_labels.extend(labels.cpu().numpy())
accuracy = accuracy_score(all_labels, all_preds)
print(f'Epoch {epoch + 1}/{num_epochs}, Accuracy: {100 * accuracy:.2f}%')
# 保存训练好的模型
torch.save(model.state_dict(), 'alexnet_binary_classification_model.pth')
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。