MobileNet实战:tensorflow2

这里可以看出tensorflow2.0以上的版本集成了Keras,我们在使用的时候就不必单独安装Keras了,以前的代码升级到tensorflow2.0以上的版本将keras前面加上tensorflow即可。

tensorflow说完了,再说明一下几个重要的全局参数:

  • norm_size = 224, 设置输入图像的大小,MobileNetV3默认的图片尺寸是224×224。

  • datapath = ‘data/train’, 设置图片存放的路径,在这里要说明一下如果图片很多,一定不要放在工程目录下,否则Pycharm加载工程的时候会浏览所有的图片,很慢很慢。

  • EPOCHS = 100, epochs的数量,关于epoch的设置多少合适,这个问题很纠结,一般情况设置300足够了,如果感觉没有训练好,再载入模型训练。

  • INIT_LR = 1e-3, 学习率,一般情况从0.001开始逐渐降低,也别太小了到1e-6就可以了。

  • classnum = 12, 类别数量,数据集有两个类别,所有就分为两类。

  • batch_size =16, batchsize,根据硬件的情况和数据集的大小设置,太小了loss浮动太大,太大了收敛不好,根据经验来,一般设置为2的次方。windows可以通过任务管理器查看显存的占用情况。

image-20220126135414054

Ubuntu可以使用nvidia-smi查看显存的占用。

image-20220120064407104

  • 定义numpy.random的随机因子。这样就可以固定随机的index

第二步 加载图片


和以前做法不同的是,这里不再处理图片,而是只返回图片路径的list列表。

具体做法详见代码:

def loadImageData():

imageList = []

listClasses = os.listdir(datapath) # 类别文件夹

print(listClasses)

for class_name in listClasses:

label_id = dicClass[class_name]

class_path = os.path.join(datapath, class_name)

image_names = os.listdir(class_path)

for image_name in image_names:

image_full_path = os.path.join(class_path, image_name)

labelList.append(label_id)

imageList.append(image_full_path)

return imageList

print(“开始加载数据”)

imageArr = loadImageData()

labelList = np.array(labelList)

print(“加载数据完成”)

print(labelList)

做好数据之后,我们需要切分训练集和测试集,一般按照4:1或者7:3的比例来切分。切分数据集使用train_test_split()方法,需要导入from sklearn.model_selection import train_test_split 包。例:

trainX, valX, trainY, valY = train_test_split(imageArr, labelList, test_size=0.2, random_state=42)

第三步 图像增强


train_transform = albumentations.Compose([

albumentations.OneOf([

albumentations.RandomGamma(gamma_limit=(60, 120), p=0.9),

albumentations.RandomBrightnessContrast(brightness_limit=0.2, contrast_limit=0.2, p=0.9),

albumentations.CLAHE(clip_limit=4.0, tile_grid_size=(4, 4), p=0.9),

]),

albumentations.HorizontalFlip(p=0.5),

albumentations.ShiftScaleRotate(shift_limit=0.2, scale_limit=0.2, rotate_limit=20,

interpolation=cv2.INTER_LINEAR, border_mode=cv2.BORDER_CONSTANT, p=1),

albumentations.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, p=1.0)

])

val_transform = albumentations.Compose([

albumentations.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, p=1.0)

])

这个随意写的,具体的设置可以参考我以前写的文章:

图像增强库Albumentations使用总结_AI浩-CSDN博客_albumentations

写了两个数据增强,一个是用于训练,一个用于验证。验证集只需要对图片做归一化处理。

第四步 定义图像处理的方法


generator的主要作用是处理图像,并迭代的方式返回一个batch的图像以及对应的label。

思路:

获取list的长度。

计算迭代次数。

生成indexs列表。

如果是训练,则打乱顺序。

在while循环:

  • 循环迭代次数

  • 初始化input_samples和input_labels,连个list分别用来存放image和image对应的标签。

  • 获取本轮迭代的indexs。

  • 如果超过最大list的最大长度,则按照最大长度获取。

  • 循环得到的indexs

  • 分别从file_pathList和labels,得到图片的路径和对应的label

  • 读取图片,如果图片的维度超过了3维,取前3维度。

  • 如果是训练就训练的transform,如果不是就执行验证的transform。

  • resize图片

  • 将image转数组

  • 将图像和label分别放到input_samples和input_labels

  • 将list转numpy数组。

  • 返回一次迭代

def generator(file_pathList,labels,batch_size,train_action=False):

L = len(file_pathList)

num_minibatches = int(L/ batch_size)

indexs= list(range(L))

if train_action==True:

np.random.shuffle(indexs)

while True:

for i in range(num_minibatches+1):

input_labels = []

input_samples = []

image_indexs = indexs[i * batch_size:(i + 1) * batch_size]

if (i + 1) * batch_size>L:

image_indexs = indexs[i * batch_size:L]

for index in image_indexs:

