2017-02-20 2 views
8

こんにちは、私はテンソルフローが初めてです。私はtensorflowで次のPythonコードを実装したいと思います。テンソルフローの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です。テンソルフローのドキュメントにはエントリーはありませんが、tf.stride_sliceのドキュメントページで簡単に触れています。 tf.expand_dimsを使用して

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

は、上記のリンクに記載されているように、あまりにも細かいですが、

これらのインタフェースは、はるかに友好的であり、強くお勧めします。

0

あなたが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の中で行う操作のと全く同じようなものです。あなたがそれを増やしたいのと同じ次元で正確に使うだけです。

関連する問題