0

I have a four-dimensional data in array trainAll of shape N × H × W × 3. I need to separate it so I did

X_train = trainAll[:,:,:,1]
Y_train = trainAll[:,:,:,1:3]

As expected, Y_train.shape was N × H × W × 2.

But X_train.shape is N × H × W because the last dimension has just size 1. But neural network need four dimensional array, so it should look like

N × H × W × 1

The amazing thing is, if I do trainAll[:,:,:,2:3] then I get N*H*W*1 but I want the first dimension separated, not the last.

Honestly, I was unable to google because I did not know what to ask. So can any one help me out, so that I can not only separate first dimension but also shape is N × H × W × 1 instead of N × H × W ?

2
  • these are numpy arrays as I printed out them as aray.shape Commented Mar 26, 2017 at 10:42
  • 1
    my bad, I was doing this trainAll[:,:,:,1] instead of trainAll[:,:,:,0] but I have found a solution by trainAll[:,:,:,0:1] Commented Mar 26, 2017 at 10:54

3 Answers 3

1

Just try to add a new axis as the desired dimension. (Here, as the fourth dimension).

X_train = trainAll[:, :, :, 0]
X_train = X_train[:, :, :, np.newaxis]
# now, X_train.shape will be N * H * W * 1

The reason why you don't get them at the first place when you slice them is because slice hands the result as (n,) when using a single index and you make it (n, 1) by adding a new axis.

Sign up to request clarification or add additional context in comments.

1 Comment

Even though I was able to do it in single line but I accepted answer for "because slice hands the result as (n,)"
1

I was able to figure it out but still do not know if my answer is right. I wanted to know the python way to do it and What is happening when shape is shifted to N*H*W instead of N*H*W*1

Solution: trainAll[:,:,:,0:1] so instead of trainAll[:,:,:,1] picking it up just slice it

5 Comments

That's why I would have suggested, too. Alternatively, you could use numpy.reshape.
Or else, X_train = trainAll[:, :, :, 0]
@kmario23 the problem with your solution is arr.shape become N*H*W while I need it as N*H*W*1. which I did by slicing array
@kmario23 and I do not know and want to know why output shape changes to N*h*w instead of N*h*w*1
Sorry, I missed a bit of the solution. the correct one is X_train = trainAll[:, :, :, 0]; X_train = X_train[:, :, :, np.newaxis]
0

I have found following and it works much better: tf.expand_dims tensorflow docs, to reduce dimension instead use: tf.squeeze() here tf refers to tensorflow

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.