使用pytorch实现图片500分类完整代码
时间: 2023-08-02 15:02:20 浏览: 108
利用pytorch实现图像分类的一个完整的代码
使用PyTorch实现图片500分类的完整代码如下:
```python
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
class Net(nn.Module):
def __init__(self, num_classes):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU()
self.maxpool = nn.MaxPool2d(kernel_size=2, stride=2)
self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)
self.fc = nn.Linear(32 * 8 * 8, num_classes)
def forward(self, x):
x = self.conv1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.conv2(x)
x = self.relu(x)
x = self.maxpool(x)
x = x.view(x.size(0), -1)
x = self.fc(x)
return x
# 数据预处理
transform = transforms.Compose([
transforms.RandomHorizontalFlip(),
transforms.RandomVerticalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
# 加载数据集
train_dataset = datasets.ImageFolder('train_directory', transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
# 初始化模型
model = Net(num_classes=500)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# 训练模型
for epoch in range(10):
for batch_idx, (data, targets) in enumerate(train_loader):
optimizer.zero_grad()
outputs = model(data)
loss = criterion(outputs, targets)
loss.backward()
optimizer.step()
if batch_idx % 100 == 0:
print(f'Epoch {epoch+1}/{10}, Step {batch_idx}/{len(train_loader)}, Loss: {loss.item()}')
# 保存模型
torch.save(model.state_dict(), 'model.pt')
```
上述代码实现了一个简单的卷积神经网络(CNN)模型,使用ImageFolder从`train_directory`加载训练数据集,并使用Adam优化器进行训练。模型在训练过程中,每100个batch打印一次loss值,并保存了训练得到的模型参数至`model.pt`文件中。请注意,代码中的`train_directory`需要替换为实际的训练数据集目录。
阅读全文