1.AlexNet简介
AlexNet是一种深度卷积神经网络,由Alex Krizhevsky等人在2012年提出。它在ImageNet大规模图像识别挑战赛(ImageNet Large-Scale Visual Recognition Challenge,ILSVRC)中取得了突破性的成果,极大地推动了深度学习的发展。
AlexNet是第一个在深度学习领域引起广泛关注的卷积神经网络。相比于传统的浅层网络,AlexNet通过增加网络深度和参数量,使用更多的隐藏层,使得网络能够学习到更复杂的特征表示。
AlexNet的网络结构相对复杂,主要有以下几个关键特点:
-
深度结构:AlexNet总共有8个卷积层和3个全连接层,其中前5个卷积层交替使用卷积、激活函数和最大池化操作,用于提取图像的低级和高级特征。
-
非线性激活函数:AlexNet使用修正线性单元(Rectified Linear Unit,ReLU)作为卷积层的激活函数,相比于传统的sigmoid函数,ReLU能够更有效地缓解梯度消失问题,并提高网络的收敛速度。
-
局部响应归一化(Local Response Normalization,LRN):在卷积层之后,AlexNet使用LRN操作对激活值进行归一化处理,以提高网络的泛化能力。
-
Dropout正则化:AlexNet引入了Dropout正则化技术,通过随机将一部分神经元输出置为0,以降低网络的过拟合风险。
-
多GPU并行训练:为了加快训练速度,AlexNet利用多个GPU进行并行计算,将网络分成两部分,并在两个GPU上交替进行计算。
AlexNet的提出标志着深度学习在计算机视觉领域的崛起,并为后续更深层次的卷积神经网络(如VGG、ResNet、Inception等)的发展奠定了基础。
2.AlexNet实现
import cv2
import torch
from d2l.torch import evaluate_accuracy_gpu
from torch import nn
from d2l import torch as d2l
if __name__ == "__main__":
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
nn.init.xavier_uniform_(m.weight)
net.apply(init_weights)
print('training on', device)
net.to(device)
optimizer = torch.optim.SGD(net.parameters(), lr=lr)
loss = nn.CrossEntropyLoss()
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
# Sum of training loss, sum of training accuracy, no. of examples
metric = d2l.Accumulator(3)
net.train()
for i, (X, y) in enumerate(train_iter):
timer.start()
optimizer.zero_grad()
X, y = X.to(device), y.to(device)
y_hat = net(X)
l = loss(y_hat, y)
l.backward()
optimizer.step()
with torch.no_grad():
metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
timer.stop()
train_l = metric[0] / metric[2]
train_acc = metric[1] / metric[2]
test_acc = evaluate_accuracy_gpu(net, test_iter)
print(f'epoch {epoch},loss :{train_l:.3f}, train acc :{train_acc:.3f}, '
f'test acc :{test_acc:.3f}, time :{timer.sum() / 60}m{int(timer.sum() % 60)}s')
print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
f'test acc {test_acc:.3f}')
print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
f'on {str(device)}')
net = nn.Sequential(nn.Conv2d(1, 96, kernel_size=11, stride=4, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(96, 256, kernel_size=5, padding=2), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2),
nn.Conv2d(256, 384, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(384, 384, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(384, 256, kernel_size=3, padding=1), nn.ReLU(),
nn.MaxPool2d(kernel_size=3, stride=2), nn.Flatten(),
nn.Linear(6400, 4096), nn.ReLU(), nn.Dropout(p=0.5),
nn.Linear(4096, 4096), nn.ReLU(), nn.Dropout(p=0.5),
nn.Linear(4096, 10))
batch_size = 64
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size=batch_size, resize=224)
lr, num_epochs = 0.01, 10
train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
# 模型保存
torch.save(net.state_dict(), f'AlexNet/AlexNet{num_epochs}.pth')
# 读取模型
# net.load_state_dict(torch.load('AlexNet/AlexNet.pth'))
def preprocess(image_path):
image = cv2.cvtColor(cv2.imread(image_path), cv2.COLOR_BGR2GRAY)
image = torch.tensor(cv2.resize(image, (28, 28)), dtype=torch.float32).unsqueeze(0).unsqueeze(0)
return image
# 预测图片
def predict(image_path):
image = preprocess(image_path)
# TODO 若是训练完直接预测,由于网络是在GPU上,因此需要将输入张量转到GPU上
image = image.cuda()
with torch.no_grad():
outputs = net(image)
_, predicted = torch.max(outputs)
# 这里的class_label需要自己修改
class_label = d2l.get_fashion_mnist_labels(predicted)
return class_label
image_path = 'AlexNet/img.png' # 待预测的图像路径
predicted_class = predict(image_path)
print('预测类别:', predicted_class)