3

I am porting code from tensorflow to numpy and i have trouble with this line of code:

tensor_unstack = tf.unstack(some_tensor, axis=0)

The tf.unstack method is used and i was unable to find a equivalent in numpy. So my question is how would a tf.unstack be implemented when using numpy?

Felix Quehl
  • 744
  • 1
  • 9
  • 24

2 Answers2

4

The star operator can be used to unstack a numpy array. Here is an example:

import tensorflow as tf
import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])
c = np.stack([a, b])
*d, = c
print(d)

c_ = tf.stack([a, b])
d_ = tf.unstack(c_)

with tf.Session() as sess:
    print(sess.run(d_))
rvinas
  • 11,824
  • 36
  • 58
1

The answer above does not allow one to specify the split axis or the number of splits one wants to make.

Thankfully, a better solution is provided by inbuilt numpy functions. Look into numpy.split and its specialized versions numpy.hsplit, numpy.vsplit, numpy.dsplit and numpy.array_split.

import numpy
a = numpy.arange(9).reshape(3,3)

# makes 3 equal splits along axis 0. equivalent to numpy.vsplit
print(numpy.split(a, 3, axis=0))

# 3 equal splits along axis 1. equivalent to numpy.hsplit
print(numpy.split(a, 3, axis=1))
Phoenix
  • 348
  • 4
  • 15
  • this, however, will preserve the "unstacked" dimension: if `x.shape: (4, 2, 3)`, then `x1, x2 = np.hsplit(x,2)` will yield `x1.shape: (4, 1, 3)`. The unstacked dimension can be removed with `squeeze`: `x1, x2 = [ xx.squeeze() for xx in np.hsplit(x,2)]`, now `x1.shape: (4, 3)` – kingusiu Sep 23 '20 at 14:57