连接特征和 - 形状错误

Concatenate Sum of Features - Shape Error

我在 Keras 中有一个模型,我想在其中明确让神经网络查看一些特征的总和。我尝试这样做:

sum_input_p = Lambda(sumFunc)(input_p)
d_input = keras.layers.concatenate(
    [input_p, cont_cond, sum_input_p, one_hot_cond_1, one_hot_cond_2 ], axis=-1)

其中

def sumFunc(x):
   return K.reshape(K.sum(x), [1])

但是我得到一个错误:

ValueError: Concatenate layer requires inputs with matching shapes except for the concat axis. Got inputs shapes: [(None, 267), (None, 1), (1,), (None, 4), (None, 2)]

是因为sumFunc中的reshape步吗?我怎样才能正确地重塑它,以便它可以与神经网络中的其他特征连接起来?

因为K.sum()K.reshape()其实也不需要)。

所有其他张量(input_pcont_cond 等)仍然包含我假设的批处理样本(即它们的形状是 (batch_size, num_features),与 batch_size = None 一样仅在图形为 运行 时定义)。因此,您可能希望 sum_input_p 具有 (batch_size, 1) 的形状,即计算输入张量 x 的所有维度的总和,除了第一个维度(对应于批量大小)。

import keras
import keras.backend as K
from keras.layers import Input, Lambda
import numpy as np

def sumFunc(x):
    x_axes = np.arange(0, len(x.get_shape().as_list()))
    # ... or simply x_axes = [0, 1] in your case, since the shape of x is known
    y = K.sum(x, axis=x_axes[1:])   # y of shape (batch_size,)
    y = K.expand_dims(y, -1)        # y of shape (batch_size, 1)
    return y


input_p = Input(shape=(267,))
sum_input_p = Lambda(sumFunc)(input_p)
print(sum_input_p)
# > Tensor("lambda_1/ExpandDims:0", shape=(?, 1), dtype=float32)
d_input = keras.layers.concatenate([input_p, sum_input_p], axis=-1)
print(d_input)
# > Tensor("concatenate_1/concat:0", shape=(?, 268), dtype=float32)