Hi I am new to tensorflow. I want to implement the following python code in tensorflow.
import numpy as np
a = np.array([1,2,3,4,5,6,7,9,0])
print(a) ## [1 2 3 4 5 6 7 9 0]
print(a.shape) ## (9,)
b = a[:, np.newaxis] ### want to write this in tensorflow.
print(b.shape) ## (9,1)
Simply put, numpy. newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus, 1D array will become 2D array.
NumPy and TensorFlow are actually very similar in many respects. Both are, essentially, array manipulation libraries, built around the concept of tensors (or nd-arrays, in NumPy terms).
TensorFlow implements a subset of the NumPy API, available as tf. experimental. numpy . This allows running NumPy code, accelerated by TensorFlow, while also allowing access to all of TensorFlow's APIs.
expand_dims() is used to insert an addition dimension in input Tensor. Parameters: input: It is the input Tensor. axis: It defines the index at which dimension should be inserted.
The corresponding command is tf.newaxis
(or None
, as in numpy). It does not have an entry on its own in tensorflow's documentation, but is briefly mentioned on the doc page of tf.stride_slice
.
x = tf.ones((10,10,10))
y = x[:, tf.newaxis] # or y = x [:, None]
print(y.shape)
# prints (10, 1, 10, 10)
Using tf.expand_dims
is fine too but, as stated in the link above,
Those interfaces are much more friendly, and highly recommended.
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