tensorflow - 在 tensorflow 中拆分张量

标签 tensorflow

我想把张量分成两部分:

ipdb> mean_log_std
<tf.Tensor 'pi/add_5:0' shape=(?, 2) dtype=float32>

上下文:?是样本数,另一个维度是 2。我想沿着第二个维度分成两个形状为 1 的 tensorflow 。

我尝试了什么?( https://www.tensorflow.org/api_docs/python/tf/slice )

ipdb> tf.slice(mean_log_std,[0,2],[0,1])
<tf.Tensor 'pi/Slice_6:0' shape=(0, 1) dtype=float32>
ipdb> tf.slice(mean_log_std,[0,1],[0,1])
<tf.Tensor 'pi/Slice_7:0' shape=(0, 1) dtype=float32>
ipdb>

我希望上述两个拆分的形状为 (?,1) 和 (?,1)。

最佳答案

你可以切片第二维的张量:

x[:,0:1], x[:,1:2]

或者在第二个轴上分割:

y, z = tf.split(x, 2, axis=1)

示例:

import tensorflow as tf

x = tf.placeholder(tf.int32, shape=[None, 2])

y, z = x[:,0:1], x[:,1:2]

y
#<tf.Tensor 'strided_slice_2:0' shape=(?, 1) dtype=int32>

z
#<tf.Tensor 'strided_slice_3:0' shape=(?, 1) dtype=int32>

with tf.Session() as sess:
    print(sess.run(y, {x: [[1,2],[3,4]]}))
    print(sess.run(z, {x: [[1,2],[3,4]]}))
#[[1]
# [3]]
#[[2]
# [4]]

有拆分:

y, z = tf.split(x, 2, axis=1)

with tf.Session() as sess:
    print(sess.run(y, {x: [[1,2],[3,4]]}))
    print(sess.run(z, {x: [[1,2],[3,4]]}))
#[[1]
# [3]]
#[[2]
# [4]]

关于tensorflow - 在 tensorflow 中拆分张量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47128715/

相关文章:

python - tensorflow 模型精度没有增加

python - 如何在 Tensorflow 上使用线性回归模型和我自己的数据

python - 尝试使用 conda 命令安装 tensorflow-gpu 时,当前 linux-64 channel 中缺少依赖项

python - 为什么要在神经网络中添加零偏差?

python - Tensorflow,多处理中的更新权重

python - TensorFlow - tf.layers 与 tf.contrib.layers

python - 如何在Google colab中更改Keras/tensorflow版本?

python-3.x - Keras Tuner get_best_hyperparameters()

tensorflow - 为什么与 rsync 一起使用时 Tensorboard 不刷新?

python - 如何用max代替tensorflow softmax来在神经网络的输出层生成一个热向量?