【问题标题】:Tensorflow: Using tf.slice to split the inputTensorflow:使用 tf.slice 分割输入
【发布时间】:2016-08-20 12:57:00
【问题描述】:

我正在尝试将输入层拆分为不同大小的部分。我正在尝试使用 tf.slice 来执行此操作,但它不起作用。

一些示例代码:

import tensorflow as tf
import numpy as np

ph = tf.placeholder(shape=[None,3], dtype=tf.int32)

x = tf.slice(ph, [0, 0], [3, 2])

input_ = np.array([[1,2,3],
                   [3,4,5],
                   [5,6,7]])

with tf.Session() as sess:
        sess.run(tf.initialize_all_variables())
        print sess.run(x, feed_dict={ph: input_})

输出:

[[1 2]
 [3 4]
 [5 6]]

这行得通并且大致是我想要发生的,但我必须指定第一个维度(在这种情况下为3)。我不知道我将输入多少个向量,这就是为什么我首先使用placeholderNone

是否可以使用slice 使其在直到运行时才知道维度未知的情况下工作?

我尝试使用placeholder,它的值来自ph.get_shape()[0],如下所示:x = tf.slice(ph, [0, 0], [num_input, 2])。但这也没有用。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    您可以在tf.slicesize 参数中指定一个负维度。负维度告诉 Tensorflow 根据其他维度动态确定正确的值。

    import tensorflow as tf
    import numpy as np
    
    ph = tf.placeholder(shape=[None,3], dtype=tf.int32)
    
    # look the -1 in the first position
    x = tf.slice(ph, [0, 0], [-1, 2])
    
    input_ = np.array([[1,2,3],
                       [3,4,5],
                       [5,6,7]])
    
    with tf.Session() as sess:
            sess.run(tf.initialize_all_variables())
            print(sess.run(x, feed_dict={ph: input_}))
    

    【讨论】:

    • 不错。谢谢!奇怪的是他们使用了不一致的符号(None 表示占位符,而否定表示)。
    • @nessuno print 末尾缺少括号,无法添加修复,因为 stackoverflow 需要至少 6 个字符才能更新。
    【解决方案2】:

    对我来说,我尝试了另一个例子来让我理解切片函数

    input = [
        [[11, 12, 13], [14, 15, 16]],
        [[21, 22, 23], [24, 25, 26]],
        [[31, 32, 33], [34, 35, 36]],
        [[41, 42, 43], [44, 45, 46]],
        [[51, 52, 53], [54, 55, 56]],
        ]
    s1 = tf.slice(input, [1, 0, 0], [1, 1, 3])
    s2 = tf.slice(input, [2, 0, 0], [3, 1, 2])
    s3 = tf.slice(input, [0, 0, 1], [4, 1, 1])
    s4 = tf.slice(input, [0, 0, 1], [1, 0, 1])
    s5 = tf.slice(input, [2, 0, 2], [-1, -1, -1]) # negative value means the function cutting tersors automatically
    tf.global_variables_initializer()
    with tf.Session() as s:
        print s.run(s1)
        print s.run(s2)
        print s.run(s3)
        print s.run(s4)
    

    它输出:

    [[[21 22 23]]]
    
    [[[31 32]]
     [[41 42]]
     [[51 52]]]
    
    [[[12]]
     [[22]]
     [[32]]
     [[42]]]
    
    []
    
    [[[33]
      [36]]
     [[43]
      [46]]
     [[53]
      [56]]]
    

    参数 begin 指示您要开始剪切的元素。 size 参数表示在该维度上需要多少元素。

    【讨论】:

      【解决方案3】:

      你也可以试试这个

      x = tf.slice(ph, [0,0], [3, 2])

      你的起点是(0,0),第二个参数是[0,0]。 你想切片三个原始和两列,所以你的第三个参数是[3,2]

      这将为您提供所需的输出。

      【讨论】:

        猜你喜欢
        • 2020-06-14
        • 2016-07-23
        • 2018-11-19
        • 1970-01-01
        • 2020-10-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多