Tensorflow: Slicing a Tensor into overlapping blocks

前端 未结 6 1481
我在风中等你
我在风中等你 2021-01-02 06:26

I have a 1D tensor that I wish to partition into overlapping blocks. I\'m thinking of something like: tensor = tf.constant([1, 2, 3, 4, 5, 6, 7])



        
6条回答
  •  青春惊慌失措
    2021-01-02 07:09

    I am not sure whether this question has been sufficiently answered, but you can use a python generator function to create overlapping windows:

    def gen_batch():
    
    # compute number of batches to emit
    num_of_batches = round(((len(sequence) - batch_size) / stride))
    
    # emit batches
    for i in range(0, num_of_batches * stride, stride):
        result = np.array(sequence[i:i + batch_size])
        yield result
    
    sequence = np.array[1,2,3,4,5,6,7,8,9]
    batch_size = 3
    stride = 2
    gen = gen_batch()
    
    print(next(gen))
    [1,2,3]
    print(next(gen))
    [3,4,5]
    ...
    print(next(gen))
    [7,8,9]
    

    Once you have defined your generator function, you can use TensorFlow's Dataset class to call each slice:

    ds = tf.data.Dataset.from_generator(
    gen_batch,
    (tf.float64),
    (tf.TensorShape([batch_size, dim_width])))
    
    ds_out = ds.make_one_shot_iterator().get_next()
    
    print(sess.run(ds_out)))
    [1,2,3]
    print(sess.run(ds_out)))
    [3,4,5]
    ...
    print(sess.run(ds_out)))
    [7,8,9]
    

提交回复
热议问题