当前位置: 首页 > 面试题库 >

Keras:如何将fit_generator与不同类型的多个输出一起使用

苍志文
2023-03-14
问题内容

在具有功能API的Keras模型中,我需要调用fit_generator来使用ImageDataGenerator训练增强图像数据。问题是我的模型有两个输出:我要预测的掩码和一个二进制值,显然我只想增加输入和掩码输出,而不是二进制值。我该如何实现?


问题答案:

下面的示例可能是不言自明的!“虚拟”模型采用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'})

下面的函数生成批次以在训练过程中提供模型。它采用训练数据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} ))

最后,我们调用fit_generator()

    model.fit_generator(batch_generator(X_train, y_train, batch_size, is_train=1))


 类似资料:
  • 我正在用人脸图像数据集训练一个卷积神经网络。该数据集有10,000个尺寸为700x700的图像。我的模型有12层。我正在使用生成器函数将图像读取到Keras fit_generator函数中,如下所示。 train_file_names==>包含训练实例文件名的Python列表 train_class_labels==>一个热编码类标记的数组([0,1,0],[0,0,1]等) train_dat

  • 问题内容: 关闭。 此问题不符合堆栈溢出准则。它当前不接受答案。 想改善这个问题吗? 更新问题,使其成为Stack Overflow的主题。 去年关闭。 改善这个问题 我正在尝试使用keras来拟合CNN模型以对图像进行分类。数据集具有来自某些类别的更多图像,因此其不平衡。 我在Keras中阅读了有关如何权衡损失以解决这一问题的其他方法,例如:https : //datascience.stack

  • 问题内容: 给定一个预测变量向量时,我有一个问题要处理两个输出。假设预测变量矢量看起来像,它是坐标,并且是附加到出现坐标的其他属性。基于这个预测变量集,我想进行预测。这是一个时间序列问题,我正在尝试使用多元回归解决。我的问题是如何设置keras,这可以在最后一层为我提供2个输出。 问题答案:

  • 问题内容: 这是课程: 现在,我试图从类中“反射”此方法: 问题答案: 只有一个。 另一种选择是。 其他原语也是如此。

  • 我用的是py。测试以运行测试。我将它与pytest xdist一起使用以并行运行测试。我想在测试中看到print语句的输出。 我有:Ubuntu 15.10,Python 2.7.10,pytest-2.9.1,plugy-0.3.1。 这是我的测试文件: 当我跑步的时候。测试时,没有打印任何内容。这是预期的:默认情况下,py。测试捕获输出。 当我跑步的时候。test-s,它会打印test_a和t

  • 问题内容: 我在生成HTML的表单中有一个标记。当我通过表单提交(例如,提交按钮等)提交表单时,在操作方法中一切正常。但是,当我将代码更改为: 在后端,该字段始终为。 在操作类中,文件字段的定义如下(使用setter和getter): 是因为现在表单已序列化,所以无法在后端正确设置文件字段了吗? 问题答案: 这是因为jQuery.serialize()仅序列化输入元素,而不序列化其中的数据。 仅“