TensorFlow 1.4以后,引入了新的tf.data.Dataset,这是个非常好用的模块,具体可以参考以下URL:
https://blog.csdn.net/kwame211/article/details/78579035
看代码的时候,一直有个疑问,就是关于类似tf.data.Dataset.map()的这种函数参数,很不容易理解。
定义:
map(
map_func,
num_parallel_calls=None
)
1,这种属于稍微可以理解的,参数是一个lambda函数,其中x是a的内容。
# NOTE: The following examples use `{ ... }` to represent the
# contents of a dataset.
a = { 1, 2, 3, 4, 5 }
a.map(lambda x: x + 1) = { 2, 3, 4, 5, 6 }
2,这种写法,一度令我非常困惑,函数fun定义了一个参数x,但是x没有任何地方赋值。
参考1的写法,倒是能明白意思。
官方的说明是这样的:
This transformation applies map_func
to each element of this dataset, and returns a new dataset containing the transformed elements, in the same order as they appeared in the input.
import tensorflow as tf
def fun(x):
return x +1
ds = tf.data.Dataset.range(5)
ds = ds.map(fun)
简单的可以理解为,map的参数是一个函数,而这个函数的参数是固定的。就是和你的dataset的内容是完全一致的。
上例中函数fun的参数x是固定的,虽然在很多语言里,这不太容易理解,不过可以理解为python的特性吧。
假如,想对fun的参数x进行自定义,比如要另加一个参数y, 也可以实现。就是用lambda和函数配合使用。
def fun(x, y):
return x + y
y = tf.constant(2, dtype=tf.int64)
ds = tf.data.Dataset.range(5)
ds = ds.map(lambda x: fun(x, y))