在Keras中交换张量轴

13

我希望将图像批处理张量的轴从(batch_size, row, col, ch)替换为(batch_size, ch, row, col)。

在numpy中,可以使用以下方法完成:

X_batch = np.moveaxis( X_batch, 3, 1)

我该如何在Keras中实现这一点?

2个回答

22
你可以使用K.permute_dimensions(),它与np.transpose()完全相似。
示例:
import numpy as np 
from keras import backend as K 

A = np.random.random((1000,32,64,3))
# B = np.moveaxis( A, 3, 1)
C = np.transpose( A, (0,3,1,2))

print A.shape
print C.shape

A_t = K.variable(A)
C_t = K.permute_dimensions(A_t, (0,3,1,2))

print K.eval(A_t).shape
print K.eval(C_t).shape

4

使用 keras.layers.Permute(dims),其中 dims 不包括样本维度

model.add(Permute((2, 1), input_shape=(10, 64)))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接