X = file_pathList[index]

Y = labels[index]

image = cv2.imdecode(np.fromfile(X, dtype=np.uint8), -1)

if image.shape[2] > 3:

image = image[:, :, :3]

if train_action:

image = train_transform(image=image)[‘image’]

else:

image = val_transform(image=image)[‘image’]

image = cv2.resize(image, (norm_size, norm_size), interpolation=cv2.INTER_LANCZOS4)

image = img_to_array(image)

input_samples.append(image)

input_labels.append(Y)

batch_x = np.asarray(input_samples)

batch_y = np.asarray(input_labels)

yield (batch_x, batch_y)

第五步 保留最好的模型和动态设置学习率


ModelCheckpoint:用来保存成绩最好的模型。

语法如下:

keras.callbacks.ModelCheckpoint(filepath, monitor=‘val_loss’, verbose=0, save_best_only=False, save_weights_only=False, mode=‘auto’, period=1)

该回调函数将在每个epoch后保存模型到filepath

filepath可以是格式化的字符串,里面的占位符将会被epoch值和传入on_epoch_end的logs关键字所填入

例如,filepath若为weights.{epoch:02d-{val_loss:.2f}}.hdf5,则会生成对应epoch和验证集loss的多个文件。

参数

  • filename:字符串,保存模型的路径
  • monitor:需要监视的值
  • verbose:信息展示模式,0或1
  • save_best_only:当设置为True时,将只保存在验证集上性能最好的模型
  • mode:‘auto’,‘min’,‘max’之一,在save_best_only=True时决定性能最佳模型的评判准则,例如,当监测值为val_acc时,模式应为max,当检测值为val_loss时,模式应为min。在auto模式下,评价准则由被监测值的名字自动推断。
  • save_weights_only:若设置为True,则只保存模型权重,否则将保存整个模型(包括模型结构,配置信息等)
  • period:CheckPoint之间的间隔的epoch数

ReduceLROnPlateau:当评价指标不在提升时,减少学习率,语法如下:

keras.callbacks.ReduceLROnPlateau(monitor=‘val_loss’, factor=0.1, patience=10, verbose=0, mode=‘auto’, epsilon=0.0001, cooldown=0, min_lr=0)

当学习停滞时,减少2倍或10倍的学习率常常能获得较好的效果。该回调函数检测指标的情况,如果在patience个epoch中看不到模型性能提升,则减少学习率

参数

  • monitor:被监测的量
  • factor:每次减少学习率的因子,学习率将以lr = lr*factor的形式被减少
  • patience:当patience个epoch过去而模型性能不提升时,学习率减少的动作会被触发
  • mode:‘auto’,‘min’,‘max’之一,在min模式下,如果检测值触发学习率减少。在max模式下,当检测值不再上升则触发学习率减少。
  • epsilon:阈值,用来确定是否进入检测值的“平原区”
  • cooldown:学习率减少后,会经过cooldown个epoch才重新进行正常操作
  • min_lr:学习率的下限

本例代码如下:

checkpointer = ModelCheckpoint(filepath=‘best_model.hdf5’,

monitor=‘val_accuracy’, verbose=1, save_best_only=True, mode=‘max’)

reduce = ReduceLROnPlateau(monitor=‘val_accuracy’, patience=10,

verbose=1,

factor=0.5,

min_lr=1e-6)

第六步 建立模型并训练


model = Sequential()

model.add(MobileNetV3Large(input_shape=(224,224,3),include_top=False, pooling=‘avg’, weights=‘imagenet’))

model.add(Dense(classnum, activation=‘softmax’))

optimizer = Adam(learning_rate=INIT_LR)

model.compile(optimizer=optimizer, loss=‘sparse_categorical_crossentropy’, metrics=[‘accuracy’])

history = model.fit(generator(trainX,trainY,batch_size,train_action=True),

steps_per_epoch=len(trainX) / batch_size,

validation_data=generator(valX,valY,batch_size,train_action=False),

epochs=EPOCHS,

validation_steps=len(valX) / batch_size,

callbacks=[checkpointer, reduce])

model.save(‘my_model.h5’)

print(history)

如果想指定classes,有两个条件:include_top:True, weights:None。否则无法指定classes。

所以指定classes就不能用预训练了,所以采用另一种方式:

model = Sequential()

model.add(MobileNetV3Large(include_top=False, pooling=‘avg’, weights=‘imagenet’))

model.add(Dense(classnum, activation=‘softmax’))

这样既能使用预训练,又能指定classnum。

另外,在2.X版本中fit支持generator方式,所以直接使用fit。

运行结果:

image-20220206142346625

第七步 评估模型


predictions = model.predict_generator(generator(valX,valY,batch_size,train_action=False),steps=len(valX) / batch_size)

print(classification_report(valY,predictions.argmax(axis=1), target_names=dicClass.keys()))

运行结果:

