return model.predict(x) if __name__=='__main__': vari,deli,m = 'cu','1712',7 db = DB() days = db.execute("select date from contract_daily where vari=%s and deli=%s order by date asc", (vari, deli))[30:] data = DataSet(m, 'direction') model = NaiveBayes(m) y_real = [] y_pred = [] for day in days: model.fit(*data.bootstrap(vari, deli, day, 300)) r = model.predict(data.get_x(vari, deli, day)) if r[0]>=r[1] and r[0]>=r[2]: r = 0 elif r[1]>=r[0] and r[1]>=r[2]: r = 1 else: r = 2 y_pred.append(r) y_real.append(data.get_y(vari, deli, day)) print (accuracy_score(y_real, y_pred)) print (y_real) print (y_pred)
for j in range(self.m): self.likelihood_tensor[y, j, x[j]] += 1 for y in range(self.y_classes): for x_dim in range(self.m): self.likelihood_tensor[y, x_dim] = [(self.likelihood_tensor[y,x_dim,x]+self.laplace)/(self.prior[y]+self.x_classes*self.laplace) for x in range(self.x_classes)] self.prior = np.array([(x+self.laplace)/(n+self.y_classes*self.laplace) for x in self.prior]) def predict(self, x): P = [1.] * self.y_classes for i in range(self.y_classes): P[i] = self.prior[i] for j in range(self.m): P[i] *= self.likelihood(i, j, x[j]) s = sum(P) P = [1.*x/s for x in P] res = {} for i in range(self.y_classes): res[i] = P[i] return res if __name__=='__main__': from dataSet import DataSet import datetime data = DataSet(5, 'direction') model = NaiveBayes(5) X,Y = data.bootstrap('cu', '1707', datetime.date(2017,6,6), n=300) model.fit(X, Y) print ('predict:', model.predict(data.get_x('cu', '1707', datetime.date(2017,6,6)))) print ('real:', data.get_y('cu', '1707', datetime.date(2017,6,6)))