Tensorflow:使用tf.slice分割inpu

2024-04-24 11:30:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图将输入层分成不同大小的部分。我试着用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)。我不知道我要输入多少向量,这就是为什么我首先使用带Noneplaceholder

使用slice的方式是否可以使它在维度未知时工作,直到运行时?

我试过使用从ph.get_shape()[0]获取其值的placeholder,就像这样:x = tf.slice(ph, [0, 0], [num_input, 2])。但那也没用。


Tags: run代码importnone示例inputtfas
3条回答

对我来说,我尝试了另一个例子来理解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参数表示需要在该维度上有多少元素。

可以在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_}))

你也可以试试这个

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

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

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

相关问题 更多 >