函数作用:将嵌套结构压平,返回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()的区别。