1 Star 0 Fork 0

ZhangHaolin/photo_classify

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
Alexnet.py 3.01 KB
一键复制 编辑 原始数据 按行查看 历史
ZhangHaolin 提交于 2023-11-11 21:11 . 1111第一次提交
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')
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/zhang-haolin1/photo_classify.git
git@gitee.com:zhang-haolin1/photo_classify.git
zhang-haolin1
photo_classify
photo_classify
main

搜索帮助