用Pytorch写AlexNet代码
时间: 2023-09-03 15:26:16 浏览: 128
Pytorch实现AlexNet花分类完整数据集+代码
5星 · 资源好评率100%
### 回答1:
在 PyTorch 中实现 AlexNet 网络的步骤如下:
1. 定义 AlexNet 的网络结构: 首先, 你需要定义 AlexNet 的网络结构, 包括每一层的输入输出尺寸以及每一层使用的卷积核的大小和数量, 池化层的大小等. 例如, AlexNet 的第一层是一个卷积层, 其输入图像的大小为 224x224, 卷积核的大小为 11x11, 卷积核的数量为 96, 步长为 4.
2. 定义卷积层和池化层: 使用 PyTorch 的 nn.Conv2d 和 nn.MaxPool2d 模块定义 AlexNet 中的卷积层和池化层. 例如, 你可以使用如下代码定义 AlexNet 的第一层卷积层:
```
import torch.nn as nn
class AlexNet(nn.Module):
def __init__(self, num_classes=1000):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
...
)
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
```
3. 定义全连接层: 使用 PyTorch 的 nn.Linear 模块定义 AlexNet 中的全连接层. 例如, 你可以使用如下代码定义 AlexNet 的第一个全连接层:
```
import torch
### 回答2:
AlexNet是一个经典的卷积神经网络模型,由深度学习领域的大师Alex Krizhevsky等人提出。下面是使用PyTorch框架编写AlexNet的代码示例:
首先,我们需要导入相关的PyTorch库和模块:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
```
然后,定义AlexNet模型的网络结构:
```python
class AlexNet(nn.Module):
def __init__(self, num_classes=1000):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
```
接下来,我们可以进行模型的实例化,并定义损失函数和优化器:
```python
model = AlexNet(num_classes=1000)
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
```
然后,可以利用训练数据对模型进行训练:
```python
for epoch in range(num_epochs):
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()
if i % 2000 == 1999:
print('[%d, %5d] loss: %.3f' %
(epoch + 1, i + 1, running_loss / 2000))
running_loss = 0.0
print('Finished Training')
```
最后,可以使用测试数据对模型进行验证:
```python
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 of the network on the 10000 test images: %d %%' % (
100 * correct / total))
```
通过以上代码,我们就可以使用PyTorch框架来实现AlexNet模型,并对图像分类任务进行训练和测试了。
### 回答3:
AlexNet是2012年由Alex Krizhevsky等人提出的一个经典的深度学习模型,被广泛应用于计算机视觉任务中,使用PyTorch实现AlexNet的代码如下:
```python
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as data
import torchvision
import torchvision.transforms as transforms
# 创建AlexNet模型
class AlexNet(nn.Module):
def __init__(self, num_classes=1000):
super(AlexNet, self).__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=11, stride=4, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(64, 192, kernel_size=5, padding=2),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(192, 384, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(384, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=3, stride=2),
)
self.avgpool = nn.AdaptiveAvgPool2d((6, 6))
self.classifier = nn.Sequential(
nn.Dropout(),
nn.Linear(256 * 6 * 6, 4096),
nn.ReLU(inplace=True),
nn.Dropout(),
nn.Linear(4096, 4096),
nn.ReLU(inplace=True),
nn.Linear(4096, num_classes),
)
def forward(self, x):
x = self.features(x)
x = self.avgpool(x)
x = torch.flatten(x, 1)
x = self.classifier(x)
return x
# 加载数据
transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
train_set = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
train_loader = data.DataLoader(train_set, batch_size=128, shuffle=True, num_workers=2)
test_set = torchvision.datasets.CIFAR10(root='./data', train=False, download=True, transform=transform)
test_loader = data.DataLoader(test_set, batch_size=100, shuffle=False, num_workers=2)
# 实例化模型
model = AlexNet(num_classes=10) # 这里假设分类任务是10分类,因为使用的是CIFAR10数据集
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)
# 训练模型
for epoch in range(10):
running_loss = 0.0
for i, (inputs, labels) in enumerate(train_loader, 0):
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
if i % 200 == 199: # 每200个batch输出一次损失值
print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1, running_loss / 200))
running_loss = 0.0
print('Finished Training')
# 在测试集上评估模型
correct = 0
total = 0
with torch.no_grad():
for data in test_loader:
images, labels = data
outputs = model(images)
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print('Accuracy on test images: %.2f %%' % (100 * correct / total))
```
通过以上代码,我们使用PyTorch成功实现了AlexNet模型,并在CIFAR-10数据集上进行了训练和测试,得到了相应的准确率。使用PyTorch编写深度学习模型非常方便,可以通过定义模型结构、加载数据、定义损失函数和优化器等步骤,便捷地完成模型的训练和评估。
阅读全文