鸢尾花数据集
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}%')
使得代码更加简洁
过度压缩可能会导致代码可读性变差
上述代码如果进一步压缩,会导致很多需要用其他变量承接数据的没有承接
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}%')