tf.layers.flatten()使用

函数定义

@tf_export('layers.flatten')
def flatten(inputs, name=None):
  """Flattens an input tensor while preserving the batch axis (axis 0).
保留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)

==============================================================
<class 'numpy.ndarray'>

# 部分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)

  • 13
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值