])
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