pytorch 读取文件夹中图片,训练,预测,保存结果代码
时间: 2023-05-20 09:06:43 浏览: 234
以下是一个简单的 PyTorch 读取文件夹中图片、训练、预测和保存结果的代码示例:
```python
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms, datasets
# 定义数据集
class ImageDataset(Dataset):
def __init__(self, root_dir, transform=None):
self.data = datasets.ImageFolder(root_dir, transform=transform)
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data)
# 定义模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 16 * 5 * 5)
x = nn.functional.relu(self.fc1(x))
x = nn.functional.relu(self.fc2(x))
x = self.fc3(x)
return x
# 定义训练函数
def train(model, train_loader, criterion, optimizer, device):
model.train()
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
return running_loss / len(train_loader)
# 定义测试函数
def test(model, test_loader, criterion, device):
model.eval()
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
return correct / total
# 定义主函数
def main():
# 定义超参数
batch_size = 32
num_epochs = 10
learning_rate = 0.001
# 定义数据增强
transform = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
# 加载数据集
train_dataset = ImageDataset('train', transform=transform)
test_dataset = ImageDataset('test', transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)
# 定义设备
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# 定义模型、损失函数和优化器
model = Net().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9)
# 训练模型
for epoch in range(num_epochs):
train_loss = train(model, train_loader, criterion, optimizer, device)
test_acc = test(model, test_loader, criterion, device)
print('Epoch [{}/{}], Train Loss: {:.4f}, Test Acc: {:.4f}'.format(epoch+1, num_epochs, train_loss, test_acc))
# 保存模型
torch.save(model.state_dict(), 'model.pth')
# 预测新数据
model.eval()
with torch.no_grad():
inputs = torch.randn(1, 3, 224, 224).to(device)
outputs = model(inputs)
_, predicted = torch.max(outputs.data, 1)
print('Predicted Class:', predicted.item())
if __name__ == '__main__':
main()
```
这段代码可以读取名为 "train" 和 "test" 的文件夹中的图片,使用数据增强进行训练,训练一个简单的卷积神经网络模型,保存模型参数到 "model.pth" 文件中,并使用模型进行预测。
阅读全文