张量流中numpy.newaxis的替代方法是什么?

Rah*_*hul 11 python numpy python-3.x tensorflow tensor

嗨,我是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)
Run Code Online (Sandbox Code Playgroud)

Div*_*kar 10

我想那会是tf.expand_dims-

tf.expand_dims(a, 1) # Or tf.expand_dims(a, -1)
Run Code Online (Sandbox Code Playgroud)

基本上,我们列出了要插入此新轴的轴ID,并且后轴/调光被推回.

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

# '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]
Run Code Online (Sandbox Code Playgroud)


P-G*_*-Gn 9

相应的命令是tf.newaxis(或None,如numpy所示)。它在tensorflow的文档中没有单独的条目,但在的doc页面上已简要提及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)
Run Code Online (Sandbox Code Playgroud)

使用tf.expand_dims也可以,但正如上面的链接所述,

这些界面更加友好,强烈建议使用。