函数作用:将嵌套结构压平,返回Python的list。

例子一,嵌套列表:

from tensorflow.python.util import nest

input = [['a', 'b', 'c'],
        ['d', 'e', 'f'],
        ['1', '2', '3']]

result = nest.flatten(input)

Out:
<class 'list'>: ['a', 'b', 'c', 'd', 'e', 'f', '1', '2', '3']

例子二,字典类型:

input = {'a': 1, 'b': 2, 'c': {'p': 3, 'q': 4}}

result = nest.flatten(input)

Out:
<class 'list'>: [1, 2, 3, 4]

注意:
1)Tensor对象、和NumPy的ndarray对象,都看做是一个元素,不会被压平。

input = {'a': np.ones(shape=(2, 3)), 'b': np.zeros(shape=(3, 2))}

result = nest.flatten(input)

Out:
<class 'list'> [ndarray, ndarray]

2)如果输入不是嵌套结构,只有一个元素的话,则返回仅包含这一个元素的list。

from tensorflow.python.util import nest

x = tf.constant([[1,2],[3,4]])
y = nest.flatten(x)

type(y) # list
len(y) # 1
y[0] # <tf.Tensor 'Const_4:0' shape=(2, 2) dtype=int32>

3)注意和tf.contrib.layers.flatten()的区别。

GitHub 加速计划 / te / tensorflow
184.54 K
74.12 K
下载
一个面向所有人的开源机器学习框架
最近提交(Master分支:26 天前 )
a49e66f2 PiperOrigin-RevId: 663726708 1 个月前
91dac11a This test overrides disabled_backends, dropping the default value in the process. PiperOrigin-RevId: 663711155 1 个月前
Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