2017-05-25 144 views
5

我正在使用tensorflow后端。平铺层如何在keras中工作?

依次应用卷积,最大池化,平坦化和密集层。卷积需要3D输入(高度,宽度,color_channels_depth)。

卷积后,这成为(高度,宽度,Number_of_filters)。

应用最大池高度后,宽度发生变化。但是在应用平坦层之后究竟发生了什么?例如。

如果在拼合之前的输入是(24,24,32),那么它如何将它弄平?

它是顺序像(24 * 24)的高度,每个过滤器编号的顺序或以其他方式的权重?一个例子将赞赏与实际值。

回答

12

Flatten()运营商将展开在最后一个维度开始值(至少Theano,这是“渠道至上”,而不是“渠道最后”像TF,我不能在我的环境中运行TensorFlow)。这等同于numpy.reshape与“C”顺序:

“C”手段读/使用C-像索引顺序写入的元素,与 最后轴指数变化最快,回第一轴索引 变化最慢。

这里是一个独立的例子,说明具有Keras Functional API的Flatten操作符。您应该能够轻松适应您的环境。

import numpy as np 
from keras.layers import Input, Flatten 
from keras.models import Model 
inputs = Input(shape=(3,2,4)) 

# Define a model consisting only of the Flatten operation 
prediction = Flatten()(inputs) 
model = Model(inputs=inputs, outputs=prediction) 

X = np.arange(0,24).reshape(1,3,2,4) 
print(X) 
#[[[[ 0 1 2 3] 
# [ 4 5 6 7]] 
# 
# [[ 8 9 10 11] 
# [12 13 14 15]] 
# 
# [[16 17 18 19] 
# [20 21 22 23]]]] 
model.predict(X) 
#array([[ 0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10., 
#   11., 12., 13., 14., 15., 16., 17., 18., 19., 20., 21., 
#   22., 23.]], dtype=float32) 
+0

这是关于Flatten如何工作的一个非常简洁的答案。 – nafizh

1

它是像24 * 24 * 32这样的顺序,并重塑它,如下面的代码所示。

def batch_flatten(x): 
    """Turn a nD tensor into a 2D tensor with same 0th dimension. 
    In other words, it flattens each data samples of a batch. 
    # Arguments 
     x: A tensor or variable. 
    # Returns 
     A tensor. 
    """ 
    x = tf.reshape(x, tf.stack([-1, prod(shape(x)[1:])])) 
    return x