用PaddlePaddle实现图像分类-AlexNet

项目简介

本项目使用paddle实现了经典的图像分类网络:AlexNet,并在公开的蔬菜数据集上进行了模型训练以及验证,建议使用GPU运行。动态图版本请查看:用PaddlePaddle实现图像分类-AlexNet(动态图版)

下载安装命令

## CPU版本安装命令
pip install -f https://paddlepaddle.org.cn/pip/oschina/cpu paddlepaddle

## GPU版本安装命令
pip install -f https://paddlepaddle.org.cn/pip/oschina/gpu paddlepaddle-gpu

数据集介绍

解压蔬菜数据集,里面包括三个目录,分别是三个类别对应的数据,具体的数据预处理过程见后续介绍

网络结构介绍

AlexNet网络具体结构如下图所示:
用PaddlePaddle实现图像分类-AlexNet
原论文中是采取了两块GPU进行交互,所以在图中有两条支路。AlexNet架构有6000万参数和650000个神经元,包含5层卷积网络,其中一些含有max pooling,还有3层全连接层,最后一层的节点数1000个,采用softmax分类
参考链接:AlexNet学习
论文原文:ImageNet Classification with Deep ConvolutionalNeural Networks

 

解压蔬菜数据集,里面包括三个目录,分别是三个类别

In[
 ]

# 解压蔬菜数据集
!cd data/data504 && unzip -q vegetables.zip

 

解压预训练参数,去掉了最后分类的全连接层

In[
 ]

# 解压预训练模型参数
!cd data/data6462 && unzip -q AlexNet_pretrained.zip

 

预处理数据,将其转化为标准格式。同时将数据拆分成两份,以便训练和计算预估准确率

  • label_list.txt 每一行一个类别,类别编号/t类别名字
  • train.txt 每一行一个样本,图片路径/t类别编号
  • trainImageSet/xxx.jpg 训练图片
  • eval.txt 格式通 train.txt
  • evalImageSet/xxx.jpg 验证图片

In[
 ]

import codecs
import os
import random
import shutil
from PIL import Image

train_ratio = 4.0 / 5

all_file_dir = 'data/data504/vegetables'
class_list = [c for c in os.listdir(all_file_dir) if os.path.isdir(os.path.join(all_file_dir, c)) and not c.endswith('Set') and not c.startswith('.')]
class_list.sort()
print(class_list)
train_image_dir = os.path.join(all_file_dir, "trainImageSet")
if not os.path.exists(train_image_dir):
    os.makedirs(train_image_dir)
    
eval_image_dir = os.path.join(all_file_dir, "evalImageSet")
if not os.path.exists(eval_image_dir):
    os.makedirs(eval_image_dir)

train_file = codecs.open(os.path.join(all_file_dir, "train.txt"), 'w')
eval_file = codecs.open(os.path.join(all_file_dir, "eval.txt"), 'w')

with codecs.open(os.path.join(all_file_dir, "label_list.txt"), "w") as label_list:
    label_id = 0
    for class_dir in class_list:
        label_list.write("{0}/t{1}/n".format(label_id, class_dir))
        image_path_pre = os.path.join(all_file_dir, class_dir)
        for file in os.listdir(image_path_pre):
            try:
                img = Image.open(os.path.join(image_path_pre, file))
                if random.uniform(0, 1) <= train_ratio:
                    shutil.copyfile(os.path.join(image_path_pre, file), os.path.join(train_image_dir, file))
                    train_file.write("{0}/t{1}/n".format(os.path.join(train_image_dir, file), label_id))
                else:
                    shutil.copyfile(os.path.join(image_path_pre, file), os.path.join(eval_image_dir, file))
                    eval_file.write("{0}/t{1}/n".format(os.path.join(eval_image_dir, file), label_id))
            except Exception as e:
                pass
                # 存在一些文件打不开,此处需要稍作清洗
        label_id += 1
            
train_file.close()
eval_file.close()
['cuke', 'lettuce', 'lotus_root']

 

训练部分,包括各种数据增强

In[1]

