Ran*_*uan 2 python deep-learning tensorflow
我的问题是关于Tensorflow中的张量运算。比方说:
import tensorflow as tf
import numpy as np
a = tf.Variable(np.random.random([10, 3, 3]))
b = tf.Variable(np.random.random([10, 3, 3]))
def some_function(m,n):
# just as an example
return tf.add(m, n)
Run Code Online (Sandbox Code Playgroud)
这在Tensorflow中有效,但需要高级了解尺寸。但是,张量的第一维很可能为无。
c = []
for i in range(10):
c.append(some_function(a[i], b[i]))
c = tf.stack(c)
Run Code Online (Sandbox Code Playgroud)
所以我想知道Tensorflow中是否有类似zip的功能?然后我们可以做:
# TypeError: zip argument #1 must support iteration
c = []
for i, j in zip(a,b):
c.append(some_function(i,j))
c = tf.stack(c)
Run Code Online (Sandbox Code Playgroud)
也许我们可以使用tf.map_fn或tf.scan之类的功能?但我不确定。真的谢谢你们
您可以使用tf.transpose这样的
>>> a = tf.constant([1, 2, 3])
>>> b = tf.constant([4, 5, 6])
>>> tf.transpose([a, b])
<tf.Tensor: shape=(3, 2), dtype=int32, numpy=
array([[1, 4],
[2, 5],
[3, 6]], dtype=int32)>
Run Code Online (Sandbox Code Playgroud)
小智 5
Tensor对象不可迭代,这说明了您的第三个代码示例失败的原因。因此,要回答您的问题,TensorFlow中没有类似zip的功能。
您确实可以使用tf.map_fn将函数应用于张量序列。您在示例代码中提出的问题可以通过以下方式解决:
def some_function(tensor):
return tf.reduce_sum(tensor)
c = tf.stack([a, b], axis=1)
d = tf.map_fn(some_function, c, dtype=tf.float32)
Run Code Online (Sandbox Code Playgroud)
产生一个张量,d其值为[20., 6., 6.]。