【笔记】【机器学习基础】分类器的不确定估计

分类器除了给出预测的不确定度,还能给出对这个预测的置信程度。
函数:1、decision_function 2、predict_proba
下面通过构建GradientBoostingClassifier分类测试:

from sklearn.ensemble import GradientBoostingClassifier
from sklearn.datasets import make_circles
X, y = make_circles(noise=0.25, factor=0.5, random_state=1)

y_named = np.array(["blue", "red"])[y]

X_train, X_test, y_train_named, y_test_named, y_train, y_test = \
    train_test_split(X, y_named, y, random_state=0)

gbrt = GradientBoostingClassifier(random_state=0)
gbrt.fit(X_train, y_train_named)

在这里插入图片描述

一、决策函数

(1)返回值

print("X_test.shape:", X_test.shape)
print("Decision function shape:",
      gbrt.decision_function(X_test).shape)

X_test.shape: (25, 2)
Decision function shape: (25,)
对于类别1,这个值表示该数据点属于正类的置信程度
正值表示对正类的偏好,负值表示对其他类的偏好

(2)显示decision_function前几个元素

print("Decision function:", gbrt.decision_function(X_test)[:6])

(3)查看决策函数的正负号再现预测值

print("Thresholded decision function:\n",
      gbrt.decision_function(X_test) > 0)
print("Predictions:\n", gbrt.predict(X_test))

Thresholded decision function:
[ True False False False True True False True True True False True
True False True False False False True True True True True False
False]
Predictions:
[‘red’ ‘blue’ ‘blue’ ‘blue’ ‘red’ ‘red’ ‘blue’ ‘red’ ‘red’ ‘red’ ‘blue’
‘red’ ‘red’ ‘blue’ ‘red’ ‘blue’ ‘blue’ ‘blue’ ‘red’ ‘red’ ‘red’ ‘red’
‘red’ ‘blue’ ‘blue’]
对于二分类问题,反类是classes_属性的第一个元素,正类是第二个元素。完全在现predict的输出需要利用classes_属性:
(4)再现predict的输出

greater_zero = (gbrt.decision_function(X_test) > 0).astype(int)

pred = gbrt.classes_[greater_zero]

print("pred is equal to predictions:",
      np.all(pred == gbrt.predict(X_test)))

pred is equal to predictions: True

(5)

decision_function = gbrt.decision_function(X_test)
print("Decision function minimum: {:.2f} maximum: {:.2f}".format(
      np.min(decision_function), np.max(decision_function)))

decision_function任意范围取值,取决于数据和模型参数,所以输出往往会很难解释

(6)利用颜色编码在二维平面将所有点的decision_function和决策边界可视化

fig, axes = plt.subplots(1, 2, figsize=(13, 5))
mglearn.tools.plot_2d_separator(gbrt, X, ax=axes[0], alpha=.4,
                                fill=True, cm=mglearn.cm2)
scores_image = mglearn.tools.plot_2d_scores(gbrt, X, ax=axes[1],
                                            alpha=.4, cm=mglearn.ReBl)

for ax in axes:
    # plot training and test points
    mglearn.discrete_scatter(X_test[:, 0], X_test[:, 1], y_test,
                             markers='^', ax=ax)
    mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train,
                             markers='o', ax=ax)
    ax.set_xlabel("Feature 0")
    ax.set_ylabel("Feature 1")
cbar = plt.colorbar(scores_image, ax=axes.tolist())
cbar.set_alpha(1)
cbar.draw_all()
axes[0].legend(["Test class 0", "Test class 1", "Train class 0",
                "Train class 1"], ncol=4, loc=(.1, 1.1))

在这里插入图片描述
给出预测结果和分类器的置信程度。但是上面的图像难以分辨决策边界

二、预测概率

(1)predict_proba

print("Shape of probabilities:", gbrt.predict_proba(X_test).shape)

predict_proba的输出是每个类别的概率

(2)估计概率

print("Predicted probabilities:")
print(gbrt.predict_proba(X_test[:6]))

Predicted probabilities:
[[0.016 0.984]
[0.846 0.154]
[0.981 0.019]
[0.974 0.026]
[0.014 0.986]
[0.025 0.975]]
每行的第一个元素是第一个类别的估计概率,第二个元素是第二个类别的估计概率,两个类别的元素之和始终为1

(3)梯度提升模型的决策边界和预测概率

fig, axes = plt.subplots(1, 2, figsize=(13, 5))
    
mglearn.tools.plot_2d_separator(
    gbrt, X, ax=axes[0], alpha=.4, fill=True, cm=mglearn.cm2)
scores_image = mglearn.tools.plot_2d_scores(
    gbrt, X, ax=axes[1], alpha=.5, cm=mglearn.ReBl, function='predict_proba')

for ax in axes:
    # plot training and test points
    mglearn.discrete_scatter(X_test[:, 0], X_test[:, 1], y_test,
                             markers='^', ax=ax)
    mglearn.discrete_scatter(X_train[:, 0], X_train[:, 1], y_train,
                             markers='o', ax=ax)
    ax.set_xlabel("Feature 0")
    ax.set_ylabel("Feature 1")

