在 TensorFlow 中制作一个列表并附加到它 [英] Making a list and appending to it in TensorFlow
问题描述
我是 TensorFlow 的新手.我无法理解如何在 TensorFlow 中创建动态pythonic"列表.基本上,我对张量对象 (train_data[i]
) 执行一些计算并将其附加到列表"X
,我希望它成为形状为 <代码>(100,)
I am new to TensorFlow. I'm not able to understand how to create a dynamic "pythonic" list in TensorFlow. Basically, I perform some computation on a tensor object (train_data[i]
) and append it to a "list" X
, which I want to be a tensor with shape (100,)
我想做这样的事情:
X = []
for i in range(100):
q = tf.log(train_data[i])
print(q) #Tensor("Log:0", shape=(), dtype=float32)
X.append(q)
我希望 X
是一个形状为 (100,)
的张量,基本上是一个列向量,它是一个张量对象.如果我运行上面的代码,我会得到一个 TensorObjects 的 python 列表.
I want X
to be a Tensor with shape (100,)
, basically a column vector which is a tensor object. If I run the code above, I instead get a python list of TensorObjects.
推荐答案
如果要将 X
转换为 (100,) 张量,可以添加 X = tf.stack(X)
在 for 循环之后:
If you want to convert X
to a (100,) tensor you could add X = tf.stack(X)
after your for loop:
X = []
for i in range(100):
q = tf.log(train_data[i])
print(q) #Tensor("Log:0", shape=(), dtype=float32)
X.append(q)
X = tf.stack(X)
这是一个有用的构造,您可能希望 tf.unstack
一些张量,循环遍历结果列表,然后使用 tf.stack
返回一个单张量.
This is a useful construct where you may want to tf.unstack
some tensor, loop over the resulting list, and then use tf.stack
to get back to a single tensor.
这篇关于在 TensorFlow 中制作一个列表并附加到它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!