2017-02-20 52 views
8

嗨,我是tensorflow的新手。我想要在tensorflow中实现下面的python代码。在tensorflow中numpy.newaxis的替代方法是什么?

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) 

回答

8

我认为这是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] 
+0

谢谢。有效 – Rahul

2

相应的命令是tf.newaxis。它在tensorflow的文档中没有单独的条目,但在tf.stride_slice的文档页面中简要提及。

x = tf.ones((10,10,10)) 
y = x[:,tf.newaxis,...] 
print(y.shape) 
# prints (10, 1, 10, 10) 

使用tf.expand_dims是好的太多,但,正如上面的链接指出,

这些接口都更友好,强烈推荐。

0

如果你有兴趣在完全相同的类型(即。None),如与NumPy,然后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做操作。只需在您希望增加的相同维度上使用它即可。

相关问题