贝叶斯决策分类(附代码)

参考课件:https://wenku.baidu.com/view/c462058f6529647d2728526a.html

错误率最小化和风险最小化

 

代码:

import numpy as np
import matplotlib.pyplot as plt

from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import make_gaussian_quantiles


# Construct dataset
X1, y1 = make_gaussian_quantiles(mean=(1, 1),cov=0.2,
                                 n_samples=100, n_features=2,
                                 n_classes=1 )

X2, y2 = make_gaussian_quantiles(mean=(1.5, 1.5), cov=0.2,
                                 n_samples=100, n_features=2,
                                 n_classes=1)
X = np.concatenate((X1, X2))
y = np.concatenate((y1, y2+1 ))


# for class 1 error
errorNum = 0
for i in range(len(X)):
    if y[i] == 0 and X[i][0]+X[i][1]>2.5:
        errorNum += 1

print 'exp1 error rate for class 1 is '+str(errorNum)+'%'

# for class 2 error
errorNum = 0
for i in range(len(X)):
    if y[i] == 1 and X[i][0]+X[i][1]<2.5:
        errorNum += 1

print 'exp1 error rate for class 2 is '+str(errorNum)+'%'


# for class 1 risk
errorNum = 0
for i in range(len(X)):
    if y[i] == 0 and 0.368528*(X[i][0]*X[i][0]+X[i][1]*X[i][1])+0.07944*(X[i][0]+X[i][1])-1.119>0:
        errorNum += 1

print 'exp1 risk error rate for class 1 is '+str(errorNum)+'%'

# for class 2 risk
errorNum = 0
for i in range(len(X)):
    if y[i] == 1 and 0.368528*(X[i][0]*X[i][0]+X[i][1]*X[i][1])+0.07944*(X[i][0]+X[i][1])-1.119<0:
        errorNum += 1

print 'exp1 risk error rate for class 2 is '+str(errorNum)+'%'


plot_colors = "br"
plot_step = 0.02
class_names = "AB"

plt.figure(figsize=(8, 8))

# Plot the decision boundaries
plt.subplot(221)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))
Z = np.sign(xx+yy-2.5)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
plt.axis("tight")

# Plot the training points
for i, n, c in zip(range(2), class_names, plot_colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1],
                c=c, cmap=plt.cm.Paired,
                label="Class %s" % n)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.legend(loc='upper right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('exp1 mini error')


plt.subplot(222)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))
Z = np.sign(0.368528*(xx*xx+yy*yy)+0.07944*(xx+yy)-1.119)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
plt.axis("tight")

# Plot the training points
for i, n, c in zip(range(2), class_names, plot_colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1],
                c=c, cmap=plt.cm.Paired,
                label="Class %s" % n)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.legend(loc='upper right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('exp1 mini risk')

###############################################################################

# Construct dataset
X1, y1 = make_gaussian_quantiles(mean=(1, 1),cov=0.2,
                                 n_samples=100, n_features=2,
                                 n_classes=1 )

X2, y2 = make_gaussian_quantiles(mean=(3, 3), cov=0.2,
                                 n_samples=100, n_features=2,
                                 n_classes=1)
X = np.concatenate((X1, X2))
y = np.concatenate((y1, y2+1))


# for class 1 error
errorNum = 0
for i in range(len(X)):
    if y[i] == 0 and X[i][0]+X[i][1]>4:
        errorNum += 1

print 'exp2 error rate for class 1 is '+str(errorNum)+'%'

# for class 2 error
errorNum = 0
for i in range(len(X)):
    if y[i] == 1 and X[i][0]+X[i][1]<4:
        errorNum += 1

print 'exp2 error rate for class 2 is '+str(errorNum)+'%'


# for class 1 risk
errorNum = 0
for i in range(len(X)):
    if y[i] == 0 and 0.368528*(X[i][0]*X[i][0]+X[i][1]*X[i][1])+2.15888*(X[i][0]+X[i][1])-10.4766>0:
        errorNum += 1

print 'exp2 risk error rate for class 1 is '+str(errorNum)+'%'

# for class 2 risk
errorNum = 0
for i in range(len(X)):
    if y[i] == 1 and 0.368528*(X[i][0]*X[i][0]+X[i][1]*X[i][1])+2.15888*(X[i][0]+X[i][1])-10.4766<0:
        errorNum += 1

print 'exp2 risk error rate for class 2 is '+str(errorNum)+'%'

# Plot the decision boundaries
plt.subplot(223)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))
Z = np.sign(xx+yy-4)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
plt.axis("tight")

# Plot the training points
for i, n, c in zip(range(2), class_names, plot_colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1],
                c=c, cmap=plt.cm.Paired,
                label="Class %s" % n)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.legend(loc='upper right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('exp2 mini error')


plt.subplot(224)
x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1
y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
                     np.arange(y_min, y_max, plot_step))
Z = np.sign(0.368528*(xx*xx+yy*yy)+2.15888*(xx+yy)-10.4766)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
plt.axis("tight")

# Plot the training points
for i, n, c in zip(range(2), class_names, plot_colors):
    idx = np.where(y == i)
    plt.scatter(X[idx, 0], X[idx, 1],
                c=c, cmap=plt.cm.Paired,
                label="Class %s" % n)
plt.xlim(x_min, x_max)
plt.ylim(y_min, y_max)
plt.legend(loc='upper right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('exp2 mini risk')


plt.tight_layout()
plt.subplots_adjust(wspace=0.35)
plt.show()

 

转载于:https://www.cnblogs.com/huangshiyu13/p/6537815.html

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
贝叶斯决策树是一种基于贝叶斯理论的决策树分类算法。与传统决策树不同的是,贝叶斯决策树考虑了样本的先验概率和属性间的相关性,能够更准确地进行分类Python中有多个库实现了贝叶斯决策分类算法,其中最常用的是scikit-learn库中的朴素贝叶斯算法。使用scikit-learn库,我们可以轻松地构建和训练贝叶斯决策分类模型。 首先,我们需要准备用于训练和测试的数据集。数据集应包含已知类别的样本和对应的属性。接下来,我们导入scikit-learn库中的贝叶斯模块,并选择合适的贝叶斯分类器。常用的贝叶斯分类器有高斯朴素贝叶斯(GaussianNB)、多项式朴素贝叶斯(MultinomialNB)和伯努利朴素贝叶斯(BernoulliNB)。 然后,我们使用数据集来训练分类器。通过调用分类器的fit()函数,将属性和类别作为输入进行训练。训练完成后,我们可以使用训练好的模型对新样本进行预测。调用分类器的predict()函数,输入待分类的属性,即可获得预测结果。 贝叶斯决策分类算法在处理有限属性空间和大量特征的分类问题时表现出色。它可以有效地处理属性关联性和缺失值,适用于文本分类、垃圾邮件过滤、智能推荐等应用场景。 总之,Python中的贝叶斯决策分类算法提供了一种可靠且准确的分类方法,而且实现简单。通过使用相关库和工具,我们可以快速构建和训练模型,从而实现高效的分类任务。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值