-1

Can anyone explain what this line is doing in python code ?

X.reshape((X.shape[0], 1) + X.shape[1:])

I am using numpy here.

Kanu
  • 91
  • 6

1 Answers1

2

Basically, this code is changing the shape of X to have an additional (size 1, or singleton if you are used to MATLAB) dimension. So if the shape was previously (3,3,3) it changes it to (3,1,3,3). This doesn't add any data since 3x3x3=3x1x3x3=27 It would probably be used so that the number of dimensions match (for functions that include another array). An equivalent form would be:

X = X[:, None, ...]

For more about why you might want to do this, see here

Community
  • 1
  • 1
Daniel F
  • 13,620
  • 2
  • 29
  • 55
  • I would rather call it `singleton` dim, borrowed from MATLAB. – Divakar May 19 '17 at 07:16
  • Empty would be something like `np.random.rand(3,0,2)`, etc., i.e. a dim of length `0` AFAI understand dims. Also, that `singleton` term used by one more author here - http://stackoverflow.com/a/3551859/3293881 – Divakar May 19 '17 at 07:18
  • Seems like the `numpy` docs mostly call it a "size 1 dimension" – Daniel F May 19 '17 at 07:25
  • There should be no spaces between the dots of the ellipsis (`...`) otherwise you may get a syntax error. – MB-F May 19 '17 at 07:44
  • @kazemakase That's true [only as of Python 3](https://docs.python.org/3/whatsnew/3.0.html#changed-syntax). – Arya McCarthy May 19 '17 at 07:59