在Gluon中實(shí)現(xiàn)遷移學(xué)習(xí)可以通過(guò)以下步驟來(lái)完成:
from mxnet.gluon.model_zoo import vision as models
pretrained_model = models.resnet50_v2(pretrained=True)
from mxnet.gluon import nn
model = nn.HybridSequential()
model.add(pretrained_model.features)
model.add(nn.Dense(num_classes)) # 添加全連接層,num_classes為新數(shù)據(jù)集的類別數(shù)
for param in pretrained_model.collect_params().values():
param.grad_req = 'null'
from mxnet.gluon import loss
from mxnet import autograd
criterion = loss.SoftmaxCrossEntropyLoss()
optimizer = mx.optimizer.Adam(learning_rate=0.001)
for epoch in range(num_epochs):
for data, label in train_data:
with autograd.record():
output = model(data)
loss = criterion(output, label)
loss.backward()
optimizer.step(batch_size)
通過(guò)以上步驟,你可以在Gluon中實(shí)現(xiàn)遷移學(xué)習(xí),利用預(yù)訓(xùn)練模型的特征提取能力,加速在新數(shù)據(jù)集上的訓(xùn)練過(guò)程。