首页 > 解决方案 > 连接特征总和 - 形状误差

问题描述

我在 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: Concatenatelayer 需要具有匹配形状的输入,除了 concat 轴。得到输入形状:[(None, 267), (None, 1), (1,), (None, 4), (None, 2)]

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

标签: tensorflowkerastensor

解决方案


这是因为K.sum()(K.reshape()也不是真的需要)。

所有其他张量(input_p,cont_cond等)仍然包含我假设的批处理样本(即它们的形状是(batch_size, num_features),batch_size = None因为它仅在图表运行时定义)。所以你可能想要sum_input_p一个 shape (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)

推荐阅读