Mik*_*ike 13 python deep-learning keras
在具有Functional API的Keras模型中,我需要使用ImageDataGenerator调用fit_generator来训练增强图像数据.问题是我的模型有两个输出:我想要预测的掩码和二进制值我显然只想增加输入和掩码输出而不是二进制值.我怎样才能做到这一点?
JMa*_*arc 23
下面的例子可能是不言自明的!'虚拟'模型需要1个输入(图像),它输出2个值.该模型计算每个输出的MSE.
x = Convolution2D(8, 5, 5, subsample=(1, 1))(image_input)
x = Activation('relu')(x)
x = Flatten()(x)
x = Dense(50, W_regularizer=l2(0.0001))(x)
x = Activation('relu')(x)
output1 = Dense(1, activation='linear', name='output1')(x)
output2 = Dense(1, activation='linear', name='output2')(x)
model = Model(input=image_input, output=[output1, output2])
model.compile(optimizer='adam', loss={'output1': 'mean_squared_error', 'output2': 'mean_squared_error'})
Run Code Online (Sandbox Code Playgroud)
下面的功能生成批次以在训练期间为模型提供信息.它需要训练数据x和标签y,其中y = [y1,y2]
batch_generator(x, y, batch_size, is_train):
sample_idx = 0
while True:
X = np.zeros((batch_size, input_height, input_width, n_channels), dtype='float32')
y1 = np.zeros((batch_size, mask_height, mask_width), dtype='float32')
y2 = np.zeros((batch_size, 1), dtype='float32')
# fill up the batch
for row in range(batch_sz):
image = x[sample_idx]
mask = y[0][sample_idx]
binary_value = y[1][sample_idx]
# transform/preprocess image
image = cv2.resize(image, (input_width, input_height))
if is_train:
image, mask = my_data_augmentation_function(image, mask)
X_batch[row, ;, :, :] = image
y1_batch[row, :, :] = mask
y2_batch[row, 0] = binary_value
sample_idx += 1
# Normalize inputs
X_batch = X_batch/255.
yield(X_batch, {'output1': y1_batch, 'output2': y2_batch} ))
Run Code Online (Sandbox Code Playgroud)
最后,我们调用fit_generator()
model.fit_generator(batch_generator(X_train, y_train, batch_size, is_train=1))
Run Code Online (Sandbox Code Playgroud)
如果你已经分离了掩码和二进制值,你可以尝试这样的事情:
generator = ImageDataGenerator(rotation_range=5.,
width_shift_range=0.1,
height_shift_range=0.1,
horizontal_flip=True,
vertical_flip=True)
def generate_data_generator(generator, X, Y1, Y2):
genX = generator.flow(X, seed=7)
genY1 = generator.flow(Y1, seed=7)
while True:
Xi = genX.next()
Yi1 = genY1.next()
Yi2 = function(Y2)
yield Xi, [Yi1, Yi2]
Run Code Online (Sandbox Code Playgroud)
因此,您使用相同的生成器对输入和掩码使用相同的种子来定义相同的操作.您可以根据需要更改二进制值(Y2).然后,调用fit_generator():
model.fit_generator(generate_data_generator(generator, X, Y1, Y2),
epochs=epochs)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12507 次 |
| 最近记录: |