本文介绍了Tensorflow:使用 tf.slice 分割输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将我的输入层分成不同大小的部分.我正在尝试使用 tf.slice 来做到这一点,但它不起作用.

I'm trying to split my input layer into different sized parts. I'm trying to use tf.slice to do that but it's not working.

一些示例代码:

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

This works and is roughly what I want to happen, but I have to specify the first dimension (3 in this case). I can't know though how many vectors I'll be inputting, that's why I'm using a placeholder with None in the first place!

是否可以以这样一种方式使用 slice,以便在运行时之前未知维度时它也能工作?

Is it possible to use slice in such a way that it will work when a dimension is unknown until runtime?

我曾尝试使用 placeholderph.get_shape()[0] 获取其值,如下所示:x = tf.slice(ph, [0, 0], [num_input, 2]).但这也不起作用.

I've tried using a placeholder that takes its value from ph.get_shape()[0] like so: x = tf.slice(ph, [0, 0], [num_input, 2]). but that didn't work either.

推荐答案

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

You can specify one negative dimension in the size parameter of tf.slice. The negative dimension tells Tensorflow to dynamically determine the right value basing its decision on the other dimensions.

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_}))

这篇关于Tensorflow:使用 tf.slice 分割输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 21:32