0

我想在将它们提供给另一层之前交换这些功能。我有 4 个变量,所以我的输入数组大小为 (#samples, 4)

假设特征是:x1,x2,x3,x4

异常输出:

交换1:x4、x3、x2、x1

交换2:x2、x3、x2、x1

…… ETC

这是我尝试过的

def toy_model():    
   _input = Input(shape=(4,))
   perm = Permute((4,3,2,1)) (_input)
   dense = Dense(1024)(perm)
   output = Dense(1)(dense)

   model = Model(inputs=_input, outputs=output)
   return model

   toy_model().summary()
   ValueError: Input 0 is incompatible with layer permute_58: expected ndim=5, found ndim=2

但是,置换层期望多维数组来置换数组,因此它无法完成这项工作。无论如何可以在keras中解决这个问题吗?

我还尝试将流动函数作为 Lambda 层提供,但出现错误

def permutation(x):
   x = keras.backend.eval(x)
   permutation = [3,2,1,0]
   idx = np.empty_like(x)
   idx[permutation] = np.arange(len(x))
   permutated = x[:,idx]
   return K.constant(permutated)

ValueError: Layer dense_93 was called with an input that isn't a symbolic tensor. Received type:                                                
<class 'keras.layers.core.Lambda'>. Full input: [<keras.layers.core.Lambda object at 
0x7f20a405f710>]. All inputs to the layer should be tensors.
4

1 回答 1

1

使用Lambda带有一些后端功能或切片 + 连接的层。

4、3、2、1

perm = Lambda(lambda x: tf.reverse(x, axis=-1))(_input)

2、3、2、1

def perm_2321(x):
    x1 = x[:, 0]
    x2 = x[:, 1]
    x3 = x[:, 2]

    return tf.stack([x2,x3,x2,x1], axis=-1)

perm = Lambda(perm_2321)(_input)
于 2020-03-02T18:40:30.600 回答