resnet50_vd_ssld.py 2.2 KB
Newer Older
J
jiangjiajun 已提交
1 2
# 环境变量配置,用于控制是否使用GPU
# 说明文档:https://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html#gpu
J
jiangjiajun 已提交
3
import os
J
jiangjiajun 已提交
4 5
os.environ['CUDA_VISIBLE_DEVICES'] = '0'

J
jiangjiajun 已提交
6 7 8 9 10 11 12 13
from paddlex.cls import transforms
import paddlex as pdx

# 下载和解压蔬菜分类数据集
veg_dataset = 'https://bj.bcebos.com/paddlex/datasets/vegetables_cls.tar.gz'
pdx.utils.download_and_decompress(veg_dataset, path='./')

# 定义训练和验证时的transforms
J
jiangjiajun 已提交
14
# API说明https://paddlex.readthedocs.io/zh_CN/develop/apis/transforms/cls_transforms.html
J
jiangjiajun 已提交
15
train_transforms = transforms.Compose([
J
jiangjiajun 已提交
16 17
    transforms.RandomCrop(crop_size=224), 
    transforms.RandomHorizontalFlip(),
J
jiangjiajun 已提交
18 19 20 21
    transforms.Normalize()
])
eval_transforms = transforms.Compose([
    transforms.ResizeByShort(short_size=256),
J
jiangjiajun 已提交
22 23
    transforms.CenterCrop(crop_size=224), 
    transforms.Normalize()
J
jiangjiajun 已提交
24 25 26
])

# 定义训练和验证所用的数据集
J
jiangjiajun 已提交
27
# API说明:https://paddlex.readthedocs.io/zh_CN/develop/apis/datasets.html#paddlex-datasets-imagenet
J
jiangjiajun 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
train_dataset = pdx.datasets.ImageNet(
    data_dir='vegetables_cls',
    file_list='vegetables_cls/train_list.txt',
    label_list='vegetables_cls/labels.txt',
    transforms=train_transforms,
    shuffle=True)
eval_dataset = pdx.datasets.ImageNet(
    data_dir='vegetables_cls',
    file_list='vegetables_cls/val_list.txt',
    label_list='vegetables_cls/labels.txt',
    transforms=eval_transforms)

# 初始化模型,并进行训练
# 可使用VisualDL查看训练指标
# VisualDL启动方式: visualdl --logdir output/mobilenetv2/vdl_log --port 8001
# 浏览器打开 https://0.0.0.0:8001即可
# 其中0.0.0.0为本机访问,如为远程服务, 改成相应机器IP
J
jiangjiajun 已提交
45
model = pdx.cls.ResNet50_vd_ssld(num_classes=len(train_dataset.labels))
J
jiangjiajun 已提交
46 47 48

# API说明:https://paddlex.readthedocs.io/zh_CN/develop/apis/models/classification.html#train
# 各参数介绍与调整说明:https://paddlex.readthedocs.io/zh_CN/develop/appendix/parameters.html
J
jiangjiajun 已提交
49 50 51 52 53 54 55
model.train(
    num_epochs=10,
    train_dataset=train_dataset,
    train_batch_size=32,
    eval_dataset=eval_dataset,
    lr_decay_epochs=[4, 6, 8],
    learning_rate=0.025,
J
jiangjiajun 已提交
56
    save_dir='output/resnet50_vd_ssld',
J
jiangjiajun 已提交
57
    use_vdl=True)