cbar = plt.colorbar(scores_image, ax=axes.tolist())
cbar.set_alpha(1)
cbar.draw_all()
axes[0].legend(["Test class 0", "Test class 1", "Train class 0",
                "Train class 1"], ncol=4, loc=(.1, 1.1))

在这里插入图片描述
边界更明显

三、多分类问题的不确定度

将两个函数应用于多分类问题

(1)鸢尾花数据集

from sklearn.datasets import load_iris

iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
    iris.data, iris.target, random_state=42)

gbrt = GradientBoostingClassifier(learning_rate=0.01, random_state=0)
gbrt.fit(X_train, y_train)
print("Decision function shape:", gbrt.decision_function(X_test).shape)

print("Decision function:")
print(gbrt.decision_function(X_test)[:6, :])

在这里插入图片描述
对于多分类的,decision_function 的形状为(n_samples,n_classes),每一类对应每个类别的确定度分数,分数较高的类别可能性更大。

(2)再现预测结果

print("Argmax of decision function:")
print(np.argmax(gbrt.decision_function(X_test), axis=1))
print("Predictions:")
print(gbrt.predict(X_test))

在这里插入图片描述
(3)

print("Predicted probabilities:")
print(gbrt.predict_proba(X_test)[:6])

print("Sums:", gbrt.predict_proba(X_test)[:6].sum(axis=1))

Predicted probabilities:
[[0.107 0.784 0.109]
[0.789 0.106 0.105]
[0.102 0.108 0.789]
[0.107 0.784 0.109]
[0.108 0.663 0.228]
[0.789 0.106 0.105]]
Sums: [1. 1. 1. 1. 1. 1.]

(4)再现预测结果(通过predict_proba的argmax)

print("Argmax of predicted probabilities:")
print(np.argmax(gbrt.predict_proba(X_test), axis=1))
print("Predictions:")
print(gbrt.predict(X_test))

predict_proba和decision_function的形状始终相同,除了二分类下的decision_function

(5)通过classes_获取真实属性名称

logreg = LogisticRegression()
named_target = iris.target_names[y_train]
logreg.fit(X_train, named_target)
print("unique classes in training data:", logreg.classes_)
print("predictions:", logreg.predict(X_test)[:10])
argmax_dec_func = np.argmax(logreg.decision_function(X_test), axis=1)
print("argmax of decision function:", argmax_dec_func[:10])
print("argmax combined with classes_:",
      logreg.classes_[argmax_dec_func][:10])

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
很高兴听到你正在学习《机器学习》这本经典的教材,下面我为你提供第十四章概率图模型的Python实现学习笔记。 ## 1. 朴素贝叶斯分类器 ### 1.1 数据准备 在本章中,我们将使用著名的鸢尾花数据集进行分类。首先,我们可以从sklearn库中导入该数据集。 ```python from sklearn.datasets import load_iris iris = load_iris() X = iris.data y = iris.target ``` ### 1.2 朴素贝叶斯分类器实现 接下来,我们可以使用sklearn库中的朴素贝叶斯分类器进行分类,具体实现如下: ```python from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42) gnb = GaussianNB() gnb.fit(X_train, y_train) y_pred = gnb.predict(X_test) accuracy = accuracy_score(y_test, y_pred) print('Accuracy:', accuracy) ``` ### 1.3 结果分析 运行上述代码后,我们可以得到该模型在测试集上的准确率,结果如下所示: ``` Accuracy: 1.0 ``` 可以看出,该模型在鸢尾花数据集上表现出色,准确率达到了100%。 ## 2. 隐马尔可夫模型 ### 2.1 数据准备 在本节中,我们将使用一个简单的例子来介绍隐马尔可夫模型的实现。假设我们有一个长度为100的序列,每个位置上的值都是0或1,其中0和1出现的概率分别为0.6和0.4。我们可以使用numpy库生成这个序列。 ```python import numpy as np np.random.seed(42) sequence = np.random.choice([0, 1], size=100, p=[0.6, 0.4]) ``` ### 2.2 隐马尔可夫模型实现 接下来,我们可以使用hmmlearn库中的隐马尔可夫模型进行序列建模,具体实现如下: ```python from hmmlearn import hmm model = hmm.MultinomialHMM(n_components=2) model.fit(sequence.reshape(-1, 1)) logprob, states = model.decode(sequence.reshape(-1, 1)) print('Sequence:', sequence) print('States:', states) ``` ### 2.3 结果分析 运行上述代码后,我们可以得到该模型对序列的建模结果,结果如下所示: ``` Sequence: [0 0 0 0 0 0 0 0 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] States: [1 1 1 1 1 1 1 1 1 1 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1] ``` 可以看出,模型对序列进行了建模,并输出了每个位置上的状态,其中0表示“假”,1表示“真”。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值