【问题标题】:Splitting tensors in tensorflow在张量流中拆分张量
【发布时间】:2018-04-18 03:07:34
【问题描述】:

我想把张量分成两部分:

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

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

我尝试了什么?(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)。

【问题讨论】:

    标签: tensorflow


    【解决方案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]]
    

    【讨论】:

    • 谢谢,我几分钟前就完成了。
    • 你能解释一下为什么是 x[:,0:1] 而不是 x[:,0]。
    • x[:,0:1] 对张量进行切片并保留原始尺寸,即 2,而 x[:,0] 从张量中提取单个列,从而将尺寸减少 1。
    • x[:,0:1] 切片张量并保持原始尺寸,即 2 :这救了我的命
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2017-11-05
    • 1970-01-01
    • 2018-07-31
    相关资源
    最近更新 更多