demo.py 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import division
  2. import numpy as np
  3. from utils.ml import AnomalyDetection
  4. mo = [[0.0, 4.5], [0.0, 4.5], [11.6, 4.4], [12.2, 4.3], [1.4, 3.9], [1.4, 3.9], [2.5, 3.8], [0.1, 3.8], [0.5, 5.1], [0.7, 5.2], [0.7, 5.1], [0.0, 4.6], [0.0, 4.6]]
  5. m = np.transpose(np.array(mo))
  6. xu_ = np.mean(m[0,:])
  7. yu_ = np.mean(m[1,:])
  8. xr_ = np.sqrt(np.var(m[0,:]))
  9. yr_ = np.sqrt(np.var(m[1,:]))
  10. #
  11. # -- normalizing the matrix before computing covariance
  12. #
  13. mn = np.array([list( (m[0,:]-xu_)/xr_),list( (m[1,:]-yu_)/yr_)])
  14. cx = np.cov(mn)
  15. n = m.shape[0]
  16. test=[2.4,3.1]
  17. x = np.array(test)
  18. u = np.array([xu_,yu_])
  19. d = np.matrix(x - u)
  20. d.shape = (n,1)
  21. a = (2*(np.pi)**(n/2))*np.linalg.det(cx)**0.5
  22. b = np.exp((-0.5*np.transpose(d)) * (np.linalg.inv(cx)*d))
  23. print u.shape
  24. print cx.shape
  25. from scipy.stats import multivariate_normal
  26. xo= multivariate_normal.pdf(x,u,cx)
  27. yo= (b/a)[0,0]
  28. e= np.float64(0.05)
  29. print [yo,yo < e]
  30. print [xo,xo < e]
  31. ml = AnomalyDetection()
  32. end = int(len(mo)*.7)
  33. mu,sigma = ml.gParameters(mo)
  34. r = ml.gPx(mu,sigma,[test],0.05)
  35. for i in range(0,len(r)) :
  36. print ' *** ', mo[(i+end)],r[i]
  37. #for row in np.transpose(m):
  38. # print ",".join([str(value) for value in row])
  39. #-- We are ready to perform anomaly detection ...