函数定义
@tf_export('layers.flatten')
def flatten(inputs, name=None):
"""Flattens an input tensor while preserving the batch axis (axis 0).
保留axis(axis0)的同时平移输入张量,即把一个输入大小为n*h*w的Tensor变成n*(hw),相当于reshape特殊操作
Arguments:
inputs: Tensor input.
name: The name of the layer (string).
Returns:
Reshaped tensor.
Examples:
```
x = tf.placeholder(shape=(None, 4, 4), dtype='float32')
y = flatten(x)
# now `y` has shape `(None, 16)`
x = tf.placeholder(shape=(None, 3, None), dtype='float32')
y = flatten(x)
# now `y` has shape `(None, None)`
```
"""
layer = Flatten(name=name)
return layer.apply(inputs)
注意事项:
1、axis 和dim同样作用,不能同时设置,否则会报错:ValueError: if both `dim` and `axis` are specified.
2、axis/dim的取值: `[-rank(input) - 1, rank(input)]`.
假设input Tensor shape = [ 2,3,4,5], 则axis/dim取值范围为[-4, 3], 对应关系如下上下对应):
axis/dim = -4 -3 -2 -1
axis/dim = 0 1 2 3
3、axis和dim不能同时设为None,否则报错:ValueError: Tried to convert 'dim' to a tensor and failed. Error: None values not supported.
4、调用该函数时,请确保inputs是Tensor类型,如下错误示范:
inputs = [1, 2, 2, 1]
inputs=np.random.random(inputs).astype(np.float32)
print(type(inputs))
a = tf.layers.flatten(inputs=inputs)
with tf.Session() as sess:
sess.run(a)
print(sess.run(a))
print(a)
==============================================================
# 部分bug trace截取
File "D:\Program Files\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1463, in _assert_input_compatibility
if x.shape.ndims is None:
AttributeError: 'tuple' object has no attribute 'ndims'
正确做法:将inputs转换成tensor在调用函数: inputs = tf.convert_to_tensor(inputs)