从本地模块导入的DisplayCallback类无法识别同模块model变量
错误原因
- 作用域绑定问题:
DisplayCallback类的show_predictions方法直接引用模块级model变量,但Python类方法的变量查找遵循LEGB规则,会优先在定义该类的模块(model_utils.py)的全局命名空间中查找model。如果你的model是在Jupyter Notebook中创建的(而非model_utils.py的模块全局变量),或者model_utils.py中model是局部变量、定义顺序不符合执行逻辑,就会导致方法执行时找不到model,触发NameError。 - 导入作用域隔离:用
from model_utils import *导入后,DisplayCallback虽被导入到Notebook命名空间,但类内部方法依然绑定model_utils模块的作用域,而非Notebook的命名空间。如果Notebook中的model和model_utils模块中的model不是同一对象(或模块中无model变量),方法执行时就会找不到目标变量。
解决方法
方法一:让回调类持有model引用(推荐)
避免依赖全局变量,实例化回调时传入model,作用域更清晰灵活:
# model_utils.py import keras class DisplayCallback(keras.callbacks.Callback): def __init__(self, model): super().__init__() self.model = model # 绑定传入的model到实例 def show_predictions(self): predictions = self.model.predict(...) # 后续处理逻辑 def create_model(): return keras.models.Sequential(...)
Notebook中使用:
from model_utils import DisplayCallback, create_model model = create_model() callback = DisplayCallback(model) model.fit(..., callbacks=[callback])
方法二:确保model_utils模块存在全局model
如果要依赖全局变量,需保证model是model_utils.py的模块级变量:
# model_utils.py import keras model = None # 先声明模块级变量 class DisplayCallback(keras.callbacks.Callback): def show_predictions(self): global model # 显式声明使用模块全局变量 if model: predictions = model.predict(...) # 处理逻辑 def build_model(): global model model = keras.models.Sequential(...) return model
Notebook中使用:
from model_utils import * build_model() # 初始化模块全局的model callback = DisplayCallback() model.fit(..., callbacks=[callback])
方法三:利用Keras回调内置的model属性
Keras的Callback类在训练时会自动将当前模型绑定到self.model,无需手动传入:
# model_utils.py import keras class DisplayCallback(keras.callbacks.Callback): def show_predictions(self): # 直接使用Keras内置的self.model,自动关联当前训练模型 predictions = self.model.predict(...) # 处理逻辑
内容的提问来源于stack exchange,提问作者ciahoneypot
相关产品推荐
相关产品推荐

