Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TensorFlow unstack with numpy

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?


2 Answers

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_))
like image 63
rvinas Avatar answered May 24 '26 08:05

rvinas


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))
like image 27
Phoenix Avatar answered May 24 '26 09:05

Phoenix



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!