通过pytorch使用cnn进行垃圾分类,需完整代码
时间: 2023-07-05 10:22:19 浏览: 105
好的,以下是使用 PyTorch 进行垃圾分类的完整代码:
```
import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
# 定义数据预处理
transform = transforms.Compose(
[transforms.Resize((32, 32)),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
# 加载训练集和测试集
trainset = torchvision.datasets.ImageFolder(root='./garbage_classify/train', transform=transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=32,
shuffle=True, num_workers=2)
testset = torchvision.datasets.ImageFolder(root='./garbage_classify/val', transform=transform)
testloader = torch.utils.data.DataLoader(testset, batch_size=32,
shuffle=False, num_workers=2)
# 定义网络模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 16, 3, padding=1)
self.bn1 = nn.BatchNorm2d(16)
self.relu1 = nn.ReLU()
self.pool1 = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.bn2 = nn.BatchNorm2d(32)
self.relu2 = nn.ReLU()
self.pool2 = nn.MaxPool2d(2, 2)
self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
self.bn3 = nn.BatchNorm2d(64)
self.relu3 = nn.ReLU()
self.pool3 = nn.MaxPool2d(2, 2)
self.fc1 = nn.Linear(64 * 4 * 4, 256)
self.dropout = nn.Dropout(p=0.5)
self.fc2 = nn.Linear(256, 6)
def forward(self, x):
x = self.conv1(x)
x = self.bn1(x)
x = self.relu1(x)
x = self.pool1(x)
x = self.conv2(x)
x = self.bn2(x)
x = self.relu2(x)
x = self.pool2(x)
x = self.conv3(x)
x = self.bn3(x)
x = self.relu3(x)
x = self.pool3(x)
x = x.view(-1, 64 * 4 * 4)
x = self.fc1(x)
x = self.dropout(x)
x = self.fc2(x)
return x
# 定义训练函数
def train(net, trainloader, optimizer, criterion, epoch):
net.train()
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = net(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 100 == 99: # 每 100 个 batch 输出一次损失
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 100))
running_loss = 0.0
# 定义测试函数
def test(net, testloader):
net.eval()
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
images, labels = images.to(device), labels.to(device)
outputs = net(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy of the network on the test images: %d %%' % (
100 * correct / total))
# 初始化网络
net = Net()
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
net.to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)
# 训练模型
for epoch in range(10):
train(net, trainloader, optimizer, criterion, epoch)
test(net, testloader)
print('Finished Training')
```
在这个代码中,我们首先定义了数据预处理方式,然后使用 `ImageFolder` 加载了训练集和测试集。接着定义了一个卷积神经网络模型 `Net`,其中包含了三个卷积层和两个全连接层。然后定义了训练函数 `train` 和测试函数 `test`,分别用于训练和测试模型。最后,我们初始化了网络,定义了损失函数和优化器,并进行了训练。
阅读全文