mean, std = value[1][i] prob[label] *= self.gaus_prob(input_data[i], mean, std) # 分类器概率公式 return prob def predict(self, X_test): label = sorted(self.cal_prob(X_test).items(), key=lambda x: x[-1])[-1][0] # {label : prob},按照概率排序,取最后(最大)的【0】标签 return label def predict_prob(self, X_test): prob = sorted(self.cal_prob(X_test).items(), key=lambda x: x[-1])[-1][1] s = sum(i for i in self.cal_prob(X_test).values()) return prob / s # 预测概率 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)) clf = GausNB() clf.fit(X_train, y_train) x = [2, ord('S')] print(x, "自编程高斯贝叶斯预测", clf.predict(x), clf.predict_prob(x))