TensorFlow模型已编译仍提示未找到损失函数的问题求助
问题描述
使用TensorFlow 2.9.2开发模型时,无论通过tf.keras.Sequential()直接堆叠层还是函数式构建,训练阶段均触发以下报错:
ValueError: No loss found. You may have forgotten to provide a `loss` argument in the `compile()` method.
两次尝试的代码
尝试1
from keras.layers import Conv2D, MaxPooling2D, Dense import keras from keras import losses from keras import optimizers from keras import metrics def create_model(): model = tf.keras.Sequential([ tf.keras.layers.Dense(65000/train.shape[0], input_shape=(65000,)), layers.Dense(128, activation='relu'), layers.Dense(256, activation='relu'), layers.Dense(3,activation='sigmoid'), ]) model.compile(loss = 'mean_squared_error', optimizer = 'sgd', metrics = [metrics.categorical_accuracy]) return model model = create_model() model.fit(train_x, labels, epochs=10)
尝试2
from keras.layers import Conv2D, MaxPooling2D, Dense import keras from keras import losses from keras import optimizers from keras import metrics model =tf.keras.Sequential() model.add(Dense(100, activation='relu')) model.add(tf.keras.layers.Dense(1, activation='softmax')) model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) model.fit(train_x, labels, epochs=2, steps_per_epoch=10) print('My custom loss: ', model.loss_tracker.result().numpy())
环境版本信息
tensorflow version 2.9.2 numpy version 1.23.4 pandas version 1.5.0 keras version 2.9.0 python Version:- 3.9.16 (main, Dec 7 2022, 01:11:51) [GCC 9.4.0]
运行环境为paperspace.com的Jupyter Notebook,更换不同显卡实例后问题仍存在,Jupyter核心包版本:
Selected Jupyter core packages... IPython : 8.5.0 ipykernel : 6.16.0 ipywidgets : 8.0.2 jupyter_client : 7.3.4 jupyter_core : 5.1.5 jupyter_server : 1.23.5 jupyterlab : 3.4.6 nbclient : 0.7.2 nbconvert : 7.2.9 nbformat : 5.7.3 notebook : 6.5.2 qtconsole : not installed traitlets : 5.8.1
解决方案
1. 统一使用tf.keras模块
报错核心原因是混用了独立Keras包与TensorFlow内置的Keras,TF 2.x版本官方仅维护tf.keras,两者混用会导致模型编译配置无法被正确识别。需将所有Keras相关导入替换为tf.keras:
修改后的尝试1代码
import tensorflow as tf from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D from tensorflow.keras import metrics def create_model(): model = tf.keras.Sequential([ # 神经元数量需为整数,改用整数除法 tf.keras.layers.Dense(65000//train.shape[0], input_shape=(65000,)), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(256, activation='relu'), tf.keras.layers.Dense(3, activation='sigmoid'), ]) model.compile( loss='mean_squared_error', optimizer='sgd', metrics=[metrics.categorical_accuracy] ) return model model = create_model() model.fit(train_x, labels, epochs=10)
修改后的尝试2代码
import tensorflow as tf from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D model = tf.keras.Sequential() model.add(tf.keras.layers.Dense(100, activation='relu')) model.add(tf.keras.layers.Dense(1, activation='softmax')) model.compile(optimizer="Adam", loss="mse", metrics=["mae"]) model.fit(train_x, labels, epochs=2, steps_per_epoch=10) # 内置损失无需调用loss_tracker,仅自定义损失并添加跟踪器时可用,此处注释或删除该行 # print('My custom loss: ', model.loss_tracker.result().numpy())
2. 清理环境依赖
卸载独立的keras包,避免版本冲突:
pip uninstall -y keras
TensorFlow 2.9.2自带的Keras版本即为2.9.0,无需单独安装。
3. 额外注意事项
- 神经元数量必须是整数,避免使用浮点数除法,改用
//进行整数运算。 model.loss_tracker仅适用于自定义损失并显式添加LossTracker回调的场景,使用内置损失时无需调用该属性。
内容的提问来源于stack exchange,提问作者Lukas Taylor
相关产品推荐
相关产品推荐

