Reshaping function in numpy
I am trying to reshape data for image classification purpose. I want to convert shape (32,32,3) to (1,3,32,32). I have used two ways for the reshaping purpose and got different results. The first one is numpy reshape method. The other code is written by me.
def res(t):
    n = np.zeros((3,32,32))

    for j in range(3):
        for k in range(32):
            for l in range(32):
                n[j][k][l]=t[k][l][j]

    n=n.reshape(1,3,32,32)
    return n

I am not able to understand what is the difference between both approaches.

This is what you want to do with np.reshape after transpose -
new = original.transpose(2,0,1).reshape(1,3,32,32)
#(32,32,3)-&gt;(3,32,32)-&gt;(1,3,32,32)

##OR##

new = original.transpose(2,0,1)[None,...]
#(32,32,3)-&gt;(3,32,32)-&gt;(1,3,32,32)


Full code with a comparison of results between your function and the transpose method.
t = np.random.random((32,32,3))

def res(t):
    n = np.zeros((3,32,32))

    for j in range(3):
        for k in range(32):
            for l in range(32):
                n[j,k,l]=t[k,l,j]  #&lt;--- fixed indexing

    n=n.reshape(1,3,32,32)
    return n

## METHOD Transpose and Reshape
np.allclose(t.transpose(2,0,1).reshape(1,3,32,32), res(t))
#True

## METHOD Transpose and new axis
np.allclose(t.transpose(2,0,1)[None,...], res(t))
#True

