机器学习朴素贝叶斯作业 2.0

作业1:优化代码(lgz同学提供的代码)实现:(1)面向过程的朴素贝叶斯(ver1)(2)面向对象版本的朴素贝叶斯。要求不能使用sklearn。

数据集来源

鸢尾花数据集

(1)面向过程的朴素贝叶斯(ver1)

import numpy as np


def GaussianProbability(x, mean, var):  # 高斯概率密度函数
    return np.array(
        [1 / (np.sqrt(2 * np.pi) * var[i]) *
         np.exp(-np.power(x[i] - mean[i], 2) / (2 * np.power(var[i], 2))) for i in range(len(x))])


def fit():  # 求均值&方差
    mean_var = [[np.mean(X[y == label], axis=0), np.var(X[y == label], axis=0)] for label in np.unique(y)]
    return mean_var


def score(feature, label):  # 模型评估
    return np.sum(np.array([[np.argmax(np.array([np.array(
        GaussianProbability(sample, np.array([i[0] for i in fit()])[j],
                            np.array([i[1] for i in fit()])[j])
    ).prod() for j in range(len(np.unique(label)))]))] for sample in
                            feature]).ravel() == label) / label.size


if __name__ == '__main__':
    # 读取数据
    data = np.loadtxt("iris.csv",  # 数据源
                      dtype='str',  # 读取类型
                      delimiter=',',  # 分割符号
                      skiprows=1)

    # 数据预处理
    X = data[::, 0:-1].astype('float32')
    y = data[:, -1]
    y = [0 if i == 'Setosa' else i for i in list(y)]
    y = [1 if i == 'Versicolor' else i for i in list(y)]
    y = [2 if i == 'Virginica' else i for i in list(y)]
    print(f'模型准确率为:{score(X, np.array(y)) * 100}%')

尝试对代码进行压缩(无脑去空行)

import numpy as np
from sklearn.datasets import load_iris
def GaussianProbability(x, mean, var):  # 高斯概率密度函数
    return np.array([1 / (np.sqrt(2 * np.pi) * var[i]) *np.exp(-np.power(x[i] - mean[i], 2) / (2 * np.power(var[i], 2))) for i in range(len(x))])
def fit():  # 求均值&方差
    return [[np.mean(load_iris().data[y == label], axis=0), np.var(X[y == label], axis=0)] for label in np.unique(y)]
def score(feature, label):  # 模型评估
    return np.sum(np.array([[np.argmax(np.array([np.array(GaussianProbability(sample, np.array([i[0] for i in fit()])[j],np.array([i[1] for i in fit()])[j])).prod() for j in range(len(np.unique(label)))]))] for sample in feature]).ravel() == label) / label.size
if __name__ == '__main__':
    X, y = load_iris().data, load_iris().target
    print(f'模型准确率为:{score(X, np.array(y)) * 100}%')

优点

使得代码更加简洁

弊端

过度压缩可能会导致代码可读性变差
上述代码如果进一步压缩,会导致很多需要用其他变量承接数据的没有承接

(2)面向对象版本的朴素贝叶斯

import numpy as np


class GaussianNB:

    def __init__(self, feature, label):
        self.feature = feature  # 特征
        self.label = label  # 标签

    @staticmethod
    def GaussianProbability(x, mean, var):  # 高斯概率密度函数
        return np.array(
            [1 / (np.sqrt(2 * np.pi) * var[i]) *
             np.exp(-np.power(x[i] - mean[i], 2) / (2 * np.power(var[i], 2))) for i in range(len(x))])

    @staticmethod
    def fit():  # 求均值&方差
        mean_var = [[np.mean(X[y == label], axis=0), np.var(X[y == label], axis=0)] for label in np.unique(y)]
        return mean_var

    def score(self, feature, label):  # 模型评估
        return np.sum(np.array([[np.argmax(np.array([np.array(
            self.GaussianProbability(sample, np.array([i[0] for i in self.fit()])[j],
                                     np.array([i[1] for i in self.fit()])[j])).prod() for j in
                                                     range(len(np.unique(label)))]))] for sample in
                                feature]).ravel() == label) / label.size
if __name__ == '__main__':
    # 读取数据
    data = np.loadtxt("iris.csv",  # 数据源
                      dtype='str',  # 读取类型
                      delimiter=',',  # 分割符号
                      skiprows=1)

    # 数据预处理
    X = data[::, 0:-1].astype('float32')
    y = data[:, -1]
    y = [0 if i == 'Setosa' else i for i in list(y)]
    y = [1 if i == 'Versicolor' else i for i in list(y)]
    y = [2 if i == 'Virginica' else i for i in list(y)]

    # 选择模型
    bayes = GaussianNB(X, np.array(y))

	# 训练选择模型及结果
    print(f'模型准确率为:{bayes.score(X, np.array(y)) * 100}%')

如何写 瞧瞧该篇文章
机器学习朴素贝叶斯作业
原创不易 转载请标明出处
如果对你有所帮助 别忘啦点赞支持哈机器学习朴素贝叶斯作业 2.0_第1张图片

你可能感兴趣的:(机器学习作业,机器学习,深度学习)