洞察探讨小游戏SDK接入的最佳实践以及对企业跨平台开发的优势
999
2022-09-06
【机器学习】朴素贝叶斯代码练习
本课程是中国大学慕课《机器学习》的“朴素贝叶斯”章节的课后代码。课程地址:numpy as npimport pandas as pdfrom sklearn.datasets import load_irisfrom sklearn.model_selection import train_test_splitfrom collections import Counterimport math
# datadef create_data(): iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df['label'] = iris.target df.columns = [ 'sepal length', 'sepal width', 'petal length', 'petal width', 'label' ] data = np.array(df.iloc[:100, :]) # print(data) return data[:, :-1], data[:, -1]
X, y = create_data()X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
X_test[0], y_test[0]
(array([5.1, 3.8, 1.9, 0.4]), 0.0)
参考:高斯朴素贝叶斯
特征的可能性被假设为高斯
概率密度函数:
数学期望(mean):
方差:
class NaiveBayes: def __init__(self): self.model = None # 数学期望 @staticmethod def mean(X): return sum(X) / float(len(X)) # 标准差(方差) def stdev(self, X): avg = self.mean(X) return math.sqrt(sum([pow(x - avg, 2) for x in X]) / float(len(X))) # 概率密度函数 def gaussian_probability(self, x, mean, stdev): exponent = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2)))) return (1 / (math.sqrt(2 * math.pi) * stdev)) * exponent # 处理X_train def summarize(self, train_data): summaries = [(self.mean(i), self.stdev(i)) for i in zip(*train_data)] return summaries # 分类别求出数学期望和标准差 def fit(self, X, y): labels = list(set(y)) data = {label: [] for label in labels} for f, label in zip(X, y): data[label].append(f) self.model = { label: self.summarize(value) for label, value in data.items() } return 'gaussianNB train done!' # 计算概率 def calculate_probabilities(self, input_data): # summaries:{0.0: [(5.0, 0.37),(3.42, 0.40)], 1.0: [(5.8, 0.449),(2.7, 0.27)]} # input_data:[1.1, 2.2] probabilities = {} for label, value in self.model.items(): probabilities[label] = 1 for i in range(len(value)): mean, stdev = value[i] probabilities[label] *= self.gaussian_probability( input_data[i], mean, stdev) return probabilities # 类别 def predict(self, X_test): # {0.0: 2.9680340789325763e-27, 1.0: 3.5749783019849535e-26} label = sorted(self.calculate_probabilities(X_test).items(), key=lambda x: x[-1])[-1][0] return label def score(self, X_test, y_test): right = 0 for X, y in zip(X_test, y_test): label = self.predict(X) if label == y: right += 1 return right / float(len(X_test))
model = NaiveBayes()
model.fit(X_train, y_train)
'gaussianNB train done!'
print(model.predict([4.4, 3.2, 1.3, 0.2]))
0.0
model.score(X_test, y_test)
1.0
scikit-learn实例
from sklearn.naive_bayes import GaussianNB, BernoulliNB, MultinomialNB# 高斯模型、伯努利模型和多项式模型
clf = GaussianNB()clf.fit(X_train, y_train)
GaussianNB(priors=None, var_smoothing=1e-09)
clf.score(X_test, y_test)
1.0
clf.predict([[4.4, 3.2, 1.3, 0.2]])
array([0.])
参考
Prof. Andrew Ng. Machine Learning. Stanford University李航,《统计学习方法》,清华大学出版社
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~