遇到ValueError:Keras函数式模型输入张量异常该如何解决?
解决方案:Keras模型调用触发的ValueError问题
错误原因
你直接将真实的输入数据张量传给了Keras函数式模型,而Keras要求模型的输入必须是通过tf.keras.Input()定义的KerasTensor(模型输入占位符),不能直接传入真实数据张量。
解决步骤
1. 正确构建Keras函数式模型
先通过tf.keras.Input()声明输入的形状、数据类型,作为模型的输入接口,再搭建模型核心逻辑:
import tensorflow as tf from transformers import TFBertModel # 根据你的任务调整参数 max_seq_len = 512 num_classes = 2 # 任务类别数量 # 定义Keras输入占位符 input_ids_input = tf.keras.Input(shape=(max_seq_len,), dtype=tf.int32, name="input_ids") attention_mask_input = tf.keras.Input(shape=(max_seq_len,), dtype=tf.int32, name="attention_mask") # 示例:基于BERT构建模型核心 bert_model = TFBertModel.from_pretrained('bert-base-chinese') bert_output = bert_model(input_ids_input, attention_mask=attention_mask_input)[0] # 提取[CLS] token输出用于分类任务 cls_output = bert_output[:, 0, :] # 输出未激活的logits logits = tf.keras.layers.Dense(num_classes, activation=None)(cls_output) # 组装完整模型 model = tf.keras.Model(inputs=[input_ids_input, attention_mask_input], outputs=logits)
2. 传入真实数据并计算softmax
用真实的输入数据张量调用模型,再对输出的logits应用softmax:
# real_input_ids、real_attention_mask为你的真实输入数据张量 logits = model([real_input_ids, real_attention_mask]) # 计算概率分布 probabilities = tf.nn.softmax(logits, axis=1)
若使用PyTorch环境
如果是PyTorch框架,不要混用Keras的Model类,改用PyTorch标准模型定义方式:
import torch import torch.nn.functional as F from transformers import BertModel class CustomModel(torch.nn.Module): def __init__(self, num_classes): super().__init__() self.bert = BertModel.from_pretrained('bert-base-chinese') self.classifier = torch.nn.Linear(self.bert.config.hidden_size, num_classes) def forward(self, input_ids, attention_mask): outputs = self.bert(input_ids, attention_mask=attention_mask) cls_output = outputs.last_hidden_state[:, 0, :] logits = self.classifier(cls_output) return logits # 实例化模型并推理 model = CustomModel(num_classes=2) logits = model(input_ids, attention_mask) probabilities = F.softmax(logits, dim=1)
内容的提问来源于stack exchange,提问作者Santhoshi Vaasanthi
相关产品推荐
相关产品推荐

