tensorflow 中 numpy.newaxis 的替代方案是什么?

What is the alternative of numpy.newaxis in tensorflow?

嗨,我是张量流的新手。我想在 tensorflow 中实现以下 python 代码。

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)

我想应该是 tf.expand_dims -

tf.expand_dims(a, 1) # Or tf.expand_dims(a, -1)

基本上,我们列出要插入此新轴的轴 ID,尾部 axes/dims 是 pushed-back.

从链接的文档中,这里有几个扩展维度的例子 -

# 't' is a tensor of shape [2]
shape(expand_dims(t, 0)) ==> [1, 2]
shape(expand_dims(t, 1)) ==> [2, 1]
shape(expand_dims(t, -1)) ==> [2, 1]

# 't2' is a tensor of shape [2, 3, 5]
shape(expand_dims(t2, 0)) ==> [1, 2, 3, 5]
shape(expand_dims(t2, 2)) ==> [2, 3, 1, 5]
shape(expand_dims(t2, 3)) ==> [2, 3, 5, 1]

对应的命令是tf.newaxis(或者None,在numpy中)。它在 tensorflow 的文档中没有单独的条目,但在 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)

使用 tf.expand_dims 也可以,但是,如上文 link 所述,

Those interfaces are much more friendly, and highly recommended.

如果您对与 NumPy 中完全相同的类型(即 None)感兴趣,那么 tf.newaxisnp.newaxis 的完全替代。

示例:

In [71]: a1 = tf.constant([2,2], name="a1")

In [72]: a1
Out[72]: <tf.Tensor 'a1_5:0' shape=(2,) dtype=int32>

# add a new dimension
In [73]: a1_new = a1[tf.newaxis, :]

In [74]: a1_new
Out[74]: <tf.Tensor 'strided_slice_5:0' shape=(1, 2) dtype=int32>

# add one more dimension
In [75]: a1_new = a1[tf.newaxis, :, tf.newaxis]

In [76]: a1_new
Out[76]: <tf.Tensor 'strided_slice_6:0' shape=(1, 2, 1) dtype=int32>

这与您在 NumPy 中执行的操作完全相同。只需在您希望增加的同一维度上使用它即可。

考虑 tf.keras.layers.Reshape:

# as first layer in a Sequential model
model = Sequential()
model.add(Reshape((3, 4), input_shape=(12,)))
# now: model.output_shape == (None, 3, 4)
# note: `None` is the batch dimension

# as intermediate layer in a Sequential model
model.add(Reshape((6, 2)))
# now: model.output_shape == (None, 6, 2)

# also supports shape inference using `-1` as dimension
model.add(Reshape((-1, 2, 2)))
# now: model.output_shape == (None, 3, 2, 2)
a = a[..., tf.newaxis].astype("float32")

这也行