在Keras中的批处理数据上调用合并层(在批处理上平均层的输出)

时间:2019-05-30 19:24:11

标签: python tensorflow keras

我正在使用Keras功能API,并且对训练批次中上一层的平均输出感兴趣。

我尝试仅在Dense层的输出上调用Keras Average层。

这是一个简单的例子。

from keras.models import  Model
from keras import layers
from keras import Input
from keras.utils import plot_model

input_tensor = layers.Input(shape=(784,))
output = layers.Dense(10,)(input_tensor)
average = layers.Average()(output)
avgout = Model(input_tensor, avgout)
avgout.summary()

我想要的是“ avgout”层,请给我输出层的平均输出。结果:

ValueError                                Traceback (most recent call last)
<ipython-input-7-9d5576113651> in <module>
      6 input_tensor = layers.Input(shape=(784,))
      7 output = layers.Dense(10,)(input_tensor)
----> 8 average = layers.Average()(output)
      9 avgout = Model(input_tensor, avgout)
     10 avgout.summary()

~/anaconda3/lib/python3.7/site-packages/keras/engine/base_layer.py in __call__(self, inputs, **kwargs)
    429                                          'You can build it manually via: '
    430                                          '`layer.build(batch_input_shape)`')
--> 431                 self.build(unpack_singleton(input_shapes))
    432                 self.built = True
    433 

~/anaconda3/lib/python3.7/site-packages/keras/layers/merge.py in build(self, input_shape)
     66         # Used purely for shape validation.
     67         if not isinstance(input_shape, list):
---> 68             raise ValueError('A merge layer should be called '
     69                              'on a list of inputs.')
     70         if len(input_shape) < 2:

ValueError: A merge layer should be called on a list of inputs.

1 个答案:

答案 0 :(得分:0)

Keras计算机中的“平均”层是多个张量的平均值,而不是一个张量的平均值。

您可以使用keras后端的意思是:

from keras import backend as K
from keras.models import  Model
from keras import layers
from keras import Input
from keras.utils import plot_model

def mean(input):
    return K.mean(input, axis=1)

input_tensor = layers.Input(shape=(784,))
output = layers.Dense(10,)(input_tensor)
average = layers.Lambda(mean, input_shape=(10,))(output)
avgout = Model(input_tensor, average)
avgout.summary()