卷积神经网络dcnn代码
时间: 2024-04-01 12:30:18 浏览: 138
卷积神经网络 CNN 代码
5星 · 资源好评率100%
卷积神经(Convolutional Neural Network,CNN)是一种广泛应用于图像识别和计算机视觉任务的深度学习模型。下面是一个简单的卷积神经网络的代码示例:
```python
import torch
import torch.nn as nn
# 定义卷积神经网络模型
class CNN(nn.Module):
def __init__(self):
super(CNN, 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, 10)
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
# 创建卷积神经网络实例
model = CNN()
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
for epoch in range(10):
running_loss = 0.0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
print('Epoch %d, Loss: %.3f' % (epoch+1, running_loss / len(trainloader)))
# 测试模型
correct = 0
total = 0
with torch.no_grad():
for data in testloader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy: %.2f %%' % (100 * correct / total))
```
这段代码实现了一个简单的卷积神经网络模型,包括定义模型结构、损失函数、优化器,以及训练和测试过程。你可以根据自己的需求进行修改和扩展。
阅读全文