Tensorflow:使用 tf.slice 分割输入

新手上路,请多包涵

我试图将我的输入层分成不同大小的部分。我正在尝试使用 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]) 。但这也没有用。

原文由 Nimitz14 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 465
2 个回答

您可以在 --- 的 tf.slice size 参数中指定一个负维度。负维度告诉 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_}))

原文由 nessuno 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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 参数表示您想要在该维度上有多少个元素。

原文由 r0n9 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题