tensorflow - 连接特征总和 - 形状误差
问题描述
我在 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 需要具有匹配形状的输入,除了 concat 轴。得到输入形状:[(None, 267), (None, 1), (1,), (None, 4), (None, 2)]
是因为reshape
步入sumFunc
吗?我怎样才能正确地重塑它,以便它可以与神经网络中的其他特征连接起来?
解决方案
这是因为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)
推荐阅读
- c - 找到连接灯泡代码的最少电线数量
- arrays - 如何在Scala中手动对数组进行排序?
- javascript - 如何存储 jwt 令牌以便重定向到其他子域不需要凭据
- python - 将大小为 2 的 numpy 数组转换为 3
- security - 阻止用户使用 AD 组策略上传文件
- python - 如何读取用于训练模型(CNN)的 csv 文件?
- ajax - 如何访问ajax内容中的关系
- python - 如何使用 python imaplib 或其他方式访问我的电子邮件?
- javascript - 如何使用当前 URL 修改 HTML 代码?
- linear-regression - 寻找一个非线性变换矩阵(就像一个有趣的房子镜子)