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?
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_))
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With