问题
Look at the demo:
elems = np.array([1, 2, 3, 4, 5, 6])
squares = map_fn(lambda x: x * x, elems)
# squares == [1, 4, 9, 16, 25, 36]
elems = (np.array([1, 2, 3]), np.array([-1, 1, -1]))
alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64)
# alternate == [-1, 2, -3]
elems = np.array([1, 2, 3])
alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64))
# alternates[0] == [1, 2, 3]
# alternates[1] == [-1, -2, -3]
I can't understand the second and third.
For the second: I think the result is [2, -1], because the first time x=np.array([1, 2, 3]) and return 1*2, the second time x=np.array([-1, 1, -1]) and return 1*(-1)
For the third: I think the shape of result is (3,2), because the first time x=1 and return (1,-1), the second time x=2 and return (2,-2), the third time x=3 and return (3,-3).
So how does map_fn work?
回答1:
Tensorflow map_fn, from the docs,
map on the list of tensors unpacked from elems on dimension 0.
in this case, the only axis of the input tensor [1,2,3], or [-1,1,-1]. Operations are thus 1*-1,2*1 and 3*-1, and the results are repacked giving you the tensor shape.
回答2:
For the second: I think the result is [2, -1], because the first time x=np.array([1, 2, 3]) and return 1*2, the second time x=np.array([-1, 1, -1]) and return 1*(-1)
In [26]: a = np.array([[1, 2, 3], [2, 4, 1], [5, 1, 7]])
In [27]: b = np.array([[1, -1, -1], [1, 1, 1], [-1, 1, -1]])
In [28]: elems = (a, b)
In [29]: alternate = map_fn(lambda x: x[0] * x[1], elems, dtype=tf.int64)
In [30]: alternate.eval()
Out[30]:
array([[ 1, -2, -3],
[ 2, 4, 1],
[-5, 1, -7]])
You will see that it is the tensor in 0 dimension of each element in the elems that is applied to the function.
For the third: I think the shape of result is (3,2), because the first time x=1 and return (1,-1), the second time x=2 and return (2,-2), the third time x=3 and return (3,-3).
In [36]: elems = np.array([[1, 2, 3], [4, 5, 1], [1, 6, 1]])
In [37]: alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64))
In [38]: alternates
Out[38]:
(<tf.Tensor 'map_6/TensorArrayStack/TensorArrayGatherV3:0' shape=(3, 3) dtype=int64>,
<tf.Tensor 'map_6/TensorArrayStack_1/TensorArrayGatherV3:0' shape=(3, 3) dtype=int64>)
In [39]: alternates[0].eval()
Out[39]:
array([[1, 2, 3],
[4, 5, 1],
[1, 6, 1]])
In [40]: alternates[1].eval()
Out[40]:
array([[-1, -2, -3],
[-4, -5, -1],
[-1, -6, -1]])
To get the results you expected:
In [8]: elems = np.array([[1], [2], [3]])
In [9]: alternates = map_fn(lambda x: (x, -x), elems, dtype=(tf.int64, tf.int64))
In [10]: sess = tf.InteractiveSession()
In [11]: alternates[0].eval()
Out[11]:
array([[1],
[2],
[3]])
In [12]: alternates[1].eval()
Out[12]:
array([[-1],
[-2],
[-3]])
May this can help you in understanding the map_fn better.
来源:https://stackoverflow.com/questions/45905601/how-does-tf-map-fn-work