簡體   English   中英

單個矩陣/張量上numpy在張量流上的hstack

[英]numpy's hstack on tensorflow for a single matrix/tensor

單個矩陣的hstack的numpy版本

c=np.array([[[2,3,4],[4,5,6]],[[20,30,40],[40,50,60]]])

np.hstack(c)

輸出:

array([[ 2,  3,  4, 20, 30, 40],
       [ 4,  5,  6, 40, 50, 60]])

我希望在TF中實現相同的行為。

c_t=tf.constant(c)
tf.stack(c_t,axis=1).eval()

我收到錯誤

TypeError: Expected list for 'values' argument to 'pack' Op, not <tf.Tensor 'Const_14:0' shape=(2, 2, 3) dtype=int64>.

所以我嘗試了

tf.stack([c_t],axis=1).eval()

輸出

array([[[[ 2,  3,  4],
         [ 4,  5,  6]]],


       [[[20, 30, 40],
         [40, 50, 60]]]])

我不是在尋找行為。 tf.reshapetf.concat也沒有幫助我。

我們可以交換/置換軸並重塑-

tf.reshape(tf.transpose(c_t,(1,0,2)),(c_t.shape[1],-1))

相關-NumPy中將4D數組重塑為2D數組的直覺和想法

使其工作的一種方法是首先將張量堆疊到列表中,然后在第一軸上將列表中的張量連接起來:

new_c = tf.concat(tf.unstack(c_t), axis=1)
sess.run(new_c)

array([[ 2,  3,  4, 20, 30, 40],
       [ 4,  5,  6, 40, 50, 60]])

如果要在原子級別上手動進行操作,則下面的方法同樣適用。

In [132]: c=np.array([[[2,3,4],[4,5,6]],[[20,30,40],[40,50,60]]])
In [133]: tfc = tf.convert_to_tensor(c) 

In [134]: slices = [tf.squeeze(tfc[:1, ...]), tf.squeeze(tfc[1:, ...])]  
In [135]: stacked = tf.concat(slices, axis=1) 
In [136]: stacked.eval()           
Out[136]: 
array([[ 2,  3,  4, 20, 30, 40],
       [ 4,  5,  6, 40, 50, 60]])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM