Qubix
Qubix

Reputation: 4353

Slice a tensor in half in tensorflow

I have a tensor of shape (32, 32, 32, 1) and I want to slice it into two tensors, along the first dimension, containing the first and second halves like so

half1  with shape = (16, 32, 32, 1)
half2  with shape = (16, 32, 32, 1)

I am trying to use tf.slice but I don't know how to use the begin and end indices, and the documentation is anything but clear.

Upvotes: 0

Views: 2088

Answers (2)

Ali
Ali

Reputation: 1635

Here is how you do it:

import tensorflow as tf
import numpy as np
t = t = tf.pack(np.random.randint(1,10,[32,32,32,1]))
half1 = tf.slice(t,[0,0,0,0],[16,32,32,1])
half2 = tf.slice(t,[16,0,0,0],[16,32,32,1])

[0,0,0,0] means start from the very first element in each dimension, [16,32,32,1] means size in first dimension is 16 and for the others 32, 32, 1. It basically means get the first half with regard to first dimension and for all other dimensions get all elements.

Upvotes: 2

Qubix
Qubix

Reputation: 4353

Turns out tensorflow does not require you to use tf.slice since you can simply use numpy slicing:

first_half = input[:16]
second_half = input[16:]

Upvotes: 5

Related Questions