W 2 A1 | Exercise 2 : X_flatten = X.reshape(X.shape[0], -1).T?

I understand what the matrix.T and X.shape[0] do, but how is the parameter “-1” interpreted here? What other parameters can be here instead of “-1”.

In the optional practice assignment- “Python_Basics_with_Numpy”, Exercise 5 it is mentioned: “You can use v = v.reshape(-1, 1). Just make sure you understand why it works.” There we were reshaping a 3 dimensional (num_px, num_px, 3) matrix into a (num_px * num_px * 3, 1) column vector. There “-1” was the first parameter in the .reshape() method.

Is this “trick” specific to Numpy?

Can I get a link to the documentation where this “trick” is explained? I hate to just memorize stuff without understanding how it works.

If I type in X_flatten = X.reshape((X.shape[0], X.shape[1] * X.shape[2]*X.shape[2])).T , where X stands for “train_set_x_orig”, the AutoGrader returned correct result as well.


Yes, you can explicitly compute the other dimensions as you show in the last paragraph. All the -1 means there is: “use whatever dimensions are left here”. It’s just a shortcut that saves you the work of actually computing the product of the other remaining dimensions. Did you try actually reading the documentation for numpy reshape? Hint: google “numpy reshape”. This is explained there. But note that this is not some general python thing: it is very specific to reshape. As one other example, when you use -1 as an index in python, it means something completely different.


Got it. Thanks a lot!

1 Like

Thank you very much, was just about to ask the same question. Your explantion really makes it clear to me now.