gpt4 book ai didi

tensorflow - tf.map_fn 如何工作?

转载 作者:行者123 更新时间:2023-12-04 14:25:29 48 4
gpt4 key购买 nike

看演示:

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]

第二个和第三个看不懂

对于第二个:
我认为结果是 [2, -1],因为第一次 x=np.array([1, 2, 3]) 并返回 1*2,第二次 x=np.array([-1, 1 , -1]) 并返回 1*(-1)

对于第三个:
我认为结果的形状是 (3,2),因为第一次 x=1 并返回 (1,-1),第二次 x=2 并返回 (2,-2),第三次 x=3并返回 (3,-3)。

那么 map_fn 是如何工作的呢?

最佳答案

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]])

您将看到应用于该函数的是 elems 中每个元素的 0 维张量。

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]])

要获得您预期的结果:
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]])

可能这可以帮助您更好地理解 map_fn。

关于tensorflow - tf.map_fn 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45905601/

48 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com