如何在TensorFlow函数式API中使用Lambda层实现自定义函数?
问题解决:生成[ab, bc]的正确实现
你的代码存在两个核心问题:
- Lambda函数返回了列表,Keras会将其解析为两个独立的输出张量,而非单个形状为(None,2)的张量,这就是输出形状显示为[(3,),(3,)]的原因。
- 张量索引方式错误:输入x是形状为(None,3)的批量张量,
x[0]取的是第一个完整样本(形状(3,)),而非每个样本的第一个元素,正确索引每个样本的第n位应该用x[:, n]。
以下是两种正确的实现方式:
方式一:使用Keras内置的concatenate拼接结果
from keras.layers import Input, Lambda, concatenate from keras.models import Model input_tensor = Input((3,)) output_tensor = Lambda( lambda x: concatenate([x[:, 0] * x[:, 1], x[:, 1] * x[:, 2]], axis=-1) )(input_tensor) model = Model(input_tensor, output_tensor) model.summary()
方式二:使用TensorFlow的concat(适用于TensorFlow后端)
import tensorflow as tf from keras.layers import Input, Lambda from keras.models import Model input_tensor = Input((3,)) output_tensor = Lambda( lambda x: tf.concat([x[:, 0] * x[:, 1], x[:, 1] * x[:, 2]], axis=1) )(input_tensor) model = Model(input_tensor, output_tensor) model.summary()
运行后,模型摘要会显示输出形状为(None, 2),完全符合你的需求。
内容的提问来源于stack exchange,提问作者Pooty Lim
相关产品推荐
相关产品推荐

