MobileNet实战:tensorflow2(1)

本文详细介绍了如何使用Albumentations进行图像预处理,包括训练和验证数据增强方法,以及如何定义和执行数据生成器。此外,还涵盖了模型的训练、验证、模型保存策略(如ModelCheckpoint和ReduceLROnPlateau)以及模型评估和预测的过程。
摘要由CSDN通过智能技术生成

])

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的log

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值