Skip to content

Movement

Movement ops change the shape of a tensor or the order of its elements, never their values.

Movement¤

reshape ¤

reshape(*shape)

Same data in a new shape; one dim may be -1.

Source code in stackgrad/tensor.py
269
270
271
def reshape(self, *shape):
  """Same data in a new shape; one dim may be -1."""
  return _apply(mlops.Reshape, self, shape=_shape(shape))

permute ¤

permute(*order)
Source code in stackgrad/tensor.py
273
274
def permute(self, *order):
  return _apply(mlops.Permute, self, order=tuple(d % self.ndim for d in _shape(order)))

transpose ¤

transpose(dim0=-2, dim1=-1)

Swap two axes, the last two by default.

Source code in stackgrad/tensor.py
276
277
278
279
280
def transpose(self, dim0=-2, dim1=-1):
  """Swap two axes, the last two by default."""
  order = list(range(self.ndim))
  order[dim0], order[dim1] = order[dim1], order[dim0]
  return self.permute(order)

expand ¤

expand(*shape)

Broadcast to shape, adding leading dims if needed.

Source code in stackgrad/tensor.py
282
283
284
285
286
def expand(self, *shape):
  """Broadcast to `shape`, adding leading dims if needed."""
  shape = _shape(shape)
  x = self.reshape((1,) * (len(shape) - self.ndim) + self.shape) if self.ndim < len(shape) else self
  return _apply(mlops.Expand, x, shape=shape)

squeeze ¤

squeeze(axis=None)
Source code in stackgrad/tensor.py
288
289
290
def squeeze(self, axis=None):
  axes = range(self.ndim) if axis is None else [a % self.ndim for a in np.atleast_1d(axis)]
  return self.reshape(tuple(d for i, d in enumerate(self.shape) if not (i in axes and d == 1)))

unsqueeze ¤

unsqueeze(axis)
Source code in stackgrad/tensor.py
292
293
294
def unsqueeze(self, axis):
  axis = axis if axis >= 0 else self.ndim + axis + 1
  return self.reshape(self.shape[:axis] + (1,) + self.shape[axis:])

im2col ¤

im2col(kh, kw, stride=1, padding=0)

(N, C, H, W) -> (NOHOW, Ckhkw) patch rows, the input to a conv-as-matmul.

Source code in stackgrad/tensor.py
305
306
307
def im2col(self, kh, kw, stride=1, padding=0):
  """(N, C, H, W) -> (N*OH*OW, C*kh*kw) patch rows, the input to a conv-as-matmul."""
  return _apply(mlops.Im2col, self, kh=kh, kw=kw, stride=stride, padding=padding)

Combining¤

cat ¤

cat(tensors, axis=0)

Concatenate tensors along an existing axis.

Source code in stackgrad/tensor.py
416
417
418
def cat(tensors, axis=0):
  """Concatenate tensors along an existing axis."""
  return _apply(mlops.Cat, *tensors, axis=axis)

stack ¤

stack(tensors, axis=0)

Stack tensors along a new axis.

Source code in stackgrad/tensor.py
421
422
423
def stack(tensors, axis=0):
  """Stack tensors along a new axis."""
  return cat([t.unsqueeze(axis) for t in tensors], axis=axis)