机器学习day8

自定义数据集 ,使用朴素贝叶斯对其进行分类

代码

python 复制代码
import numpy as np
import matplotlib.pyplot as plt

class1_points = np.array([[2.1, 2.2], [2.4, 2.5], [2.2, 2.0], [2.0, 2.1], [2.3, 2.3], [2.6, 2.4], [2.5, 2.1]])
class2_points = np.array([[4.0, 3.5], [4.2, 3.9], [4.1, 3.8], [3.7, 3.4], [4.4, 3.6], [4.5, 3.7], [4.3, 3.9]])

X = np.concatenate((class1_points, class2_points), axis=0)
Y = np.concatenate((np.zeros(len(class1_points)), np.ones(len(class2_points))), axis=0)
print(Y)

prior_prob = [np.sum(Y == 0) / len(Y), np.sum(Y == 1) / len(Y)]

class_μ = [np.mean(X[Y == 0], axis=0), np.mean(X[Y == 1], axis=0)]
class_cov = [np.cov(X[Y == 0], rowvar=False), np.cov(X[Y == 1], rowvar=False)]

def pdf(x, mean, cov):
    n = len(mean)
    coff = 1 / (2 * np.pi) ** (n / 2) * np.sqrt(np.linalg.det(cov))
    exponent = np.exp(-(1 / 2) * np.dot(np.dot((x - mean).T, np.linalg.inv(cov)), (x - mean)))
    return coff * exponent

xx, yy = np.meshgrid(np.arange(0, 5, 0.05), np.arange(0, 5, 0.05))
grid_points = np.c_[xx.ravel(), yy.ravel()]

grid_label = []
for point in grid_points:
    poster_prob = []
    for i in range(2):
        likelihood = pdf(point, class_μ[i], class_cov[i])
        poster_prob.append(prior_prob[i] * likelihood)
    pre_class = np.argmax(poster_prob)
    grid_label.append(pre_class)

plt.scatter(class1_points[:, 0], class1_points[:, 1], c="blue", label="class 1")
plt.scatter(class2_points[:, 0], class2_points[:, 1], c="red", label="class 2")
plt.legend()

grid_label = np.array(grid_label)
pre_grid_label = grid_label.reshape(xx.shape)
contour = plt.contour(xx, yy, pre_grid_label, level=0.5, color='green')

plt.show()

效果

相关推荐
全栈练习生16 小时前
AI Agent 沙箱
python·ai
SEO_juper17 小时前
用 Python 写一个 GEO 可见性检查脚本:你的网站现在能被 AI 引用吗
开发语言·人工智能·爬虫·python·seo·外贸独立站
用户83562907805118 小时前
使用 Python 对 Excel 工作表进行排序
后端·python
for_ever_love__18 小时前
MySQL 全文索引实战:FULLTEXT、ngram 中文分词与 MATCH AGAINST 到底该怎么用
java·python·mysql·全文检索·分词·索引·ngram
用户83562907805118 小时前
使用 Python 合并 PowerPoint 演示文稿
后端·python
weixin_4617694019 小时前
VS Code 中创建 Jupyter 文件(.ipynb)
ide·python·jupyter
2601_9669496519 小时前
多市场量化策略的数据接口应该如何设计:从数据层架构到策略接入
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
joopthd19 小时前
工业在线 TDLAS 器件源头厂商|连续监测场景器件选型要点
机器学习·激光气体检测·tdlas分析模块·仪器集成开发·工业在线监测
全栈弄潮儿19 小时前
Python实战第1期:Python环境搭建与第一个程序
python