Trylks
Trylks

Reputation: 1498

Slicing a tensor with Keras

I have a 3D tensor. It is not an image, but for the sake of using the same conventions as Keras I will consider it an image, i.e. height x width x channels.

I have applied a 2D convolution to this tensor, and it is the input for a sequence of layers. However, I would like to keep the last channel separately, to concatenate it later on. Perhaps it is easier to see in code:

l = [64, 32, 16, 8]
inputs = Input(shape=(x,y,z))
we_are_here = Sequential([Conv2D(z, (x, y), padding='same') for _ in l])(inputs)
last_channel = SomethingSomething(we_are_here) # How do I do this?
long_path = Sequential(lots_of_layers)(we_are_here)
res = Concatenate([Flatten()(layer) for layer in [long_path, last_channel]]
outputs = Sequential([Dense(i) for i in l])(res)

I could not find a way to separate the last channel. There are several operations for slicing, splitting, cropping, etc. but none seems to help.

Upvotes: 0

Views: 465

Answers (1)

Steele Farnsworth
Steele Farnsworth

Reputation: 893

If you're familiar with list slicing in regular Python, array-like types support the same behavior, but generalized to additional dimensions. arr[:, :, -1] would get the last slice along the third dimension, and arr[:, :, :-1] would get all but that last slice.

Note that where arr.shape is (a, b, c), arr[:, :, -1] will return an array of shape (a, b). If the dimensionality needs to be preserved, arr[:, :, [-1]] will return an array of shape (a, b, 1). arr[:, :, :-1] will return an array of shape (a, b, c - 1).

Upvotes: 2

Related Questions