from sklearn.naive_bayes import GaussianNB
class naiveBayes:
	gnb = None
	x = []
	y = []
	def __init__(self,filename):
		self.gnb = GaussianNB()
		with open(filename) as f:
			for line in f:
				if line[0]>='0' and line[0]<='9':
					tmp = line.strip('\n').split(',')
					tmp = map(lambda x:float(x),tmp)
					self.x.append(tmp[:-1])
					self.y.append(tmp[-1])
	def train(self):
		self.gnb.fit(self.x,self.y)
	def predict(self,input):
		return self.gnb.predict(input)
if __name__ == '__main__':
	nb = naiveBayes("../decisionTree/trainingSet/train_500.txt");
	nb.train()
	print(nb.predict(nb.x[0]))

@@ -36,16 +36,117 @@
 ssianNB%0A
+import numpy as nu%0Aimport sys%0Afrom sklearn import cross_validation as cv%0Afrom sklearn import metrics%0A
 class na
@@ -183,16 +183,29 @@
 %09y = %5B%5D%0A
+%09labels = %5B%5D%0A
 %09def __i
@@ -475,113 +475,1191 @@
 %5D)%0A%09
-def train(self):%0A%09%09self.gnb.fit(self.x,self.y)%0A%09def predict(self,input):%0A%09%09return self.gnb.predict(input)
+%09%09%09elif line%5B0%5D == 's':%0A%09%09%09%09%09line = line.strip('%5Cn').split('%7C')%0A%09%09%09%09%09print(line)%0A%09%09%09%09%09self.labels = map(lambda x: int(x),line%5B2%5D.strip('%7B%7D').split(','))%0A%09def train(self):%0A%09%09self.gnb.fit(self.x,self.y)%0A%09def predict(self,input):%0A%09%09return self.gnb.predict(input)%0A%09def crossValidate(self,test_size=None,confusion_matrux=False):%0A%09%09if len(self.x)==0 or len(self.y) ==0:%0A%09%09%09sys.stderr.write(%22Uninitialized object%22)%0A%09%09%09return%0A%09%09#randomly draw from sample%0A%09%09X_train, X_test, y_train, y_test = cv.train_test_split(self.x, self.y, test_size=0.2, random_state=0)%0A%09%09self.gnb.fit(X_train,y_train)%0A%09%09out = self.predict(X_test)%0A%09%09if confusion_matrux:%0A%09%09%09self.comput_confusion_matrix(out,y_test)%0A%09%09total_correct = 0%0A%09%09for i in range(len(out)):%0A%09%09%09if out%5Bi%5D == y_test%5Bi%5D:%0A%09%09%09%09total_correct +=1%0A%09%09return float(total_correct)/len(out)%0A%09def comput_confusion_matrix(self,y_out,y_test):%0A%09%09matrix = nu.zeros((len(self.labels),len(self.labels)),dtype=nu.int)%0A%09%09for i in xrange(len(y_out)):%0A%09%09%09matrix%5By_test%5Bi%5D%5D%5By_out%5Bi%5D%5D +=1%0A%09%09print %22     0   1   2   3   4 predict value%22%0A%09%09for row_label, row in zip(self.labels, matrix):%0A%09%09%09print '%25s %5B%25s%5D' %25 (row_label, ' '.join('%2503s' %25 i for i in row))%0A%09%09print %22Expected%22
 %0Aif 
@@ -1768,25 +1768,75 @@
 int(
-nb.predict(nb.x%5B0%5D
+%22Overall correct percentage:%22,nb.crossValidate(confusion_matrux=True
 ))%0A

add confusion matrix ri naive bayes