Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tensorflow: Using tf.slice to split the input

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.

Some sample code:

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

Output:

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

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!

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

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.

like image 346
Nimitz14 Avatar asked Aug 20 '16 12:08

Nimitz14


2 Answers

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_}))
like image 79
nessuno Avatar answered Sep 20 '22 22:09

nessuno


You can also try out this one

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

As your starting point is (0,0) second argument is [0,0]. You want to slice three raw and two column so your third argument is [3,2].

This will give you desired output.

like image 26
USS Avatar answered Sep 20 '22 22:09

USS