18.2:tensorflow分类模型mobilenetv2训练(数据增强,保存模型,衰减学习率,tensorboard),预测图像(单张,批量预测),导出为pb完整示例

二、预测

经过一段时间的训练后在model_save文件夹下保存了下面的模型:

他想使用model.ckpt-250000模型对数据进行预测。

他写了个predict.py程序为:

#coding:utf-8
import os, cv2
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # use cpu

import numpy as np
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import glob

import model


config = tf.ConfigProto()
config.gpu_options.allow_growth = True
os.environ["CUDA_VISIBLE_DEVICES"] = "0"  # use gpu 0

label_dict, label_dict_res = {}, {}
with open("label.txt", 'r') as f:
    for line in f.readlines():
        folder, label = line.strip().split(':')[0], line.strip().split(':')[1]
        label_dict[folder] = label
        label_dict_res[label] = folder
print(label_dict)

N_CLASSES = len(label_dict)
IMG_W = 224
IMG_H = IMG_W

def init_tf(logs_train_dir = './model_save/model.ckpt-250000'):
    global sess, pred, x
    # process image
    x = tf.placeholder(tf.float32, shape=[IMG_W, IMG_W, 3])
    x_norm = tf.image.per_image_standardization(x)
    x_4d = tf.reshape(x_norm, [-1, IMG_W, IMG_W, 3])
    # predict
    logit = model.MobileNetV2(x_4d, num_classes=N_CLASSES, is_training=False).output
    print("logit", np.shape(logit))
    #logit = model.model4(x_4d, N_CLASSES, is_trian=False)
    #logit = model.model2(x_4d, batch_size=1, n_classes=N_CLASSES)
    pred = tf.nn.softmax(logit)

    saver = tf.train.Saver()
    sess = tf.Session(config=config)
    saver.restore(sess, logs_train_dir)
    print('load model done...')

def evaluate_image(img_dir):
    # read image
    im = cv2.imread(img_dir)
    im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
    im = cv2.resize(im, (IMG_W, IMG_W))
    image_array = np.array(im)

    prediction = sess.run(pred, feed_dict={x: image_array})
    max_index = np.argmax(prediction)
    pred_label = label_dict_res[str(max_index)]
    print("%s, predict: %s(index:%d), prob: %f" %(img_dir, pred_label, max_index, prediction[0][max_index]))
    

if __name__ == '__main__':
    init_tf()
    data_path = "/media/DATA2/sku_val"
    label = os.listdir(data_path)
    for l in label:
        if os.path.isfile(os.path.join(data_path, l)):
            continue
        for img in glob.glob(os.path.join(data_path, l, "*.jpg")):
            evaluate_image(img_dir=img)
    sess.close()

他嫌一张张输入有点慢,于是改了以下代码,让一次输入一个batch。命名为predict_batch.py

#coding:utf-8
import os, cv2, time
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"  # use cpu

import numpy as np
import tensorflow as tf
from PIL import Image
import matplotlib.pyplot as plt
import glob

import model

label_dict, label_dict_res = {}, {}
with open("label.txt", 'r') as f:
    for line in f.readlines():
        folder, label = line.strip().split(':')[0], line.strip().split(':')[1]
        label_dict[folder] = label
        label_dict_res[label] = folder
print(label_dict)

N_CLASSES = len(label_dict)
IMG_W = 224
IMG_H = IMG_W
batch_size = 16

os.environ["CUDA_VISIBLE_DEVICES"] = "0"  # use gpu 0
config = tf.ConfigProto()
config.gpu_options.allow_growth = True


def get_imgpath(path):
    img_list = []
    for fpath , dirs , fs in os.walk(path):
        for f in fs:
            img_path = os.path.join(fpath , f)
            if os.path.dirname(img_path) == os.getcwd():
                continue
            if not os.path.isfile(img_path):
                continue
            if os.path.basename(img_path)[-3:] == "jpg":
                img_list.append(img_path)
    return img_list


def init_tf(logs_train_dir = './model_save/model.ckpt-140000'):
    global sess, pred, x
    # process image
    x = tf.placeholder(tf.float32, shape=[None, IMG_W, IMG_W, 3], name="input_1")
    # predict
    logit = model.MobileNetV2(x, num_classes=N_CLASSES, is_training=False).output
    #logit = model.model4(x, N_CLASSES, is_trian=False)
    #logit = model.model2(x_4d, batch_size=1, n_classes=N_CLASSES)
    pred = tf.nn.softmax(logit, name="pred")

    saver = tf.train.Saver()
    sess = tf.Session(config=config)
    saver.restore(sess, logs_train_dir)
    print('load model done...')

