AttributeError:使用后端random_uniform时,'Tensor'对象没有属性'_keras_history'

时间:2018-05-23 08:54:14

标签: python tensorflow keras

我正在Keras实施一个WGAN-GP,我计算了两个张量的随机加权平均值。

def random_weighted_average(self, generated, real):
    alpha = K.random_uniform(shape=K.shape(real))
    diff = keras.layers.Subtract()([generated, real])
    return keras.layers.Add()([real, keras.layers.Multiply()([alpha, diff])])

这就是它的用法。一旦我尝试创建discriminator_model,它就会抛出错误。

averaged_samples = self.random_weighted_average(
    generated_samples_for_discriminator, 
    real_samples)
averaged_samples_out = self.discriminator(averaged_samples)

discriminator_model = Model(
    inputs=[real_samples, generator_input_for_discriminator],
    outputs=[
        discriminator_output_from_real_samples,
        discriminator_output_from_generator, 
        averaged_samples_out
    ])

我的后端是TensorFlow。当我在最后一行使用alpha时,我收到以下错误:

AttributeError: 'Tensor' object has no attribute '_keras_history'

我尝试将alpha替换为realgenerated以查看它是否与后端张量有关,情况就是如此(错误消失了)。那可能导致这个问题呢?我需要一个随机均匀采样的张量,其形状为realgenerated

1 个答案:

答案 0 :(得分:1)

使用后端功能的自定义操作需要围绕Layer进行处理。如果您没有任何可训练的权重,就像您的情况一样,最简单的方法是使用Lambda图层:

def random_weighted_average(inputs):
  generated, real = inputs
  alpha = K.random_uniform(shape=K.shape(real))
  diff = generated - real
  return real + alpha * diff
averaged_samples = Lambda(random_weighted_average)([generated_for_discriminator, real_samples])