如何在Keras中应用旋转而不使用model.fit_发电机?

2024-04-26 05:35:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在研究一个使用卷积神经网络的图像像素分类问题。 我的培训images的大小是128x128x3,并且 标签mask128x128

我在Keras进行如下培训:

Xtrain, Xvalid, ytrain, yvalid = train_test_split(images, masks,test_size=0.3, random_state=567)

model.fit(Xtrain, ytrain, batch_size=32, epochs=20, verbose=1, shuffle=True, validation_data=(Xvalid, yvalid))

但是,我想对Xtrain和{}应用随机的2D旋转,它们的大小分别是128x128x3和{}。更具体地说,我想对每个epoch迭代应用这个旋转。在

目前,我想继续使用model.fit,而不是使用model.fit_generator,因为我知道数据扩充通常是使用.fit_generator完成的。在

所以本质上,我想循环model.fit,这样Xtrain和{}在每个历元中随机旋转。我是Python和Keras的新手,所以如果有可能的话,欢迎有任何见解。在


Tags: test图像sizemodel神经网络像素generator卷积
1条回答
网友
1楼 · 发布于 2024-04-26 05:35:53

下面是一个使用ImageDataGenerator将输出保存到指定目录的示例,从而避免了使用model.fit_发电机. 在

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img

datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')

img = load_img('data/train/cats/cat.0.jpg')  # this is a PIL image
x = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, 3, 150, 150)

# the .flow() command below generates batches of randomly transformed images
# and saves the results to the `preview/` directory
i = 0
for batch in datagen.flow(x, batch_size=1,
                          save_to_dir='preview', save_prefix='cat', save_format='jpeg'):
    i += 1
    if i > 20:
        break  # otherwise the generator would loop indefinitely

从这里拍摄:https://blog.keras.io/building-powerful-image-classification-models-using-very-little-data.html

您可以更改参数以适合您的用例,然后生成xu train和xu valid或其他数据集,然后加载到内存中并使用普通的old模型.拟合. 在

相关问题 更多 >