在keras中交换张量轴

swap tensor axis in keras

我想将图像批次的张量轴从 (batch_size, row, col, ch) 交换到 (batch_size、通道、行、列)。

在 numpy 中,这可以用

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

我如何在 Keras 中做到这一点?

您可以使用 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

使用 keras.layers.Permute(dims) 其中 dims does not include the samples dimension

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