You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

测试图像标题生成模型时遇Unknown layer: 'NotEqual'错误求助

解决加载图像标题生成模型时的Unknown layer: 'NotEqual'错误

问题原因

你定义了NotEqual自定义操作,但加载模型时仅在custom_objects参数中注册了KerasLayer,Keras无法识别未注册的自定义操作,因此抛出Unknown layer: 'NotEqual'错误。

解决步骤

  1. 注册自定义操作到custom_objects
    加载模型时,将NotEqual函数添加到custom_objects字典中,让Keras能够识别它:
model = load_model(
    path,
    custom_objects={'KerasLayer': hub.KerasLayer, 'NotEqual': NotEqual}
)
  1. 优化自定义操作定义
    当前代码中NotEqual函数内部重复导入TensorFlow,建议将TensorFlow导入移到文件顶部,避免冗余:
# 移到文件开头的导入区
import tensorflow as tf

# 定义自定义操作
def NotEqual(x, y):
    return tf.math.not_equal(x, y)
  1. 修复缺失的依赖导入
    原代码extract_features函数中使用了numpy但未导入,需在开头补充:
import numpy as np

修改后的关键代码片段

from PIL import Image
import matplotlib.pyplot as plt
import argparse
import pickle
import numpy as np
import tensorflow as tf
from keras.models import load_model
from keras.layers import Lambda
from keras.applications.xception import Xception
from keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
import tensorflow_hub as hub

# 定义自定义操作
def NotEqual(x, y):
    return tf.math.not_equal(x, y)

# ... 其余函数定义保持不变 ...

# 加载模型部分修改
path='models/model_9.h5'
model = load_model(
    path,
    custom_objects={'KerasLayer': hub.KerasLayer, 'NotEqual': NotEqual}
)

内容的提问来源于stack exchange,提问作者Arpit Goyal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 21:22:39