def evaluate_image(img_dir):
    # read and process image
    batch_img = []
    for img in img_dir:    
        im = cv2.imread(img)
        im = cv2.cvtColor(im, cv2.COLOR_BGR2RGB)
        im = cv2.resize(im, (IMG_W, IMG_W))
        im_mean = np.mean(im)
        stddev = max(np.std(im), 1.0/np.sqrt(IMG_W*IMG_H*3))
        im = (im - im_mean) / stddev
        image_array = np.array(im)
        batch_img.append(image_array)
    # output sotfmax
    prediction = sess.run(pred, feed_dict={x: batch_img})
    for i in range(len(img_dir)):
        img = img_dir[i]
        max_index = np.argmax(prediction[i])
        print("img:%s, predict: %s, prob: %f" % (img, label_dict_res[str(max_index)], prediction[i][max_index]))
    

if __name__ == '__main__':
    init_tf()
    data_path = "/media/DATA2/sku_val"
    img_list = get_imgpath(data_path)
    print("there are %d images in %s" %(len(img_list), data_path))
    total_batch = len(img_list)/batch_size
    start = time.time()
    for i in range(total_batch):
        print(str(i) + "-"*50)
        batch_img = img_list[i*batch_size: (i+1)*batch_size]
        evaluate_image(batch_img)
    print("time cost:", time.time()-start)
    sess.close()

下一篇:导出.pb文件并预测图像https://blog.csdn.net/u010397980/article/details/84932538

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 11
    评论
好的,以下是您需要的代码: 1. 数据集准备和预处理 ```python import tensorflow as tf import numpy as np import os # 定义数据集目录和类别数 data_dir = 'path/to/dataset' num_classes = 2 # 定义图像大小和批次大小 image_size = 224 batch_size = 32 # 定义数据增强器,包括随机裁剪、水平翻转和随机亮度、对比度和饱和度变换 data_augmentation = tf.keras.Sequential([ tf.keras.layers.experimental.preprocessing.RandomCrop(image_size, image_size), tf.keras.layers.experimental.preprocessing.RandomFlip(mode='horizontal'), tf.keras.layers.experimental.preprocessing.RandomContrast(0.1), tf.keras.layers.experimental.preprocessing.RandomBrightness(0.1), tf.keras.layers.experimental.preprocessing.RandomSaturation(0.1), ]) # 定义训练集和验证集 train_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, validation_split=0.2, subset='training', seed=123, image_size=(image_size, image_size), batch_size=batch_size ) val_ds = tf.keras.preprocessing.image_dataset_from_directory( data_dir, validation_split=0.2, subset='validation', seed=123, image_size=(image_size, image_size), batch_size=batch_size ) # 对训练集应用数据增强器 train_ds = train_ds.map(lambda x, y: (data_augmentation(x, training=True), y)) # 对验证集进行缓存和预取以加速读取速度 val_ds = val_ds.cache().prefetch(buffer_size=tf.data.AUTOTUNE) ``` 2. 模型构建 ```python from tensorflow.keras.applications import MobileNetV3Small # 加载 MobileNetV3 模型,不包括分类层 base_model = MobileNetV3Small(include_top=False, weights='imagenet', input_shape=(image_size, image_size, 3)) # 冻结模型的所有层,以便只训练新添加的分类层 base_model.trainable = False # 添加全局平均池化层和分类层 global_average_layer = tf.keras.layers.GlobalAveragePooling2D() prediction_layer = tf.keras.layers.Dense(num_classes, activation='softmax') # 构建完整模型 model = tf.keras.Sequential([ base_model, global_average_layer, prediction_layer ]) ``` 3. 模型编译和训练 ```python # 编译模型,选择损失函数、优化器和评价指标 model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy']) # 定义回调函数,包括学习率衰减和早停 lr_scheduler = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=2, verbose=1, factor=0.5) early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5, verbose=1, restore_best_weights=True) # 训练模型,选择训练轮数和回调函数 epochs = 20 history = model.fit(train_ds, epochs=epochs, validation_data=val_ds, callbacks=[lr_scheduler, early_stopping]) ``` 4. 模型预测保存 ```python # 对单张图像进行预测 img_path = 'path/to/image' img = tf.keras.preprocessing.image.load_img(img_path, target_size=(image_size, image_size)) img_array = tf.keras.preprocessing.image.img_to_array(img) img_array = tf.expand_dims(img_array, 0) # 扩展维度以匹配模型输入 predictions = model.predict(img_array) print(predictions) # 保存整个模型为 SavedModel 格式 tf.saved_model.save(model, 'saved_model') ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值