image-20220206142202018

第八步 保留训练结果,并将其生成图片


loss_trend_graph_path = r"WW_loss.jpg"

acc_trend_graph_path = r"WW_acc.jpg"

import matplotlib.pyplot as plt

print(“Now,we start drawing the loss and acc trends graph…”)

summarize history for accuracy

fig = plt.figure(1)

plt.plot(history.history[“accuracy”])

plt.plot(history.history[“val_accuracy”])

plt.title(“Model accuracy”)

plt.ylabel(“accuracy”)

plt.xlabel(“epoch”)

plt.legend([“train”, “test”], loc=“upper left”)

plt.savefig(acc_trend_graph_path)

plt.close(1)

summarize history for loss

fig = plt.figure(2)

plt.plot(history.history[“loss”])

plt.plot(history.history[“val_loss”])

plt.title(“Model loss”)

plt.ylabel(“loss”)

plt.xlabel(“epoch”)

plt.legend([“train”, “test”], loc=“upper left”)

plt.savefig(loss_trend_graph_path)

plt.close(2)

print(“We are done, everything seems OK…”)

#windows系统设置10关机

#os.system(“shutdown -s -t 10”)

image-20220202121436026

image-20220202121449688

测试部分

===============================================================

单张图片预测


1、导入依赖

import cv2

import numpy as np

from tensorflow.keras.preprocessing.image import img_to_array

from tensorflow.keras.models import load_model

import time

import os

import albumentations

2、设置全局参数

这里注意,字典的顺序和训练时的顺序保持一致

norm_size=224

imagelist=[]

emotion_labels = {

0: ‘Black-grass’,

1: ‘Charlock’,

2: ‘Cleavers’,

3: ‘Common Chickweed’,

4: ‘Common wheat’,

5: ‘Fat Hen’,

6: ‘Loose Silky-bent’,

7: ‘Maize’,

8: ‘Scentless Mayweed’,

9: ‘Shepherds Purse’,

10: ‘Small-flowered Cranesbill’,

11: ‘Sugar beet’,

}

3、设置图片归一化参数

归一化参数的设置和验证的参数保持一致

val_transform = albumentations.Compose([

albumentations.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225), max_pixel_value=255.0, p=1.0)

])

4、加载模型

emotion_classifier=load_model(“my_model.h5”)

5、处理图片

处理图片的逻辑和训练集也类似,步骤:

  • 读取图片

  • 将图片resize为norm_size×norm_size大小。

  • 将图片转为数组。

  • 放到imagelist中。

  • 将list转为numpy数组。

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数大数据工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年大数据全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上大数据开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注大数据获取)
img

  • 读取图片

  • 将图片resize为norm_size×norm_size大小。

  • 将图片转为数组。

  • 放到imagelist中。

  • 将list转为numpy数组。

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数大数据工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年大数据全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友。
[外链图片转存中…(img-9Zbg8hgd-1712853029723)]
[外链图片转存中…(img-xN4hvMTU-1712853029723)]
[外链图片转存中…(img-q0zpPwjU-1712853029723)]
[外链图片转存中…(img-lGdaGtCx-1712853029724)]
[外链图片转存中…(img-ukTHi7W7-1712853029724)]

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上大数据开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加VX:vip204888 (备注大数据获取)
[外链图片转存中…(img-PKieiggi-1712853029724)]

  • 14
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Mobilenet-V3 is a convolutional neural network architecture that is designed for efficient mobile and embedded vision applications. It is an extension of the Mobilenet-V2 architecture, with improvements in terms of accuracy, efficiency, and flexibility. To use Mobilenet-V3 in TensorFlow, you can either build the network from scratch or utilize pre-trained models provided by TensorFlow. The pre-trained models are available in different sizes and variations, such as small, large, and search-space options. To get started with Mobilenet-V3 in TensorFlow, you can follow these steps: 1. Install TensorFlow: Make sure you have TensorFlow installed on your system. You can use pip to install it: `pip install tensorflow`. 2. Load the Mobilenet-V3 model: If you want to use a pre-trained model, you can use the `tf.keras.applications` module to load it. For example, to load the small variant of Mobilenet-V3, you can use: ```python import tensorflow as tf model = tf.keras.applications.MobileNetV3Small() ``` 3. Preprocess your input data: Before feeding your data into the network, you may need to preprocess it according to the requirements of Mobilenet-V3. This typically involves resizing the images and normalizing the pixel values. 4. Run inference: Once you have loaded the model and preprocessed your data, you can run inference to obtain predictions. Pass your input data through the model and interpret the output based on your task (e.g., classification, object detection, etc.). Note that this is just a brief overview of how to use Mobilenet-V3 in TensorFlow. Depending on your specific requirements and use case, you may need to customize the architecture or fine-tune the pre-trained models. It's recommended to consult the TensorFlow documentation and resources for more detailed instructions and examples.

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值