[英]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.reshape
和tf.concat
也沒有幫助我。
使其工作的一種方法是首先將張量堆疊到列表中,然后在第一軸上將列表中的張量連接起來:
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.