?????作者簡(jiǎn)介:一位即將上大四,正專攻機(jī)器學(xué)習(xí)的保研er
??上期文章:機(jī)器學(xué)習(xí)&&深度學(xué)習(xí)——池化層
??訂閱專欄:機(jī)器學(xué)習(xí)&&深度學(xué)習(xí)
希望文章對(duì)你們有所幫助
引言
之前的內(nèi)容中曾經(jīng)將softmax回歸模型和多層感知機(jī)應(yīng)用于Fashion-MNIST數(shù)據(jù)集中的服裝圖片。為了能應(yīng)用他們,我們首先就把圖像展平成了一維向量,然后用全連接層對(duì)其進(jìn)行處理。
而現(xiàn)在已經(jīng)學(xué)習(xí)過了卷積層的處理方法,我們就可以在圖像中保留空間結(jié)構(gòu)。同時(shí),用卷積層代替全連接層的另一個(gè)好處是:模型更簡(jiǎn)單,所需參數(shù)更少。
LeNet是最早發(fā)布的卷積神經(jīng)網(wǎng)絡(luò)之一,之前出來的目的是為了識(shí)別圖像中的手寫數(shù)字。
LeNet
總體看,由兩個(gè)部分組成:
1、卷積編碼器:由兩個(gè)卷積層組成
2、全連接層密集快:由三個(gè)全連接層組成
上圖中就是LeNet的數(shù)據(jù)流圖示,其中匯聚層也就是池化層。
最終輸出的大小是10,也就是10個(gè)可能結(jié)果(0-9)。
每個(gè)卷積塊的基本單元是一個(gè)卷積層、一個(gè)sigmoid激活函數(shù)和平均池化層(當(dāng)年沒有ReLU和最大池化層)。每個(gè)卷積層使用5×5卷積核和一個(gè)sigmoid激活函數(shù)。
這些層的作用就是將輸入映射到多個(gè)二維特征輸出,通常同時(shí)增加通道的數(shù)量。(從上圖容易看出:第一卷積層有6個(gè)輸出通道,而第二個(gè)卷積層有16個(gè)輸出通道;每個(gè)2×2池操作(步幅也為2)通過空間下采樣將維數(shù)減少4倍)。卷積的輸出形狀那是由批量大小、通道數(shù)、高度、寬度決定。
為了將卷積塊的輸出傳遞給稠密塊,我們必須在小批量中展平每個(gè)樣本(也就是把四維的輸入轉(zhuǎn)換為全連接層期望的二維輸入,第一維索引小批量中的樣本,第二維給出給個(gè)樣本的平面向量表示)。
LeNet的稠密塊有三個(gè)全連接層,分別有120、84和10個(gè)輸出。因?yàn)槲覀冊(cè)趫?zhí)行分類任務(wù),所以輸出層的10維對(duì)應(yīng)于最后輸出結(jié)果的數(shù)量(代表0-9是個(gè)結(jié)果)。
深度學(xué)習(xí)框架實(shí)現(xiàn)此類模型非常簡(jiǎn)單,用一個(gè)Sequential塊把需要的層連接在一個(gè)就可以了,我們對(duì)原始模型做一個(gè)小改動(dòng),去掉最后一層的高斯激活:
import torch
from torch import nn
from d2l import torch as d2l
net = nn.Sequential(
# 輸入圖像和輸出圖像都是28×28,因此我們要先進(jìn)行填充2格
nn.Conv2d(1, 6, kernel_size=5, padding=2), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Conv2d(6, 16, kernel_size=5), nn.Sigmoid(),
nn.AvgPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(16 * 5 * 5, 120), nn.Sigmoid(),
nn.Linear(120, 84), nn.Sigmoid(),
nn.Linear(84, 10)
)
上面的模型圖示就為:
我們可以先檢查模型,在每一層打印輸出的形狀:
X = torch.rand(size=(1, 1, 28, 28), dtype=torch.float32)
for layer in net:
X = layer(X)
print(layer.__class__.__name__, 'output shape:\t', X.shape)
輸出結(jié)果:
Conv2d output shape: torch.Size([1, 6, 28, 28])
Sigmoid output shape: torch.Size([1, 6, 28, 28])
AvgPool2d output shape: torch.Size([1, 6, 14, 14])
Conv2d output shape: torch.Size([1, 16, 10, 10])
Sigmoid output shape: torch.Size([1, 16, 10, 10])
AvgPool2d output shape: torch.Size([1, 16, 5, 5])
Flatten output shape: torch.Size([1, 400])
Linear output shape: torch.Size([1, 120])
Sigmoid output shape: torch.Size([1, 120])
Linear output shape: torch.Size([1, 84])
Sigmoid output shape: torch.Size([1, 84])
Linear output shape: torch.Size([1, 10])
模型訓(xùn)練
既然已經(jīng)實(shí)現(xiàn)了LeNet,現(xiàn)在可以查看它在Fashion-MNIST數(shù)據(jù)集上的表現(xiàn):
batch_size = 256
train_iter, test_iter = d2l.load_data_fashion_mnist(batch_size)
計(jì)算成本較高,因此使用GPU來加快訓(xùn)練。為了進(jìn)行評(píng)估,對(duì)之前的evaluate_accuracy進(jìn)行修改,由于完整的數(shù)據(jù)集位于內(nèi)存中,因此在模型使用GPU計(jì)算數(shù)據(jù)集之前,我們需要將其復(fù)制到顯存中。
def evaluate_accuracy_gpu(net, data_iter, device=None):
"""使用GPU計(jì)算模型在數(shù)據(jù)集上的精度"""
if isinstance(net, nn.Module):
net.eval() # 設(shè)置為評(píng)估模式
if not device:
device = next(iter(net.parameters())).device
# 正確預(yù)測(cè)的數(shù)量,總預(yù)測(cè)的數(shù)量
metric = d2l.Accumulator(2)
with torch.no_grad():
for X, y in data_iter:
if isinstance(X, list):
# BERT微調(diào)所需(后面內(nèi)容)
else:
X = X.to(device)
y = y.to(device)
metric.add(d2l.accuracy(net(X), y), y.numel())
return metric[0] / metric[1]
要使用GPU,我們要在正向和反向傳播之前,將每一小批量數(shù)據(jù)移動(dòng)到我們GPU上。
如下所示的train_ch6類似于之前定義的train_ch3。以下訓(xùn)練函數(shù)假定從高級(jí)API創(chuàng)建的模型作為輸入,并進(jìn)行相應(yīng)的優(yōu)化。
使用Xavier來隨機(jī)初始化模型參數(shù)。有關(guān)于Xavier的推導(dǎo)和原理可以看下面的文章:
機(jī)器學(xué)習(xí)&&深度學(xué)習(xí)——數(shù)值穩(wěn)定性和模型化參數(shù)(詳細(xì)數(shù)學(xué)推導(dǎo))
與全連接層一樣,使用交叉熵?fù)p失函數(shù)和小批量隨機(jī)梯度下降,代碼如下:
def train_ch6(net, train_iter, test_iter, num_epochs, lr, device): #@save
"""用GPU訓(xùn)練模型"""
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()
animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
legend=['train loss', 'train acc', 'test acc'])
timer, num_batches = d2l.Timer(), len(train_iter)
for epoch in range(num_epochs):
# 訓(xùn)練損失之和,訓(xùn)練準(zhǔn)確率之和,樣本數(shù)
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)
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]
if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
animator.add(epoch + (i+1) / num_batches, (train_l, train_acc, None))
test_acc = evaluate_accuracy_gpu(net, test_iter)
animator.add(epoch + 1, (None, None, test_acc))
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)}')
此時(shí)我們可以開始訓(xùn)練和評(píng)估LeNet模型:
lr, num_epochs = 0.9, 10
train_ch6(net, train_iter, test_iter, num_epochs, lr, d2l.try_gpu())
d2l.plt.show()
運(yùn)行輸出(這邊我沒有用遠(yuǎn)程的GPU,在自己本地跑了,本地只有CPU):
training on cpu
loss 0.477, train acc 0.820, test acc 0.795
8004.2 examples/sec on cpu
運(yùn)行圖片:文章來源:http://www.zghlxwxcb.cn/news/detail-625170.html
小結(jié)
1、卷積神經(jīng)網(wǎng)絡(luò)(CNN)是一類使用卷積層的網(wǎng)絡(luò)
2、在卷積神經(jīng)網(wǎng)絡(luò)中,我們組合使用卷積層、非線性激活函數(shù)和池化層
3、為了構(gòu)造高性能的卷積神經(jīng)網(wǎng)絡(luò),我們通常對(duì)卷積層進(jìn)行排列,逐漸降低其表示的空間分辨率,同時(shí)增加通道數(shù)
4、傳統(tǒng)卷積神經(jīng)網(wǎng)絡(luò)中,卷積塊編碼得到的表征在輸出之前需要由一個(gè)或多個(gè)全連接層進(jìn)行處理文章來源地址http://www.zghlxwxcb.cn/news/detail-625170.html
到了這里,關(guān)于機(jī)器學(xué)習(xí)&&深度學(xué)習(xí)——卷積神經(jīng)網(wǎng)絡(luò)(LeNet)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!