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

如何解决神经网络预测中的负值问题——混淆矩阵报错排查

问题:sigmoid输出的神经网络生成混淆矩阵时出现负值报错

我搭建了一个含16列特征的简单ANN,训练和评估环节都正常,但添加混淆矩阵代码时触发错误。

训练代码(运行正常)

import tensorflow as tf
import pandas as pd
from tensorflow import keras

data = pd.read_csv(soruce_code.csv)

features = data.drop('feature1', axis=1)
labels = data['feature1']

features = tf.keras.utils.normalize(features, axis=1)

model = tf.keras.models.Sequential([
    tf.keras.layers.Dense(12, activation='relu'),
    tf.keras.layers.Dense(8, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy' , metrics=['accuracy'])

model.fit(features, labels, epochs=100)
model.evaluate(features, labels)

混淆矩阵代码及报错

添加以下代码生成混淆矩阵:

confusion_matrix = tf.math.confusion_matrix(labels, model.predict(features))
print(confusion_matrix)

触发错误:

InvalidArgumentError: predictions contains negative values.
Condition x >= 0 did not hold element-wise:

明明输出层用了sigmoid激活,输出应该被压缩在0-1区间,不会有负值,一开始加sigmoid就是为了避免这类问题,但没效果。


解决方法

问题核心是tf.math.confusion_matrix的参数要求:它需要输入整数类型的类别标签,而不是sigmoid输出的0-1概率值。直接传入概率值会导致tensorflow在处理时出现类型转换或数值精度相关的误判,进而抛出“存在负值”的错误。

修正后的混淆矩阵代码

# 获取模型的概率输出
predict_probs = model.predict(features)
# 以0.5为阈值转换为类别标签(可根据需求调整阈值)
predict_labels = (predict_probs > 0.5).astype(int)
# 确保原始标签为整数类型
labels = labels.astype(int)
# 生成混淆矩阵
confusion_matrix = tf.math.confusion_matrix(labels, predict_labels)
print(confusion_matrix)

补充说明:sigmoid的输出确实不会出现负值,报错里的提示是因为直接传入概率值后,tensorflow的内部处理逻辑导致的误报,本质是参数类型不符合要求。

内容的提问来源于stack exchange,提问作者John Stiles

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 21:55:09