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

估计器置信水平求解:预测时能否获取置信水平值?

当然可以!不过具体实现方式得看你用的是哪个机器学习框架以及模型类型——毕竟不同的估计器输出置信度的方法不太一样。我给你举几个最常用场景的例子:

1. Scikit-learn 框架下的实现

分类模型

绝大多数分类器都自带 predict_proba() 方法,它会返回每个样本属于各个类别的概率值,这个概率值就可以看作模型对预测结果的置信水平。比如用逻辑回归的例子:

from sklearn.linear_model import LogisticRegression
from sklearn.datasets import load_iris

data = load_iris()
X, y = data.data, data.target
model = LogisticRegression()
model.fit(X, y)

# 获取预测类别与对应最高置信度
predictions = model.predict(X)
confidence_scores = model.predict_proba(X).max(axis=1)

这里 predict_proba() 返回的是二维数组,每行对应一个样本,每列对应一个类别的概率,用 max(axis=1) 就能提取该样本预测类别的最高置信度。

回归模型

回归模型不会直接输出“置信度”,但可以通过预测区间来衡量不确定性——区间越窄,模型对预测值的置信水平越高。比如用 statsmodels 配合线性回归:

import statsmodels.api as sm
from sklearn.datasets import fetch_california_housing

data = fetch_california_housing()
X = sm.add_constant(data.data)
y = data.target

model = sm.OLS(y, X).fit()
# 获取预测值与95%置信区间
predictions = model.predict(X)
confidence_intervals = model.get_prediction(X).conf_int()
2. TensorFlow/Keras 深度学习框架

如果是分类模型,且最后一层用了 softmax 激活函数,预测输出的就是各个类别的概率,直接取最大值就是置信度:

import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten

(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0

model = Sequential([
    Flatten(input_shape=(28, 28)),
    Dense(128, activation='relu'),
    Dense(10, activation='softmax')
])

model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)

# 获取每个测试样本的最高置信度
predictions = model.predict(x_test)
confidence_scores = predictions.max(axis=1)

要是需要更严谨的不确定性估计,还可以开启蒙特卡洛 Dropout(预测时保持Dropout层激活),通过多次预测结果的方差来衡量置信水平。

额外提示

像XGBoost、LightGBM这类树模型,也支持用 predict_proba() 获取分类任务的置信概率;另外要注意,置信度高不代表预测绝对正确,它只是模型对结果的“自我信心”,实际应用中还要结合业务场景做验证。

内容的提问来源于stack exchange,提问作者Vik Thakur

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:12:28