# -*- coding: UTF-8 -*-
"""
训练常用视觉基础网络,用于分类任务
需要将训练图片,类别文件 label_list.txt 放置在同一个文件夹下
程序会先读取 train.txt 文件获取类别数和图片数量
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import numpy as np
import time
import math
import paddle
import paddle.fluid as fluid
import codecs
import logging

from paddle.fluid.initializer import MSRA
from paddle.fluid.initializer import Uniform
from paddle.fluid.param_attr import ParamAttr
from PIL import Image
from PIL import ImageEnhance

train_parameters = {
    "input_size": [3, 224, 224],
    "class_dim": -1,  # 分类数,会在初始化自定义 reader 的时候获得
    "image_count": -1,  # 训练图片数量,会在初始化自定义 reader 的时候获得
    "label_dict": {},
    "data_dir": "data/data504/vegetables",  # 训练数据存储地址
    "train_file_list": "train.txt",
    "label_file": "label_list.txt",
    "save_freeze_dir": "./freeze-model",
    "save_persistable_dir": "./persistable-params",
    "continue_train": False,        # 是否接着上一次保存的参数接着训练,优先级高于预训练模型
    "pretrained": True,            # 是否使用预训练的模型
    "pretrained_dir": "data/data6462/AlexNet_pretrained", 
    "mode": "train",
    "num_epochs": 20,
    "train_batch_size": 20,
    "mean_rgb": [127.5, 127.5, 127.5],  # 常用图片的三通道均值,通常来说需要先对训练数据做统计,此处仅取中间值
    "use_gpu": True,
    "image_enhance_strategy": {  # 图像增强相关策略
        "need_distort": True,  # 是否启用图像颜色增强
        "need_rotate": True,   # 是否需要增加随机角度
        "need_crop": True,      # 是否要增加裁剪
        "need_flip": True,      # 是否要增加水平随机翻转
        "hue_prob": 0.5,
        "hue_delta": 18,
        "contrast_prob": 0.5,
        "contrast_delta": 0.5,
        "saturation_prob": 0.5,
        "saturation_delta": 0.5,
        "brightness_prob": 0.5,
        "brightness_delta": 0.125
    },
    "early_stop": {
        "sample_frequency": 50,
        "successive_limit": 3,
        "good_acc1": 0.92
    },
    "rsm_strategy": {
        "learning_rate": 0.001,
        "lr_epochs": [20, 40, 60, 80, 100],
        "lr_decay": [1, 0.5, 0.25, 0.1, 0.01, 0.002]
    },
    "momentum_strategy": {
        "learning_rate": 0.001,
        "lr_epochs": [20, 40, 60, 80, 100],
        "lr_decay": [1, 0.5, 0.25, 0.1, 0.01, 0.002]
    },
    "sgd_strategy": {
        "learning_rate": 0.001,
        "lr_epochs": [20, 40, 60, 80, 100],
        "lr_decay": [1, 0.5, 0.25, 0.1, 0.01, 0.002]
    },
    "adam_strategy": {
        "learning_rate": 0.001
    }
}


class AlexNet():
    def __init__(self):
        pass

    def name(self):
        """
        返回网络名字
        :return:
        """
        return 'AlexNet'

    def net(self, input, class_dim=1000):
        stdv = 1.0 / math.sqrt(input.shape[1] * 11 * 11)
        layer_name = [
            "conv1", "conv2", "conv3", "conv4", "conv5", "fc6", "fc7", "fc8"
        ]
        conv1 = fluid.layers.conv2d(
            input=input,
            num_filters=64,
            filter_size=11,
            stride=4,
            padding=2,
            groups=1,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[0] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[0] + "_weights"))
        pool1 = fluid.layers.pool2d(
            input=conv1,
            pool_size=3,
            pool_stride=2,
            pool_padding=0,
            pool_type='max')

        stdv = 1.0 / math.sqrt(pool1.shape[1] * 5 * 5)
        conv2 = fluid.layers.conv2d(
            input=pool1,
            num_filters=192,
            filter_size=5,
            stride=1,
            padding=2,
            groups=1,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[1] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[1] + "_weights"))
        pool2 = fluid.layers.pool2d(
            input=conv2,
            pool_size=3,
            pool_stride=2,
            pool_padding=0,
            pool_type='max')

        stdv = 1.0 / math.sqrt(pool2.shape[1] * 3 * 3)
        conv3 = fluid.layers.conv2d(
            input=pool2,
            num_filters=384,
            filter_size=3,
            stride=1,
            padding=1,
            groups=1,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[2] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[2] + "_weights"))

        stdv = 1.0 / math.sqrt(conv3.shape[1] * 3 * 3)
        conv4 = fluid.layers.conv2d(
            input=conv3,
            num_filters=256,
            filter_size=3,
            stride=1,
            padding=1,
            groups=1,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[3] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[3] + "_weights"))

        stdv = 1.0 / math.sqrt(conv4.shape[1] * 3 * 3)
        conv5 = fluid.layers.conv2d(
            input=conv4,
            num_filters=256,
            filter_size=3,
            stride=1,
            padding=1,
            groups=1,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[4] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[4] + "_weights"))
        pool5 = fluid.layers.pool2d(
            input=conv5,
            pool_size=3,
            pool_stride=2,
            pool_padding=0,
            pool_type='max')

        drop6 = fluid.layers.dropout(x=pool5, dropout_prob=0.5)
        stdv = 1.0 / math.sqrt(drop6.shape[1] * drop6.shape[2] *
                               drop6.shape[3] * 1.0)

        fc6 = fluid.layers.fc(
            input=drop6,
            size=4096,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[5] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[5] + "_weights"))

        drop7 = fluid.layers.dropout(x=fc6, dropout_prob=0.5)
        stdv = 1.0 / math.sqrt(drop7.shape[1] * 1.0)

        fc7 = fluid.layers.fc(
            input=drop7,
            size=4096,
            act='relu',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[6] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[6] + "_weights"))

        stdv = 1.0 / math.sqrt(fc7.shape[1] * 1.0)
        out = fluid.layers.fc(
            input=fc7,
            size=class_dim,
            act='softmax',
            bias_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[7] + "_offset"),
            param_attr=fluid.param_attr.ParamAttr(
                initializer=fluid.initializer.Uniform(-stdv, stdv),
                name=layer_name[7] + "_weights"))
        return out


def init_log_config():
    """
    初始化日志相关配置
    :return:
    """
    global logger
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)
    log_path = os.path.join(os.getcwd(), 'logs')
    if not os.path.exists(log_path):
        os.makedirs(log_path)
    log_name = os.path.join(log_path, 'train.log')
    sh = logging.StreamHandler()
    fh = logging.FileHandler(log_name, mode='w')
    fh.setLevel(logging.DEBUG)
    formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
    fh.setFormatter(formatter)
    sh.setFormatter(formatter)
    logger.addHandler(sh)
    logger.addHandler(fh)


def init_train_parameters():
    """
    初始化训练参数,主要是初始化图片数量,类别数
    :return:
    """
    train_file_list = os.path.join(train_parameters['data_dir'], train_parameters['train_file_list'])
    label_list = os.path.join(train_parameters['data_dir'], train_parameters['label_file'])
    index = 0
    with codecs.open(label_list, encoding='utf-8') as flist:
        lines = [line.strip() for line in flist]
        for line in lines:
            parts = line.strip().split()
            train_parameters['label_dict'][parts[1]] = int(parts[0])
            index += 1
        train_parameters['class_dim'] = index
    with codecs.open(train_file_list, encoding='utf-8') as flist:
        lines = [line.strip() for line in flist]
        train_parameters['image_count'] = len(lines)


def resize_img(img, target_size):
    """
    强制缩放图片
    :param img:
    :param target_size:
    :return:
    """
    target_size = input_size
    img = img.resize((target_size[1], target_size[2]), Image.BILINEAR)
    return img


def random_crop(img, scale=[0.08, 1.0], ratio=[3. / 4., 4. / 3.]):
    aspect_ratio = math.sqrt(np.random.uniform(*ratio))
    w = 1. * aspect_ratio
    h = 1. / aspect_ratio

    bound = min((float(img.size[0]) / img.size[1]) / (w**2),
                (float(img.size[1]) / img.size[0]) / (h**2))
    scale_max = min(scale[1], bound)
    scale_min = min(scale[0], bound)

    target_area = img.size[0] * img.size[1] * np.random.uniform(scale_min,
                                                                scale_max)
    target_size = math.sqrt(target_area)
    w = int(target_size * w)
    h = int(target_size * h)

    i = np.random.randint(0, img.size[0] - w + 1)
    j = np.random.randint(0, img.size[1] - h + 1)

    img = img.crop((i, j, i + w, j + h))
    img = img.resize((train_parameters['input_size'][1], train_parameters['input_size'][2]), Image.BILINEAR)
    return img


def rotate_image(img):
    """
    图像增强,增加随机旋转角度
    """
    angle = np.random.randint(-14, 15)
    img = img.rotate(angle)
    return img


def random_brightness(img):
    """
    图像增强,亮度调整
    :param img:
    :return:
    """
    prob = np.random.uniform(0, 1)
    if prob < train_parameters['image_enhance_strategy']['brightness_prob']:
        brightness_delta = train_parameters['image_enhance_strategy']['brightness_delta']
        delta = np.random.uniform(-brightness_delta, brightness_delta) + 1
        img = ImageEnhance.Brightness(img).enhance(delta)
    return img


def random_contrast(img):
    """
    图像增强,对比度调整
    :param img:
    :return:
    """
    prob = np.random.uniform(0, 1)
    if prob < train_parameters['image_enhance_strategy']['contrast_prob']:
        contrast_delta = train_parameters['image_enhance_strategy']['contrast_delta']
        delta = np.random.uniform(-contrast_delta, contrast_delta) + 1
        img = ImageEnhance.Contrast(img).enhance(delta)
    return img


def random_saturation(img):
    """
    图像增强,饱和度调整
    :param img:
    :return:
    """
    prob = np.random.uniform(0, 1)
    if prob < train_parameters['image_enhance_strategy']['saturation_prob']:
        saturation_delta = train_parameters['image_enhance_strategy']['saturation_delta']
        delta = np.random.uniform(-saturation_delta, saturation_delta) + 1
        img = ImageEnhance.Color(img).enhance(delta)
    return img


def random_hue(img):
    """
    图像增强,色度调整
    :param img:
    :return:
    """
    prob = np.random.uniform(0, 1)
    if prob < train_parameters['image_enhance_strategy']['hue_prob']:
        hue_delta = train_parameters['image_enhance_strategy']['hue_delta']
        delta = np.random.uniform(-hue_delta, hue_delta)
        img_hsv = np.array(img.convert('HSV'))
        img_hsv[:, :, 0] = img_hsv[:, :, 0] + delta
        img = Image.fromarray(img_hsv, mode='HSV').convert('RGB')
    return img


def distort_color(img):
    """
    概率的图像增强
    :param img:
    :return:
    """
    prob = np.random.uniform(0, 1)
    # Apply different distort order
    if prob < 0.35:
        img = random_brightness(img)
        img = random_contrast(img)
        img = random_saturation(img)
        img = random_hue(img)
    elif prob < 0.7:
        img = random_brightness(img)
        img = random_saturation(img)
        img = random_hue(img)
        img = random_contrast(img)
    return img


def custom_image_reader(file_list, data_dir, mode):
    """
    自定义用户图片读取器,先初始化图片种类,数量
    :param file_list:
    :param data_dir:
    :param mode:
    :return:
    """
    with codecs.open(file_list) as flist:
        lines = [line.strip() for line in flist]

    def reader():
        np.random.shuffle(lines)
        for line in lines:
            if mode == 'train' or mode == 'val':
                img_path, label = line.split()
                img = Image.open(img_path)
                try:
                    if img.mode != 'RGB':
                        img = img.convert('RGB')
                    if train_parameters['image_enhance_strategy']['need_distort'] == True:
                        img = distort_color(img)
                    if train_parameters['image_enhance_strategy']['need_rotate'] == True:
                        img = rotate_image(img)
                    if train_parameters['image_enhance_strategy']['need_crop'] == True:
                        img = random_crop(img, train_parameters['input_size'])
                    if train_parameters['image_enhance_strategy']['need_flip'] == True:
                        mirror = int(np.random.uniform(0, 2))
                        if mirror == 1:
                            img = img.transpose(Image.FLIP_LEFT_RIGHT)
                    # HWC--->CHW && normalized
                    img = np.array(img).astype('float32')
                    img -= train_parameters['mean_rgb']
                    img = img.transpose((2, 0, 1))  # HWC to CHW
                    img *= 0.007843                 # 像素值归一化
                    yield img, int(label)
                except Exception as e:
                    pass                            # 以防某些图片读取处理出错,加异常处理
            elif mode == 'test':
                img_path = os.path.join(data_dir, line)
                img = Image.open(img_path)
                if img.mode != 'RGB':
                    img = img.convert('RGB')
                img = resize_img(img, train_parameters['input_size'])
                # HWC--->CHW && normalized
                img = np.array(img).astype('float32')
                img -= train_parameters['mean_rgb']
                img = img.transpose((2, 0, 1))  # HWC to CHW
                img *= 0.007843  # 像素值归一化
                yield img

    return reader


def optimizer_momentum_setting():
    """
    阶梯型的学习率适合比较大规模的训练数据
    """
    learning_strategy = train_parameters['momentum_strategy']
    batch_size = train_parameters["train_batch_size"]
    iters = train_parameters["image_count"] // batch_size
    lr = learning_strategy['learning_rate']

    boundaries = [i * iters for i in learning_strategy["lr_epochs"]]
    values = [i * lr for i in learning_strategy["lr_decay"]]
    learning_rate = fluid.layers.piecewise_decay(boundaries, values)
    optimizer = fluid.optimizer.MomentumOptimizer(learning_rate=learning_rate, momentum=0.9)
    return optimizer


def optimizer_rms_setting():
    """
    阶梯型的学习率适合比较大规模的训练数据
    """
    batch_size = train_parameters["train_batch_size"]
    iters = train_parameters["image_count"] // batch_size
    learning_strategy = train_parameters['rsm_strategy']
    lr = learning_strategy['learning_rate']

    boundaries = [i * iters for i in learning_strategy["lr_epochs"]]
    values = [i * lr for i in learning_strategy["lr_decay"]]

    optimizer = fluid.optimizer.RMSProp(
        learning_rate=fluid.layers.piecewise_decay(boundaries, values))

    return optimizer


def optimizer_sgd_setting():
    """
    loss下降相对较慢,但是最终效果不错,阶梯型的学习率适合比较大规模的训练数据
    """
    learning_strategy = train_parameters['sgd_strategy']
    batch_size = train_parameters["train_batch_size"]
    iters = train_parameters["image_count"] // batch_size
    lr = learning_strategy['learning_rate']

    boundaries = [i * iters for i in learning_strategy["lr_epochs"]]
    values = [i * lr for i in learning_strategy["lr_decay"]]
    learning_rate = fluid.layers.piecewise_decay(boundaries, values)
    optimizer = fluid.optimizer.SGD(learning_rate=learning_rate)
    return optimizer


def optimizer_adam_setting():
    """
    能够比较快速的降低 loss,但是相对后期乏力
    """
    learning_strategy = train_parameters['adam_strategy']
    learning_rate = learning_strategy['learning_rate']
    optimizer = fluid.optimizer.Adam(learning_rate=learning_rate)
    return optimizer


def load_params(exe, program):
    if train_parameters['continue_train'] and os.path.exists(train_parameters['save_persistable_dir']):
        logger.info('load params from retrain model')
        fluid.io.load_persistables(executor=exe,
                                   dirname=train_parameters['save_persistable_dir'],
                                   main_program=program)
    elif train_parameters['pretrained'] and os.path.exists(train_parameters['pretrained_dir']):
        logger.info('load params from pretrained model')
        def if_exist(var):
            return os.path.exists(os.path.join(train_parameters['pretrained_dir'], var.name))

        fluid.io.load_vars(exe, train_parameters['pretrained_dir'], main_program=program,
                           predicate=if_exist)


def train():
    train_prog = fluid.Program()
    train_startup = fluid.Program()
    logger.info("create prog success")
    logger.info("train config: %s", str(train_parameters))
    logger.info("build input custom reader and data feeder")
    file_list = os.path.join(train_parameters['data_dir'], "train.txt")
    mode = train_parameters['mode']
    batch_reader = paddle.batch(custom_image_reader(file_list, train_parameters['data_dir'], mode),
                                batch_size=train_parameters['train_batch_size'],
                                drop_last=True)
    place = fluid.CUDAPlace(0) if train_parameters['use_gpu'] else fluid.CPUPlace()
    # 定义输入数据的占位符
    img = fluid.layers.data(name='img', shape=train_parameters['input_size'], dtype='float32')
    label = fluid.layers.data(name='label', shape=[1], dtype='int64')
    feeder = fluid.DataFeeder(feed_list=[img, label], place=place)

    # 选取不同的网络
    logger.info("build newwork")
    model = AlexNet()
    out = model.net(input=img, class_dim=train_parameters['class_dim'])
    cost = fluid.layers.cross_entropy(out, label)
    avg_cost = fluid.layers.mean(x=cost)
    acc_top1 = fluid.layers.accuracy(input=out, label=label, k=1)
    # 选取不同的优化器
    optimizer = optimizer_rms_setting()
    # optimizer = optimizer_momentum_setting()
    # optimizer = optimizer_sgd_setting()
    # optimizer = optimizer_adam_setting()
    optimizer.minimize(avg_cost)
    exe = fluid.Executor(place)

    main_program = fluid.default_main_program()
    exe.run(fluid.default_startup_program())
    train_fetch_list = [avg_cost.name, acc_top1.name, out.name]
    
    load_params(exe, main_program)

    # 训练循环主体
    stop_strategy = train_parameters['early_stop']
    successive_limit = stop_strategy['successive_limit']
    sample_freq = stop_strategy['sample_frequency']
    good_acc1 = stop_strategy['good_acc1']
    successive_count = 0
    stop_train = False
    total_batch_count = 0
    for pass_id in range(train_parameters["num_epochs"]):
        logger.info("current pass: %d, start read image", pass_id)
        batch_id = 0
        for step_id, data in enumerate(batch_reader()):
            t1 = time.time()
            loss, acc1, pred_ot = exe.run(main_program,
                                          feed=feeder.feed(data),
                                          fetch_list=train_fetch_list)
            t2 = time.time()
            batch_id += 1
            total_batch_count += 1
            period = t2 - t1
            loss = np.mean(np.array(loss))
            acc1 = np.mean(np.array(acc1))
            if batch_id % 10 == 0:
                logger.info("Pass {0}, trainbatch {1}, loss {2}, acc1 {3}, time {4}".format(pass_id, batch_id, loss, acc1,
                                                                                            "%2.2f sec" % period))
            # 简单的提前停止策略,认为连续达到某个准确率就可以停止了
            if acc1 >= good_acc1:
                successive_count += 1
                logger.info("current acc1 {0} meets good {1}, successive count {2}".format(acc1, good_acc1, successive_count))
                fluid.io.save_inference_model(dirname=train_parameters['save_freeze_dir'],
                                              feeded_var_names=['img'],
                                              target_vars=[out],
                                              main_program=main_program,
                                              executor=exe)
                if successive_count >= successive_limit:
                    logger.info("end training")
                    stop_train = True
                    break
            else:
                successive_count = 0

            # 通用的保存策略,减小意外停止的损失
            if total_batch_count % sample_freq == 0:
                logger.info("temp save {0} batch train result, current acc1 {1}".format(total_batch_count, acc1))
                fluid.io.save_persistables(dirname=train_parameters['save_persistable_dir'],
                                           main_program=main_program,
                                           executor=exe)
        if stop_train:
            break
    logger.info("training till last epcho, end training")
    fluid.io.save_persistables(dirname=train_parameters['save_persistable_dir'],
                                           main_program=main_program,
                                           executor=exe)
    fluid.io.save_inference_model(dirname=train_parameters['save_freeze_dir'],
                                              feeded_var_names=['img'],
                                              target_vars=[out],
                                              main_program=main_program,
                                              executor=exe)


if __name__ == '__main__':
    init_log_config()
    init_train_parameters()
    train()
2020-01-15 19:42:21,382-INFO: create prog success
2020-01-15 19:42:21,382 - <ipython-input-1-27a7613e6676>[line:537] - INFO: create prog success
2020-01-15 19:42:21,385-INFO: train config: {'input_size': [3, 224, 224], 'class_dim': 3, 'image_count': 239, 'label_dict': {'cuke': 0, 'lettuce': 1, 'lotus_root': 2}, 'data_dir': 'data/data504/vegetables', 'train_file_list': 'train.txt', 'label_file': 'label_list.txt', 'save_freeze_dir': './freeze-model', 'save_persistable_dir': './persistable-params', 'continue_train': False, 'pretrained': True, 'pretrained_dir': 'data/data6462/AlexNet_pretrained', 'mode': 'train', 'num_epochs': 20, 'train_batch_size': 20, 'mean_rgb': [127.5, 127.5, 127.5], 'use_gpu': True, 'image_enhance_strategy': {'need_distort': True, 'need_rotate': True, 'need_crop': True, 'need_flip': True, 'hue_prob': 0.5, 'hue_delta': 18, 'contrast_prob': 0.5, 'contrast_delta': 0.5, 'saturation_prob': 0.5, 'saturation_delta': 0.5, 'brightness_prob': 0.5, 'brightness_delta': 0.125}, 'early_stop': {'sample_frequency': 50, 'successive_limit': 3, 'good_acc1': 0.92}, 'rsm_strategy': {'learning_rate': 0.001, 'lr_epochs': [20, 40, 60, 80, 100], 'lr_decay': [1, 0.5, 0.25, 0.1, 0.01, 0.002]}, 'momentum_strategy': {'learning_rate': 0.001, 'lr_epochs': [20, 40, 60, 80, 100], 'lr_decay': [1, 0.5, 0.25, 0.1, 0.01, 0.002]}, 'sgd_strategy': {'learning_rate': 0.001, 'lr_epochs': [20, 40, 60, 80, 100], 'lr_decay': [1, 0.5, 0.25, 0.1, 0.01, 0.002]}, 'adam_strategy': {'learning_rate': 0.001}}
2020-01-15 19:42:21,385 - <ipython-input-1-27a7613e6676>[line:538] - INFO: train config: {'input_size': [3, 224, 224], 'class_dim': 3, 'image_count': 239, 'label_dict': {'cuke': 0, 'lettuce': 1, 'lotus_root': 2}, 'data_dir': 'data/data504/vegetables', 'train_file_list': 'train.txt', 'label_file': 'label_list.txt', 'save_freeze_dir': './freeze-model', 'save_persistable_dir': './persistable-params', 'continue_train': False, 'pretrained': True, 'pretrained_dir': 'data/data6462/AlexNet_pretrained', 'mode': 'train', 'num_epochs': 20, 'train_batch_size': 20, 'mean_rgb': [127.5, 127.5, 127.5], 'use_gpu': True, 'image_enhance_strategy': {'need_distort': True, 'need_rotate': True, 'need_crop': True, 'need_flip': True, 'hue_prob': 0.5, 'hue_delta': 18, 'contrast_prob': 0.5, 'contrast_delta': 0.5, 'saturation_prob': 0.5, 'saturation_delta': 0.5, 'brightness_prob': 0.5, 'brightness_delta': 0.125}, 'early_stop': {'sample_frequency': 50, 'successive_limit': 3, 'good_acc1': 0.92}, 'rsm_strategy': {'learning_rate': 0.001, 'lr_epochs': [20, 40, 60, 80, 100], 'lr_decay': [1, 0.5, 0.25, 0.1, 0.01, 0.002]}, 'momentum_strategy': {'learning_rate': 0.001, 'lr_epochs': [20, 40, 60, 80, 100], 'lr_decay': [1, 0.5, 0.25, 0.1, 0.01, 0.002]}, 'sgd_strategy': {'learning_rate': 0.001, 'lr_epochs': [20, 40, 60, 80, 100], 'lr_decay': [1, 0.5, 0.25, 0.1, 0.01, 0.002]}, 'adam_strategy': {'learning_rate': 0.001}}
2020-01-15 19:42:21,386-INFO: build input custom reader and data feeder
2020-01-15 19:42:21,386 - <ipython-input-1-27a7613e6676>[line:539] - INFO: build input custom reader and data feeder
2020-01-15 19:42:21,387-INFO: build newwork
2020-01-15 19:42:21,387 - <ipython-input-1-27a7613e6676>[line:552] - INFO: build newwork
2020-01-15 19:42:23,908-INFO: load params from pretrained model
2020-01-15 19:42:23,908 - <ipython-input-1-27a7613e6676>[line:526] - INFO: load params from pretrained model
2020-01-15 19:42:24,647-INFO: current pass: 0, start read image
2020-01-15 19:42:24,647 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 0, start read image
2020-01-15 19:42:27,832-INFO: Pass 0, trainbatch 10, loss 1.0631659030914307, acc1 0.4000000059604645, time 0.03 sec
2020-01-15 19:42:27,832 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 0, trainbatch 10, loss 1.0631659030914307, acc1 0.4000000059604645, time 0.03 sec
2020-01-15 19:42:28,266-INFO: current pass: 1, start read image
2020-01-15 19:42:28,266 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 1, start read image
2020-01-15 19:42:31,170-INFO: Pass 1, trainbatch 10, loss 1.058628797531128, acc1 0.4000000059604645, time 0.02 sec
2020-01-15 19:42:31,170 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 1, trainbatch 10, loss 1.058628797531128, acc1 0.4000000059604645, time 0.02 sec
2020-01-15 19:42:31,821-INFO: current pass: 2, start read image
2020-01-15 19:42:31,821 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 2, start read image
2020-01-15 19:42:34,758-INFO: Pass 2, trainbatch 10, loss 0.8650014996528625, acc1 0.6499999761581421, time 0.03 sec
2020-01-15 19:42:34,758 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 2, trainbatch 10, loss 0.8650014996528625, acc1 0.6499999761581421, time 0.03 sec
2020-01-15 19:42:35,260-INFO: current pass: 3, start read image
2020-01-15 19:42:35,260 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 3, start read image
2020-01-15 19:42:38,102-INFO: Pass 3, trainbatch 10, loss 1.0817111730575562, acc1 0.3499999940395355, time 0.03 sec
2020-01-15 19:42:38,102 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 3, trainbatch 10, loss 1.0817111730575562, acc1 0.3499999940395355, time 0.03 sec
2020-01-15 19:42:38,752-INFO: current pass: 4, start read image
2020-01-15 19:42:38,752 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 4, start read image
2020-01-15 19:42:40,410-INFO: temp save 50 batch train result, current acc1 0.6499999761581421
2020-01-15 19:42:40,410 - <ipython-input-1-27a7613e6676>[line:615] - INFO: temp save 50 batch train result, current acc1 0.6499999761581421
2020-01-15 19:42:48,672-INFO: Pass 4, trainbatch 10, loss 0.7673219442367554, acc1 0.6499999761581421, time 0.03 sec
2020-01-15 19:42:48,672 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 4, trainbatch 10, loss 0.7673219442367554, acc1 0.6499999761581421, time 0.03 sec
2020-01-15 19:42:49,189-INFO: current pass: 5, start read image
2020-01-15 19:42:49,189 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 5, start read image
2020-01-15 19:42:51,984-INFO: Pass 5, trainbatch 10, loss 0.942317008972168, acc1 0.6000000238418579, time 0.03 sec
2020-01-15 19:42:51,984 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 5, trainbatch 10, loss 0.942317008972168, acc1 0.6000000238418579, time 0.03 sec
2020-01-15 19:42:52,433-INFO: current pass: 6, start read image
2020-01-15 19:42:52,433 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 6, start read image
2020-01-15 19:42:55,348-INFO: Pass 6, trainbatch 10, loss 0.7420933842658997, acc1 0.550000011920929, time 0.03 sec
2020-01-15 19:42:55,348 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 6, trainbatch 10, loss 0.7420933842658997, acc1 0.550000011920929, time 0.03 sec
2020-01-15 19:42:55,957-INFO: current pass: 7, start read image
2020-01-15 19:42:55,957 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 7, start read image
2020-01-15 19:42:58,346-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:42:58,346 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:42:59,026-INFO: current acc1 1.0 meets good 0.92, successive count 2
2020-01-15 19:42:59,026 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 2
2020-01-15 19:43:01,101-INFO: Pass 7, trainbatch 10, loss 1.0134819746017456, acc1 0.75, time 0.04 sec
2020-01-15 19:43:01,101 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 7, trainbatch 10, loss 1.0134819746017456, acc1 0.75, time 0.04 sec
2020-01-15 19:43:01,716-INFO: current pass: 8, start read image
2020-01-15 19:43:01,716 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 8, start read image
2020-01-15 19:43:04,460-INFO: Pass 8, trainbatch 10, loss 0.41141408681869507, acc1 0.8999999761581421, time 0.03 sec
2020-01-15 19:43:04,460 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 8, trainbatch 10, loss 0.41141408681869507, acc1 0.8999999761581421, time 0.03 sec
2020-01-15 19:43:04,795-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:04,795 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:06,793-INFO: current pass: 9, start read image
2020-01-15 19:43:06,793 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 9, start read image
2020-01-15 19:43:07,049-INFO: temp save 100 batch train result, current acc1 0.8999999761581421
2020-01-15 19:43:07,049 - <ipython-input-1-27a7613e6676>[line:615] - INFO: temp save 100 batch train result, current acc1 0.8999999761581421
2020-01-15 19:43:15,713-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:15,713 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:18,484-INFO: Pass 9, trainbatch 10, loss 0.3376213014125824, acc1 0.8999999761581421, time 0.03 sec
2020-01-15 19:43:18,484 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 9, trainbatch 10, loss 0.3376213014125824, acc1 0.8999999761581421, time 0.03 sec
2020-01-15 19:43:19,000-INFO: current pass: 10, start read image
2020-01-15 19:43:19,000 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 10, start read image
2020-01-15 19:43:21,914-INFO: Pass 10, trainbatch 10, loss 0.8194038271903992, acc1 0.6000000238418579, time 0.03 sec
2020-01-15 19:43:21,914 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 10, trainbatch 10, loss 0.8194038271903992, acc1 0.6000000238418579, time 0.03 sec
2020-01-15 19:43:22,401-INFO: current pass: 11, start read image
2020-01-15 19:43:22,401 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 11, start read image
2020-01-15 19:43:23,561-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:43:23,561 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:43:27,126-INFO: Pass 11, trainbatch 10, loss 0.3646256923675537, acc1 0.8999999761581421, time 0.02 sec
2020-01-15 19:43:27,126 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 11, trainbatch 10, loss 0.3646256923675537, acc1 0.8999999761581421, time 0.02 sec
2020-01-15 19:43:27,739-INFO: current pass: 12, start read image
2020-01-15 19:43:27,739 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 12, start read image
2020-01-15 19:43:28,791-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:43:28,791 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:43:30,890-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:43:30,890 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:43:33,842-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:33,842 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:35,895-INFO: Pass 12, trainbatch 10, loss 0.1496678739786148, acc1 1.0, time 0.03 sec
2020-01-15 19:43:35,895 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 12, trainbatch 10, loss 0.1496678739786148, acc1 1.0, time 0.03 sec
2020-01-15 19:43:35,897-INFO: current acc1 1.0 meets good 0.92, successive count 2
2020-01-15 19:43:35,897 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 2
2020-01-15 19:43:38,244-INFO: current pass: 13, start read image
2020-01-15 19:43:38,244 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 13, start read image
2020-01-15 19:43:39,840-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:39,840 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:42,090-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:42,090 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:43,857-INFO: temp save 150 batch train result, current acc1 0.949999988079071
2020-01-15 19:43:43,857 - <ipython-input-1-27a7613e6676>[line:615] - INFO: temp save 150 batch train result, current acc1 0.949999988079071
2020-01-15 19:43:51,051-INFO: current acc1 1.0 meets good 0.92, successive count 2
2020-01-15 19:43:51,051 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 2
2020-01-15 19:43:53,476-INFO: Pass 13, trainbatch 10, loss 0.600031316280365, acc1 0.75, time 0.02 sec
2020-01-15 19:43:53,476 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 13, trainbatch 10, loss 0.600031316280365, acc1 0.75, time 0.02 sec
2020-01-15 19:43:53,939-INFO: current pass: 14, start read image
2020-01-15 19:43:53,939 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 14, start read image
2020-01-15 19:43:55,088-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:55,088 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:43:58,719-INFO: Pass 14, trainbatch 10, loss 0.3305586576461792, acc1 0.8999999761581421, time 0.02 sec
2020-01-15 19:43:58,719 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 14, trainbatch 10, loss 0.3305586576461792, acc1 0.8999999761581421, time 0.02 sec
2020-01-15 19:43:59,267-INFO: current pass: 15, start read image
2020-01-15 19:43:59,267 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 15, start read image
2020-01-15 19:43:59,818-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:43:59,818 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:01,819-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:01,819 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:04,206-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:04,206 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:06,548-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:06,548 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:09,153-INFO: Pass 15, trainbatch 10, loss 0.40113502740859985, acc1 0.8500000238418579, time 0.03 sec
2020-01-15 19:44:09,153 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 15, trainbatch 10, loss 0.40113502740859985, acc1 0.8500000238418579, time 0.03 sec
2020-01-15 19:44:09,746-INFO: current pass: 16, start read image
2020-01-15 19:44:09,746 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 16, start read image
2020-01-15 19:44:09,989-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:09,989 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:14,313-INFO: Pass 16, trainbatch 10, loss 0.46252816915512085, acc1 0.8500000238418579, time 0.03 sec
2020-01-15 19:44:14,313 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 16, trainbatch 10, loss 0.46252816915512085, acc1 0.8500000238418579, time 0.03 sec
2020-01-15 19:44:14,520-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:14,520 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:16,518-INFO: current pass: 17, start read image
2020-01-15 19:44:16,518 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 17, start read image
2020-01-15 19:44:16,771-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:16,771 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:21,227-INFO: Pass 17, trainbatch 10, loss 0.38278794288635254, acc1 0.8999999761581421, time 0.03 sec
2020-01-15 19:44:21,227 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 17, trainbatch 10, loss 0.38278794288635254, acc1 0.8999999761581421, time 0.03 sec
2020-01-15 19:44:21,526-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:21,526 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:23,610-INFO: current pass: 18, start read image
2020-01-15 19:44:23,610 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 18, start read image
2020-01-15 19:44:24,085-INFO: temp save 200 batch train result, current acc1 0.8999999761581421
2020-01-15 19:44:24,085 - <ipython-input-1-27a7613e6676>[line:615] - INFO: temp save 200 batch train result, current acc1 0.8999999761581421
2020-01-15 19:44:31,300-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:31,300 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:33,700-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:33,700 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:36,903-INFO: Pass 18, trainbatch 10, loss 0.3098202347755432, acc1 0.949999988079071, time 0.03 sec
2020-01-15 19:44:36,903 - <ipython-input-1-27a7613e6676>[line:596] - INFO: Pass 18, trainbatch 10, loss 0.3098202347755432, acc1 0.949999988079071, time 0.03 sec
2020-01-15 19:44:36,905-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:36,905 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:39,129-INFO: current pass: 19, start read image
2020-01-15 19:44:39,129 - <ipython-input-1-27a7613e6676>[line:581] - INFO: current pass: 19, start read image
2020-01-15 19:44:40,261-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:40,261 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 1
2020-01-15 19:44:42,207-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:42,207 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:44,569-INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:44,569 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 1.0 meets good 0.92, successive count 1
2020-01-15 19:44:46,562-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:46,562 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 2
2020-01-15 19:44:48,594-INFO: current acc1 0.949999988079071 meets good 0.92, successive count 3
2020-01-15 19:44:48,594 - <ipython-input-1-27a7613e6676>[line:600] - INFO: current acc1 0.949999988079071 meets good 0.92, successive count 3
2020-01-15 19:44:50,391-INFO: end training
2020-01-15 19:44:50,391 - <ipython-input-1-27a7613e6676>[line:607] - INFO: end training
2020-01-15 19:44:50,393-INFO: training till last epcho, end training
2020-01-15 19:44:50,393 - <ipython-input-1-27a7613e6676>[line:621] - INFO: training till last epcho, end training

 

预测,判断预估准确率

In[2]

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import numpy as np
import random
import time
import codecs
import sys
import functools
import math
import paddle
import paddle.fluid as fluid
from paddle.fluid import core
from paddle.fluid.param_attr import ParamAttr
from PIL import Image, ImageEnhance

target_size = [3, 224, 224]
mean_rgb = [127.5, 127.5, 127.5]
data_dir = "data/data504/vegetables"
eval_file = "eval.txt"
use_gpu = True
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
save_freeze_dir = "./freeze-model"
[inference_program, feed_target_names, fetch_targets] = fluid.io.load_inference_model(dirname=save_freeze_dir, executor=exe)
# print(fetch_targets)


def crop_image(img, target_size):
    width, height = img.size
    w_start = (width - target_size[2]) / 2
    h_start = (height - target_size[1]) / 2
    w_end = w_start + target_size[2]
    h_end = h_start + target_size[1]
    img = img.crop((w_start, h_start, w_end, h_end))
    return img


def resize_img(img, target_size):
    ret = img.resize((target_size[1], target_size[2]), Image.BILINEAR)
    return ret


def read_image(img_path):
    img = Image.open(img_path)
    if img.mode != 'RGB':
        img = img.convert('RGB')
    img = crop_image(img, target_size)
    img = np.array(img).astype('float32')
    img -= mean_rgb
    img = img.transpose((2, 0, 1))  # HWC to CHW
    img *= 0.007843
    img = img[np.newaxis,:]
    return img


def infer(image_path):
    tensor_img = read_image(image_path)
    label = exe.run(inference_program, feed={feed_target_names[0]: tensor_img}, fetch_list=fetch_targets)
    return np.argmax(label)


def eval_all():
    eval_file_path = os.path.join(data_dir, eval_file)
    total_count = 0
    right_count = 0
    with codecs.open(eval_file_path, encoding='utf-8') as flist: 
        lines = [line.strip() for line in flist]
        t1 = time.time()
        for line in lines:
            total_count += 1
            parts = line.strip().split()
            result = infer(parts[0])
            # print("infer result:{0} answer:{1}".format(result, parts[1]))
            if str(result) == parts[1]:
                right_count += 1
        period = time.time() - t1
        print("total eval count:{0} cost time:{1} predict accuracy:{2}".format(total_count, "%2.2f sec" % period, right_count / total_count))


if __name__ == '__main__':
    eval_all()
total eval count:61 cost time:0.46 sec predict accuracy:0.9180327868852459

 点击链接,使用AI Studio一键上手实践项目吧:https://aistudio.baidu.com/aistudio/projectdetail/169431

下载安装命令

## CPU版本安装命令
pip install -f https://paddlepaddle.org.cn/pip/oschina/cpu paddlepaddle

## GPU版本安装命令
pip install -f https://paddlepaddle.org.cn/pip/oschina/gpu paddlepaddle-gpu

>> 访问 PaddlePaddle 官网,了解更多相关内容

{{o.name}}


{{m.name}}

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/tech/opensource/72682.html

(0)
上一篇 2021年8月11日 22:19
下一篇 2021年8月11日 22:19

相关推荐

发表回复

登录后才能评论