【问题标题】:Merge Variables in Keras在 Keras 中合并变量
【发布时间】:2016-09-27 18:16:22
【问题描述】:

我正在使用 Keras 构建卷积神经网络,并希望在最后一个全连接层之前添加一个带有我的数据标准差的单个节点。

这是重现错误的最少代码:

from keras.layers import merge, Input, Dense
from keras.layers import Convolution1D, Flatten
from keras import backend as K

input_img = Input(shape=(64, 4))

x = Convolution1D(48, 3, activation='relu', init='he_normal')(input_img)
x = Flatten()(x)

std = K.std(input_img, axis=1)
x = merge([x, std], mode='concat', concat_axis=1)

output =  Dense(100, activation='softmax', init='he_normal')(x)

这会产生以下TypeError

-----------------------------------------------------------------
TypeError                       Traceback (most recent call last)
<ipython-input-117-c1289ebe610e> in <module>()
      6 x = merge([x, std], mode='concat', concat_axis=1)
      7 
----> 8 output =  Dense(100, activation='softmax', init='he_normal')(x)

/home/ubuntu/anaconda2/envs/tensorflow/lib/python2.7/site-packages/keras/engine/topology.pyc in __call__(self, x, mask)
    486                                     '`layer.build(batch_input_shape)`')
    487             if len(input_shapes) == 1:
--> 488                 self.build(input_shapes[0])
    489             else:
    490                 self.build(input_shapes)

/home/ubuntu/anaconda2/envs/tensorflow/lib/python2.7/site-packages/keras/layers/core.pyc in build(self, input_shape)
    701 
    702         self.W = self.init((input_dim, self.output_dim),
--> 703                            name='{}_W'.format(self.name))
    704         if self.bias:
    705             self.b = K.zeros((self.output_dim,),

/home/ubuntu/anaconda2/envs/tensorflow/lib/python2.7/site-packages/keras/initializations.pyc in he_normal(shape, name, dim_ordering)
     64     '''
     65     fan_in, fan_out = get_fans(shape, dim_ordering=dim_ordering)
---> 66     s = np.sqrt(2. / fan_in)
     67     return normal(shape, s, name=name)
     68 

TypeError: unsupported operand type(s) for /: 'float' and 'NoneType'

知道为什么吗?

【问题讨论】:

  • 您使用的是哪个版本的 Keras?当我尝试运行您的代码时,我收到错误消息:'您试图调用层“dense_output”。该层没有关于其预期输入形状的信息,其中 'dense_output' 是最后一层,这是因为 K.std 没有像 keras 嵌入到其层中的输出形状信息。

标签: python tensorflow keras


【解决方案1】:

std 不是 Keras 层,因此它不满足层输入/输出形状接口。对此的解决方案是使用Lambda 层包裹K.std

from keras.layers import merge, Input, Dense, Lambda
from keras.layers import Convolution1D, Flatten
from keras import backend as K

input_img = Input(shape=(64, 4))

x = Convolution1D(48, 3, activation='relu', init='he_normal')(input_img)
x = Flatten()(x)

std = Lambda(lambda x: K.std(x, axis=1))(input_img)
x = merge([x, std], mode='concat', concat_axis=1)

output =  Dense(100, activation='softmax', init='he_normal')(x)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-26
    • 2015-01-22
    • 2011-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    相关资源
    最近更新 更多