如何对形状未知的张量应用NumPy函数,实现Keras自定义Tile层
问题根源
报错的核心原因是在Keras计算图构建阶段混用了NumPy算子:Keras搭建模型时输入为无实际值的符号Tensor,而np.tile是NumPy原生函数,仅能处理有具体数值的数组,无法识别TensorFlow的符号张量,和batch维度未知是间接关联,本质是算子不兼容。
解决方法
将call方法中的NumPy实现替换为TensorFlow原生的tf.tile算子,同时补全自定义层必要的序列化方法,避免后续模型保存加载出错。
修正后完整可运行代码
import tensorflow as tf from tensorflow import keras from keras import Input, Layer # 补全Layer的导入 class Tile(Layer): def __init__(self, repeat, **kwargs): self.repeat = repeat super(Tile,self).__init__(**kwargs) def call(self, x): # 替换为tf原生tile算子,兼容符号张量计算 return tf.tile(x, self.repeat) # 补全get_config方法,支持模型序列化保存/加载 def get_config(self): config = super().get_config() config.update({"repeat": self.repeat}) return config input = Input(shape=(3,)) repeat = (1, 2) x = Tile(repeat)(input) model = keras.Model(input, x) # 输入补全batch维度,输出形状为(1,6) print(model(tf.ones((1, 3))))
运行输出
tf.Tensor([[1. 1. 1. 1. 1. 1.]], shape=(1, 6), dtype=float32)
内容的提问来源于stack exchange,提问作者danix
相关产品推荐
相关产品推荐

