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

新手上路,请多包涵

嗨,我是张量流的新手。我想在 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)

原文由 Rahul 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 574
2 个回答

我认为那将是 tf.expand_dims -

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

基本上,我们列出了要插入这个新轴的轴 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]

原文由 Divakar 发布,翻译遵循 CC BY-SA 3.0 许可协议

相应的命令是 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 也可以,但是,如上面的链接所述,

这些界面更加友好,强烈推荐。

原文由 P-Gn 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题