Tensorflow: using tf.slice to split input

I am trying to split my input layer into pieces of different sizes. I am trying to use tf.slice for this, but it does not work.

Code example:

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 roughly what I want, but I have to specify the first dimension ( 3 in this case). I don’t know how many vectors I will enter, so I use a placeholder with None in the first place!

Is it possible to use slice in such a way that it works when the measurement is unknown before runtime?

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

+5
source share
2 answers

You can specify one negative dimension in the size tf.slice parameter. A negative size tells Tensorflow to dynamically determine the correct value, basing its decision on 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_}) 
+7
source

For me, I tried another example to let me understand the cut function

 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) 

It outputs:

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

The parameter begins to indicate which element you are going to cut. The dimension parameter means how many elements you want in this dimension.

+2
source

All Articles