本示例将展示如何使用PaddleHub的SpinalNet预训练模型进行宝石识别或finetune并完成宝石的预测任务。
$pip install -U paddlehub==2.0.0
import paddlehub as hub
spinal_res50 = hub.Module(name="spinalnet_res50_gemstone")
spinal_vgg16 = hub.Module(name="spinalnet_vgg16_gemstone")
spinal_res101 = hub.Module(name="spinalnet_res101_gemstone")
result_res50 = spinal_res50.predict(['/PATH/TO/IMAGE'])
print(result_res50)
result_vgg16 = spinal_vgg16.predict(['/PATH/TO/IMAGE'])
print(result_vgg16)
sresult_res101 = spinal_res101.predict(['/PATH/TO/IMAGE'])
print(result_res101)
$ hub run spinalnet_res50_gemstone --input_path "/PATH/TO/IMAGE" --top_k 5
在完成安装PaddlePaddle与PaddleHub后,即可对Spinalnet模型进行针对宝石数据集的Fine-tune。
使用PaddleHub Fine-tune API进行Fine-tune可以分为5个步骤。
from paddlehub.finetune.trainer import Trainer
from gem_dataset import GemStones
from paddlehub.vision import transforms as T
import paddle
train_transforms = T.Compose([T.Resize((256, 256)), T.CenterCrop(224), T.Normalize(mean=[0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225])], to_rgb=True)
eval_transforms = T.Compose([T.Resize((256, 256)), T.CenterCrop(224), T.Normalize(mean=[0.485, 0.456, 0.406], std = [0.229, 0.224, 0.225])], to_rgb=True)
transforms
数据增强模块定义了丰富的数据预处理方式,用户可按照需求替换自己需要的数据预处理方式。
gem_train = GemStones(transforms=train_transforms, mode='train')
gem_validate = GemStones(transforms=eval_transforms, mode='eval')
数据集的准备代码可以参考 gem_dataset.py。
optimizer = paddle.optimizer.Momentum(learning_rate=0.001, momentum=0.9, parameters=spinal_res50.parameters())
trainer = Trainer(spinal_res50, optimizer, use_gpu=True, checkpoint_dir='fine_tuned_model')
trainer.train(gem_train, epochs=5, batch_size=128, eval_dataset=gem_validate, save_interval=1, log_interval=10)
spinal_res50 = hub.Module(name="spinalnet_res50_gemstone")
result_res50 = spinal_res50.predict(['/PATH/TO/IMAGE'])
print(result_res50)
paddlepaddle >= 2.0.0
paddlehub >= 2.0.0