在keras中交换张量轴

use*_*212 11 keras tensorflow

我想将图像批次的张量轴从(batch_size,row,col,ch)交换到(batch_size,ch,row,col).

在numpy,这可以完成

X_batch = np.moveaxis( X_batch, 3, 1)
Run Code Online (Sandbox Code Playgroud)

我怎么能在Keras那样做?

ind*_*you 18

您可以使用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
Run Code Online (Sandbox Code Playgroud)