Tensorflow: Using tf.slice to split the input

后端 未结 3 1345
梦毁少年i
梦毁少年i 2021-02-20 03:22

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 te         


        
相关标签:
3条回答
  • 2021-02-20 04:10

    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.

    0 讨论(0)
  • 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_}))
    
    0 讨论(0)
  • 2021-02-20 04:16

    For me, I tried another example to let me understand the slice 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 begin indicates which element you are going to start to cut. The size parameter means how many element you want on that dimension.

    0 讨论(0)
提交回复
热议问题