tensorflow - 是否有任何解决方法可以沿着可变长度的维度取消堆叠张量?

标签 tensorflow machine-learning deep-learning reshape tensor

我需要循环长度可变的第一个维度,我该如何做到这一点?如果不可能有什么解决方法吗?

最佳答案

tf.unstack沿动态维度不支持:

If value.shape[axis] is not known, ValueError is raised.

但是你可以尝试使用tf.while_loop迭代张量切片。下面是计算总和的示例:

# Input tensor: trying to iterate along axis=0
x = tf.placeholder(dtype=tf.float32, shape=[None, 3])
batch_size = tf.shape(x)[0]

def cond(x, i, _):
  return i < batch_size

def body(x, i, x_prev):
  # Do some operation with `x_prev` and `x[i]`. Here we just add the slices
  sum = x_prev + x[i]
  return x, i + 1, sum

# This means: starting from 0, apply the body, while the `cond` is true
_, _, c = tf.while_loop(cond, body, (x, 0, tf.zeros([3])))

# Test it
with tf.Session() as sess:
  data = np.arange(12).reshape([4, 3])
  print(data)

  result = sess.run(c, feed_dict={x: data})
  print(result)

输出:

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]

[ 18.  22.  26.]

关于tensorflow - 是否有任何解决方法可以沿着可变长度的维度取消堆叠张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48208489/

相关文章:

python - 我正在处理一个银行数据集,我必须只使用 'experience in job' 列的整数部分

python-3.x - CelebA 数据集无法使用 tfds.load() 访问

python - Keras:ResourceExhaustedError(请参阅上面的回溯):分配具有形状的张量时出现 OOM [26671,32,32,64]

python-3.x - 训练多个 Keras NN 模型时出现段错误(核心转储)

python - Tensorflow 均方误差损失函数

machine-learning - 我想构建一个交互式机器学习系统,以使用尽可能多的现成软件对项目进行分类

authentication - 使机器学习算法适应我的问题

python - 输入和输出之间的相关熵

python - tensorflow.keras.preprocessing.text.Tokenizer.texts_to_sequences 的 Numpy 数组给出了奇怪的输出,list([2]) 而不是 [[2]]

android - TensorFlow-Lite 预训练模型在 Android 演示中不起作用