## 2017年2月17日 Gaussian Naive Bayes 原

airxiechao

Naive Bayes method is based on applying Bayes’s theorm with the “naive” assumption of independence between features

Gaussian Naive Bayes assumes the likelihood is gaussian

``````from __future__ import division
import numpy as np
from sklearn.naive_bayes import GaussianNB
from scipy.stats import norm
from pylab import scatter, show, legend, xlabel, ylabel

X = data.data
y = data.target

def visualize(X, y):
ys = np.unique(y)
for v in ys:
pos = np.where(y == v)
scatter(X[pos, 0], X[pos, 1])
show()

visualize(X, y)``````

``````class myGaussianNB:
def fit(self, X, y):
self.pys = {}
for v in np.unique(y):
self.pys[v] = y[y==v].shape[0] / y.shape[0]

self.pxys = {}
for v in np.unique(y):
for i in range(X.shape[1]):
xs = X[y==v]
x_mean = np.mean(xs[:,i])
x_std = np.std(xs[:,i])
self.pxys[(v,i)] = (x_mean, x_std)

def predict_single(self, x):
ps = [ self.pys[v] * np.sum([ norm.pdf(x[i], self.pxys[(v,i)][0], self.pxys[(v,i)][1]) for i in range(X.shape[1])]) for v in np.unique(y)]
return np.unique(y)[np.argmax(ps)]

def predict(self, X):
return np.array(map(self.predict_single, X))

def score(self, X, y):
res = self.predict(X)
return np.count_nonzero((res == y) == True) / y.shape[0]

nb = myGaussianNB()
nb.fit(X, y)
print 'score:',nb.score(X, y)
#score: 0.953333333333``````

### airxiechao

xinzhangyanxiang
2014/05/28
0
0

SylvanasSun
2017/12/24
0
0

2018/07/03
0
0

2018/06/07
0
0

superPershing
2017/03/28
0
0

shzwork

6
0
object 类中有哪些方法？

getClass(): 获取运行时类的对象 equals()：判断其他对象是否与此对象相等 hashcode()：返回该对象的哈希码值 toString()：返回该对象的字符串表示 clone()： 创建并返此对象的一个副本 wait...

happywe

6
0
Docker容器实战(七) - 容器中进程视野下的文件系统

JavaEdge

8
0

7
0

MtrS

6
0