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
它像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
3 回答
Flatten()
运算符展开从最后一个维度开始的值(至少对于Theano来说是"channels first",而不是像TF这样的"channels last" . 我无法在我的环境中运行TensorFlow) . 这相当于numpy.reshape
与'C'排序:这是一个独立的示例,用于说明使用Keras Functional API的
Flatten
运算符 . 您应该能够轻松适应您的环境 .它像24 * 24 * 32一样顺序并重新整形,如下面的代码所示 .
压平张量意味着除去一个尺寸以外的所有尺寸 .
Keras中的Flatten层将张量整形为具有与张量中包含的元素数量相等的形状 .
这与制作1d元素数组是一回事 .
例如,在VGG16模型中,您可能会发现它很容易理解:
注意flatten_1层的形状是如何(None,8192),其中8192实际上是4 * 4 * 512 .
PS,无意味着任何维度,但您通常可以将其读作1.您可以在here中找到更多详细信息 .